dolibarr 22.0.5
societe.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5 * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2013-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
12 * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16 * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17 * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18 * Copyright (C) 2019-2025 Frédéric France <frederic.france@free.fr>
19 * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20 * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
21 * Copyright (C) 2023-2024 Alexandre Janniaux <alexandre.janniaux@gmail.com>
22 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
23 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
24 *
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 3 of the License, or
28 * (at your option) any later version.
29 *
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
34 *
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <https://www.gnu.org/licenses/>.
37 */
38
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
48require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
49require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
50
51
55class Societe extends CommonObject
56{
57 use CommonIncoterm;
59 use CommonPeople;
60
64 public $module = 'societe';
65
69 public $element = 'societe';
70
74 public $table_element = 'societe';
75
79 public $fk_element = 'fk_soc';
80
84 public $fieldsforcombobox = 'nom,name_alias';
85
89 protected $childtables = array(
90 'supplier_proposal' => array('name' => 'SupplierProposal'),
91 'propal' => array('name' => 'Proposal'),
92 'commande' => array('name' => 'Order'),
93 'facture' => array('name' => 'Invoice'),
94 'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
95 'contrat' => array('name' => 'Contract'),
96 'fichinter' => array('name' => 'Fichinter'),
97 'facture_fourn' => array('name' => 'SupplierInvoice'),
98 'commande_fournisseur' => array('name' => 'SupplierOrder'),
99 'projet' => array('name' => 'Project'),
100 'expedition' => array('name' => 'Shipment'),
101 'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
102 );
103
108 protected $childtablesoncascade = array(
109 'societe_prices',
110 'product_fournisseur_price',
111 'product_customer_price_log',
112 'product_customer_price',
113 '@Contact:/contact/class/contact.class.php:fk_soc',
114 'adherent',
115 'societe_account',
116 'societe_rib',
117 'societe_remise',
118 'societe_remise_except',
119 'societe_commerciaux',
120 'categorie',
121 'notify',
122 'notify_def',
123 'actioncomm',
124 );
125
129 public $picto = 'company';
130
135 public $restrictiononfksoc = 1;
136
141 public $SupplierCategories = array();
142
147 public $prefixCustomerIsRequired;
148
178 public $fields = array(
179 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
180 'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
181 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
182 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
183 'nom' => array('type' => 'varchar(128)', 'length' => 128, 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1, 'csslist' => 'tdoverflowmax150'),
184 'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
185 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
186 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
187 'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
188 'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
189 'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
190 'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
191 'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
192 'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
193 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
194 'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
195 'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
196 'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
197 'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
198 'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
199 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
200 'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
201 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
202 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
203 'fk_typent' => array('type' => 'integer', 'label' => 'TypeOfCompany', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
204 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
205 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
206 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
207 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
208 'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
209 'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
210 'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
211 'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
212 'tva_intra' => array('type' => 'varchar(20)', 'label' => 'Tva intra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
213 'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
214 'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
215 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225),
216 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230),
217 'prefix_comm' => array('type' => 'varchar(5)', 'label' => 'Prefix comm', 'enabled' => "getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible' => -1, 'position' => 235),
218 'client' => array('type' => 'tinyint(4)', 'label' => 'Client', 'enabled' => 1, 'visible' => -1, 'position' => 240),
219 'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Fournisseur', 'enabled' => 1, 'visible' => -1, 'position' => 245),
220 'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
221 'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
222 'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
223 'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
224 'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
225 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
226 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
227 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
228 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
229 'mode_reglement' => array('type' => 'tinyint(4)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
230 'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
231 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
232 'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
233 'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
234 'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
235 '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),
236 '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),
237 'fk_shipping_method' => array('type' => 'integer', 'label' => 'Fk shipping method', 'enabled' => 1, 'visible' => -1, 'position' => 330),
238 'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'Tva assuj', 'enabled' => 1, 'visible' => -1, 'position' => 335),
239 'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax1 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 340),
240 'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'Localtax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
241 'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax2 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 350),
242 'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'Localtax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
243 'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
244 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
245 'price_level' => array('type' => 'integer', 'label' => 'Price level', 'enabled' => '$conf->global->PRODUIT_MULTIPRICES || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES") || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES")', 'visible' => -1, 'position' => 365),
246 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
247 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
248 'fk_barcode_type' => array('type' => 'integer', 'label' => 'Fk barcode type', 'enabled' => 1, 'visible' => -1, 'position' => 405),
249 'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
250 'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
251 'fk_incoterms' => array('type' => 'integer', 'label' => 'Fk incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 425),
252 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
253 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
254 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
255 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
256 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
257 'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
258 'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
259 'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
260 'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
261 'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
262 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
263 );
264
268 public $entity;
269
276 public $nom;
277
281 public $name;
282
287 public $name_alias;
288
292 public $particulier;
293
298 public $status = 1;
299
303 public $region_code;
304
308 public $region;
309
313 public $country_id;
314
320 public $departement_code;
321
327 public $departement;
328
334 public $pays;
335
340 public $phone;
345 public $phone_mobile;
350 public $fax;
351
356 public $email;
357
362 public $no_email;
363
369 public $skype;
370
376 public $twitter;
377
383 public $facebook;
384
390 public $linkedin;
391
396 public $url;
397
402 public $barcode;
403
404 // 6 professional id (usage depends on country)
405
410 public $idprof1;
411
417 public $siren;
418
419
424 public $idprof2;
425
431 public $siret;
432
437 public $idprof3;
438
444 public $ape;
445
450 public $idprof4;
451
456 public $idprof5;
457
462 public $idprof6;
463
468 public $idprof7;
469
474 public $idprof8;
475
480 public $idprof9;
481
486 public $idprof10;
487
492 public $socialobject;
493
497 public $prefix_comm;
498
502 public $tva_assuj = 1;
503
507 public $tva_intra;
508
512 public $vat_reverse_charge = 0;
513
514 // Local taxes
518 public $localtax1_assuj;
522 public $localtax1_value;
526 public $localtax2_assuj;
530 public $localtax2_value;
531
535 public $managers;
536
540 public $capital;
541
545 public $typent_id = 0;
549 public $typent_code;
553 public $effectif;
557 public $effectif_id = 0;
561 public $forme_juridique_code = 0;
566 public $forme_juridique;
567
571 public $remise_percent;
575 public $remise_supplier_percent;
576
580 public $mode_reglement_id;
584 public $cond_reglement_id;
588 public $deposit_percent;
592 public $mode_reglement_supplier_id;
596 public $cond_reglement_supplier_id;
600 public $transport_mode_supplier_id;
601
605 public $fk_prospectlevel;
606
610 public $name_bis;
611
617 public $user_modification;
618
624 public $user_creation;
625
630 public $client = 0;
631
636 public $prospect = 0;
637
642 public $fournisseur;
643
648 public $code_client;
649
654 public $code_fournisseur;
655
660 public $code_compta_client;
661
666 public $accountancy_code_customer_general;
667
672 public $accountancy_code_customer;
673
678 public $code_compta_fournisseur;
679
684 public $accountancy_code_supplier_general;
685
690 public $accountancy_code_supplier;
691
696 public $code_compta_product;
697
703 public $note;
704
709 public $note_private;
710
715 public $note_public;
716
721 public $stcomm_id;
722
727 public $stcomm_picto;
728
733 public $status_prospect_label;
734
739 public $price_level;
740
744 public $outstanding_limit;
745
749 public $order_min_amount;
750
754 public $supplier_order_min_amount;
755
760 public $commercial_id;
761
766 public $parent;
767
772 public $default_lang;
773
777 public $ref;
778
784 public $ref_ext;
785
789 public $ip;
790
797 public $import_key;
798
803 public $webservices_url;
804
809 public $webservices_key;
810
814 public $logo;
815
819 public $logo_small;
820
824 public $logo_mini;
825
829 public $logo_squarred;
830
834 public $logo_squarred_small;
835
839 public $logo_squarred_mini;
840
844 public $accountancy_code_sell;
845
849 public $accountancy_code_buy;
850
854 public $currency_code;
855
856 // Multicurrency
860 public $fk_multicurrency;
861
865 public $multicurrency_code;
866
867 // Warehouse
871 public $fk_warehouse;
872
876 public $termsofsale;
877
878
879 // Fields loaded by fetchPartnerships()
880
884 public $partnerships = array();
885
886
890 public $bank_account;
891
897 public $code_compta;
898
899
900 const STATUS_CEASED = 0;
901 const STATUS_INACTIVITY = 1;
902
906 const NO_CUSTOMER = 0;
907
911 const CUSTOMER = 1;
912
916 const PROSPECT = 2;
917
922
926 const NO_SUPPLIER = 0;
927
931 const SUPPLIER = 1;
932
938 protected function deprecatedProperties()
939 {
940 return
941 array(
942 'code_compta' => 'code_compta_client',
943 )
944 + parent::deprecatedProperties();
945 }
946
947
948
954 public function __construct($db)
955 {
956 $this->db = $db;
957
958 $this->ismultientitymanaged = 1;
959 $this->isextrafieldmanaged = 1;
960 $this->client = 0;
961 $this->prospect = 0;
962 $this->fournisseur = 0;
963 $this->typent_id = 0;
964 $this->effectif_id = 0;
965 $this->forme_juridique_code = 0;
966 $this->tva_assuj = 1;
967 $this->vat_reverse_charge = 0;
968 $this->status = 1;
969
970 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
971 $this->fields['address']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
972 $this->fields['zip']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
973 $this->fields['town']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
974 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
975 }
976 }
977
978
987 public function create(User $user, $notrigger = 0)
988 {
989 global $langs, $conf;
990
991 $error = 0;
992
993 // Clean parameters
994 if (empty($this->status)) {
995 $this->status = 0;
996 }
997 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
998 $this->setUpperOrLowerCase();
999 $this->nom = $this->name; // For backward compatibility
1000
1001 if (empty($this->client)) {
1002 $this->client = 0;
1003 }
1004 if (empty($this->fournisseur)) {
1005 $this->fournisseur = 0;
1006 }
1007 $this->import_key = trim((string) $this->import_key);
1008
1009 $this->code_compta_client = trim($this->code_compta_client ?? '');
1010
1011 $this->accountancy_code_customer_general = trim($this->accountancy_code_customer_general ?? '');
1012 if ($this->accountancy_code_customer_general === '-1') {
1013 $this->accountancy_code_customer_general = '';
1014 }
1015 $this->accountancy_code_customer = trim((string) $this->code_compta_client);
1016 $this->accountancy_code_supplier_general = trim($this->accountancy_code_supplier_general ?? '');
1017 if ($this->accountancy_code_supplier_general === '-1') {
1018 $this->accountancy_code_supplier_general = '';
1019 }
1020 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
1021 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1022 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1023
1024 if (!empty($this->multicurrency_code)) {
1025 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1026 }
1027 if (empty($this->fk_multicurrency)) {
1028 $this->multicurrency_code = '';
1029 $this->fk_multicurrency = 0;
1030 }
1031
1032 dol_syslog(get_class($this)."::create ".$this->name);
1033
1034 $now = dol_now();
1035
1036 if (empty($this->date_creation)) {
1037 $this->date_creation = $now;
1038 }
1039
1040 $this->db->begin();
1041
1042 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1043 if ($this->code_client == -1 || $this->code_client === 'auto') {
1044 $this->get_codeclient($this, 0);
1045 }
1046 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1047 $this->get_codefournisseur($this, 1);
1048 }
1049
1050 // Check more parameters (including mandatory setup
1051 // If error, this->errors[] is filled
1052 $result = $this->verify();
1053
1054 if ($result >= 0) {
1055 $this->entity = setEntity($this);
1056
1057 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
1058 $sql .= "nom";
1059 $sql .= ", name_alias";
1060 $sql .= ", entity";
1061 $sql .= ", datec";
1062 $sql .= ", fk_user_creat";
1063 $sql .= ", fk_typent";
1064 $sql .= ", canvas";
1065 $sql .= ", status";
1066 $sql .= ", ref_ext";
1067 $sql .= ", fk_stcomm";
1068 $sql .= ", fk_incoterms";
1069 $sql .= ", location_incoterms";
1070 $sql .= ", import_key";
1071 $sql .= ", fk_multicurrency";
1072 $sql .= ", multicurrency_code";
1073 $sql .= ", ip";
1074 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1075 $sql .= ", vat_reverse_charge";
1076 $sql .= ", accountancy_code_buy";
1077 $sql .= ", accountancy_code_sell";
1078 }
1079 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
1080 $sql .= " '".$this->db->escape($this->name_alias)."',";
1081 $sql .= " ".((int) $this->entity).",";
1082 $sql .= " '".$this->db->idate($this->date_creation)."'";
1083 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
1084 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
1085 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
1086 $sql .= ", ".((int) $this->status);
1087 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1088 $sql .= ", 0";
1089 $sql .= ", ".(int) $this->fk_incoterms;
1090 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1091 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1092 $sql .= ", ".(int) $this->fk_multicurrency;
1093 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1094 $sql .= ", '".$this->db->escape($this->ip)."'";
1095 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1096 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1097 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1098 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1099 }
1100 $sql .= ")";
1101
1102 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1103
1104 $result = $this->db->query($sql);
1105 if ($result) {
1106 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1107
1108 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1109
1110 // update accountancy for this entity
1111 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1112 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1113
1114 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1115 $sql .= " fk_soc";
1116 $sql .= ", entity";
1117 $sql .= ", vat_reverse_charge";
1118 $sql .= ", accountancy_code_customer_general";
1119 $sql .= ", accountancy_code_customer";
1120 $sql .= ", accountancy_code_supplier_general";
1121 $sql .= ", accountancy_code_supplier";
1122 $sql .= ", accountancy_code_buy";
1123 $sql .= ", accountancy_code_sell";
1124 $sql .= ") VALUES (";
1125 $sql .= $this->id;
1126 $sql .= ", ".((int) $conf->entity);
1127 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1128 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1129 $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1130 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1131 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1132 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1133 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1134 $sql .= ")";
1135 $result = $this->db->query($sql);
1136 if (!$result) {
1137 $error++;
1138 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1139 }
1140 }
1141
1142 // Ajout du commercial affecte
1143 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1144 $this->add_commercial($user, $this->commercial_id);
1145 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1146 // si un commercial cree un client il lui est affecte automatiquement
1147 $this->add_commercial($user, $user->id);
1148 }
1149
1150 if ($ret >= 0) {
1151 if (! $notrigger) {
1152 // Call trigger
1153 $result = $this->call_trigger('COMPANY_CREATE', $user);
1154 if ($result < 0) {
1155 $error++;
1156 }
1157 // End call triggers
1158 }
1159 } else {
1160 $error++;
1161 }
1162
1163 if (!$error) {
1164 dol_syslog(get_class($this)."::Create success id=".$this->id);
1165 $this->db->commit();
1166 return $this->id;
1167 } else {
1168 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1169 $this->db->rollback();
1170 return -4;
1171 }
1172 } else {
1173 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1174 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1175 $result = -1;
1176 } else {
1177 $this->error = $this->db->lasterror();
1178 $result = -2;
1179 }
1180 $this->db->rollback();
1181 return $result;
1182 }
1183 } else {
1184 $this->db->rollback();
1185 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1186 return -3;
1187 }
1188 }
1189
1190
1191 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1201 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1202 {
1203 $error = 0;
1204
1205 $this->db->begin();
1206
1207 // phpcs:enable
1208 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1209 $contact = new Contact($this->db);
1210
1211 $contact->name = $this->name_bis;
1212 $contact->firstname = $this->firstname;
1213 $contact->civility_id = $this->civility_id;
1214 $contact->socid = $this->id; // fk_soc
1215 $contact->statut = 1; // deprecated
1216 $contact->status = 1;
1217 $contact->priv = 0;
1218 $contact->country_id = $this->country_id;
1219 $contact->state_id = $this->state_id;
1220 $contact->address = $this->address;
1221 $contact->email = $this->email;
1222 $contact->zip = $this->zip;
1223 $contact->town = $this->town;
1224 $this->setUpperOrLowerCase();
1225 $contact->phone_pro = $this->phone;
1226 if (getDolGlobalString('CONTACTS_DEFAULT_ROLES')) {
1227 $contact->roles = explode(',', getDolGlobalString('CONTACTS_DEFAULT_ROLES'));
1228 }
1229
1230 $contactId = $contact->create($user, $notrigger);
1231 if ($contactId < 0) {
1232 $error++;
1233 $this->setErrorsFromObject($contact);
1234 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1235 }
1236
1237 if (empty($error) && is_array($tags) && !empty($tags)) {
1238 $result = $contact->setCategories($tags);
1239 if ($result < 0) {
1240 $error++;
1241 $this->setErrorsFromObject($contact);
1242 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1243 $contactId = $result;
1244 }
1245 }
1246
1247 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1248 $result = $contact->setNoEmail($no_email);
1249 if ($result < 0) {
1250 $this->setErrorsFromObject($contact);
1251 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1252 $contactId = $result;
1253 }
1254 }
1255
1256 if (empty($error)) {
1257 dol_syslog(get_class($this)."::create_individual success");
1258 $this->db->commit();
1259 } else {
1260 $this->db->rollback();
1261 }
1262
1263 return $contactId;
1264 }
1265
1272 public function verify()
1273 {
1274 global $langs, $mysoc;
1275
1276 $error = 0;
1277 $this->errors = array();
1278
1279 $result = 0;
1280 $this->name = trim($this->name);
1281 $this->nom = $this->name; // For backward compatibility
1282
1283 if (!$this->name) {
1284 $this->errors[] = 'ErrorBadThirdPartyName';
1285 $result = -2;
1286 }
1287
1288 if ($this->client) {
1289 $rescode = $this->check_codeclient();
1290 if ($rescode != 0 && $rescode != -5) {
1291 if ($rescode == -1) {
1292 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1293 } elseif ($rescode == -2) {
1294 $this->errors[] = 'ErrorCustomerCodeRequired';
1295 } elseif ($rescode == -3) {
1296 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1297 } elseif ($rescode == -4) {
1298 $this->errors[] = 'ErrorPrefixRequired';
1299 } else {
1300 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1301 }
1302
1303 $result = -3;
1304 }
1305 }
1306
1307 if ($this->fournisseur) {
1308 $rescode = $this->check_codefournisseur();
1309 if ($rescode != 0 && $rescode != -5) {
1310 if ($rescode == -1) {
1311 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1312 } elseif ($rescode == -2) {
1313 $this->errors[] = 'ErrorSupplierCodeRequired';
1314 } elseif ($rescode == -3) {
1315 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1316 } elseif ($rescode == -4) {
1317 $this->errors[] = 'ErrorPrefixRequired';
1318 } else {
1319 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1320 }
1321 $result = -3;
1322 }
1323 }
1324
1325 // Check for duplicate or mandatory fields defined into setup
1326 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1327 foreach ($array_to_check as $key) {
1328 $keymin = strtolower($key);
1329 $keyfield_db = $keymin;
1330 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1331 $keymin = 'code_compta_client';
1332 $keyfield_db = 'code_compta';
1333 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1334 $keymin = 'code_compta_fournisseur';
1335 $keyfield_db = 'code_compta_fournisseur';
1336 }
1337 $i = (int) preg_replace('/[^0-9]/', '', $key);
1338 $vallabel = $this->$keymin;
1339
1340 if ($i > 0) {
1341 if ($mysoc != null && $this->isACompany()) {
1342 // Check for mandatory prof id (but only if country is same than ours)
1343 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1344 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1345 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1346 $langs->load("errors");
1347 $error++;
1348 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1349 }
1350 }
1351 }
1352
1353 // Check for unicity on profid
1354 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1355 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1356 $langs->load("errors");
1357 $error++;
1358 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1359 }
1360 }
1361 } else {
1362 //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1363 //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1364 if ($key == 'EMAIL') {
1365 // Check for mandatory
1366 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1367 $langs->load("errors");
1368 $error++;
1369 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1370 }
1371
1372 // Check for unicity
1373 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1374 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1375 $langs->load("errors");
1376 $error++;
1377 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1378 }
1379 }
1380 } elseif ($key == 'TVA_INTRA') {
1381 // Check for unicity
1382 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1383 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1384 $langs->load("errors");
1385 $error++;
1386 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1387 }
1388 }
1389 if ($this->tva_assuj && !$vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_MANDATORY')) {
1390 $langs->load("errors");
1391 $error++;
1392 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('VATIntra')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1393 }
1394 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1395 // Check for unicity
1396 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1397 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1398 $langs->loadLangs(array("errors", 'compta'));
1399 $error++;
1400 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1401 }
1402 }
1403
1404 // Check for mandatory
1405 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1406 $langs->loadLangs(array("errors", 'compta'));
1407 $error++;
1408 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1409 }
1410 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1411 // Check for unicity
1412 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1413 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1414 $langs->loadLangs(array("errors", 'compta'));
1415 $error++;
1416 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1417 }
1418 }
1419
1420 // Check for mandatory
1421 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1422 $langs->loadLangs(array("errors", 'compta'));
1423 $error++;
1424 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1425 }
1426 }
1427 }
1428 }
1429
1430 if ($error) {
1431 $result = -4;
1432 }
1433
1434 return $result;
1435 }
1436
1449 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1450 {
1451 global $langs, $conf, $hookmanager;
1452
1453 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1454
1455 if (empty($id)) {
1456 $id = $this->id;
1457 }
1458 if (empty($this->country_id) && !empty($this->country_code)) {
1459 $this->country_id = dol_getIdFromCode($this->db, $this->country_code, 'c_country', 'code', 'rowid');
1460 }
1461
1462 if (empty($this->country_id) && !empty($this->country_code)) {
1463 $country_id = getCountry($this->country_code, '3');
1464 $this->country_id = is_int($country_id) ? $country_id : 0;
1465 }
1466
1467 $error = 0;
1468
1469 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1470
1471 $now = dol_now();
1472
1473 // Clean parameters
1474 $this->id = $id;
1475 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1476 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1477 $this->nom = $this->name; // For backward compatibility
1478 $this->name_alias = trim((string) $this->name_alias);
1479 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1480 $this->address = trim((string) $this->address);
1481 $this->zip = trim((string) $this->zip);
1482 $this->town = trim((string) $this->town);
1483 $this->state_id = (is_numeric($this->state_id)) ? (int) $this->state_id : 0;
1484 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1485 $this->phone = trim((string) $this->phone);
1486 $this->phone = preg_replace("/\s/", "", $this->phone);
1487 $this->phone = preg_replace("/\./", "", $this->phone);
1488 $this->phone_mobile = trim((string) $this->phone_mobile);
1489 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1490 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1491 $this->fax = trim((string) $this->fax);
1492 $this->fax = preg_replace("/\s/", "", $this->fax);
1493 $this->fax = preg_replace("/\./", "", $this->fax);
1494 $this->email = trim((string) $this->email);
1495 $this->url = $this->url ? clean_url($this->url, 0) : '';
1496 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1497 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1498 $this->idprof1 = trim((string) $this->idprof1);
1499 $this->idprof2 = trim((string) $this->idprof2);
1500 $this->idprof3 = trim((string) $this->idprof3);
1501 $this->idprof4 = trim((string) $this->idprof4);
1502 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1503 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1504 $this->prefix_comm = trim((string) $this->prefix_comm);
1505 $this->outstanding_limit = price2num($this->outstanding_limit);
1506 $this->order_min_amount = price2num($this->order_min_amount);
1507 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1508
1509 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1510 $this->tva_intra = trim((string) $this->tva_intra);
1511 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1512 if (empty($this->status)) {
1513 $this->status = 0;
1514 }
1515
1516 if (!empty($this->multicurrency_code)) {
1517 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1518 }
1519 if (empty($this->fk_multicurrency)) {
1520 $this->multicurrency_code = '';
1521 $this->fk_multicurrency = 0;
1522 }
1523
1524 // Local taxes
1525 $this->localtax1_assuj = (int) trim((string) $this->localtax1_assuj);
1526 $this->localtax2_assuj = (int) trim((string) $this->localtax2_assuj);
1527
1528 $this->localtax1_value = trim($this->localtax1_value);
1529 $this->localtax2_value = trim($this->localtax2_value);
1530
1531 $this->capital = ($this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1532
1533 $this->effectif_id = (int) $this->effectif_id;
1534 $this->forme_juridique_code = (int) $this->forme_juridique_code;
1535
1536 //Gencod
1537 $this->barcode = trim((string) $this->barcode);
1538
1539 // For automatic creation
1540 if ($this->code_client == -1 || $this->code_client === 'auto') {
1541 $this->get_codeclient($this, 0);
1542 }
1543 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1544 $this->get_codefournisseur($this, 1);
1545 }
1546
1547 $this->accountancy_code_customer_general = trim((string) $this->accountancy_code_customer_general);
1548 if ($this->accountancy_code_customer_general === '-1') {
1549 $this->accountancy_code_customer_general = '';
1550 }
1551 $this->code_compta_client = trim((string) $this->code_compta_client);
1552 $this->accountancy_code_supplier_general = trim((string) $this->accountancy_code_supplier_general);
1553 if ($this->accountancy_code_supplier_general === '-1') {
1554 $this->accountancy_code_supplier_general = '';
1555 }
1556 $this->code_compta_fournisseur = trim((string) $this->code_compta_fournisseur);
1557
1558 // Check parameters. More tests are done later in the ->verify()
1559 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1560 $langs->load("errors");
1561 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1562 return -1;
1563 }
1564
1565 $customer = false;
1566 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1567 // If $allowmodcodeclient is set and value is not set, we generate it
1568 if (empty($this->code_compta_client)) {
1569 $ret = $this->get_codecompta('customer');
1570 if ($ret < 0) {
1571 return -1;
1572 }
1573 }
1574
1575 $customer = true;
1576 }
1577
1578 $supplier = false;
1579 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1580 // If $allowmodcodefournisseur is set and value is not set, we generate it
1581 if (empty($this->code_compta_fournisseur)) {
1582 $ret = $this->get_codecompta('supplier');
1583 if ($ret < 0) {
1584 return -1;
1585 }
1586 }
1587
1588 $supplier = true;
1589 }
1590
1591 //Web services
1592 $this->webservices_url = empty($this->webservices_url) ? '' : clean_url($this->webservices_url, 0);
1593 $this->webservices_key = trim((string) $this->webservices_key);
1594
1595 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1596 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1597
1598 //Incoterms
1599 $this->fk_incoterms = (int) $this->fk_incoterms;
1600 $this->location_incoterms = trim((string) $this->location_incoterms);
1601
1602 $this->db->begin();
1603
1604 // Check name is required and codes are ok or unique.
1605 // If error, this->errors[] is filled
1606 $result = 0;
1607 if ($action != 'add' && $action != 'merge') {
1608 // We don't check when update called during a create because verify was already done.
1609 // 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
1610 $result = $this->verify();
1611
1612 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1613 // So we can update record that were using and old numbering rule.
1614 if (is_array($this->errors)) {
1615 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1616 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1617 unset($this->errors[$key]); // Remove error message
1618 }
1619 }
1620 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1621 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1622 unset($this->errors[$key]); // Remove error message
1623 }
1624 }
1625 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1626 $result = 0;
1627 }
1628 }
1629 }
1630 $this->setUpperOrLowerCase();
1631 if ($result >= 0) {
1632 dol_syslog(get_class($this)."::update verify ok or not done");
1633
1634 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1635 $sql .= "entity = ".((int) $this->entity);
1636 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1637 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1638 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1639 $sql .= ",address = '".$this->db->escape($this->address)."'";
1640
1641 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1642 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1643
1644 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1645 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1646
1647 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1648 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1649 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1650 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1651 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1652 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1653
1654 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1655
1656 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1657 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1658
1659 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1660 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1661 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1662 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1663 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1664 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1665
1666 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape((string) $this->tva_assuj)."'" : "null");
1667 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1668 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1669 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape((string) $this->vat_reverse_charge) . "'" : 0);
1670 }
1671 $sql .= ",status = ".((int) $this->status);
1672
1673 // Local taxes
1674 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape((string) $this->localtax1_assuj)."'" : "null");
1675 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape((string) $this->localtax2_assuj)."'" : "null");
1676 if ($this->localtax1_assuj == 1) {
1677 if ($this->localtax1_value != '') {
1678 $sql .= ", localtax1_value = ".((float) $this->localtax1_value);
1679 } else {
1680 $sql .= ", localtax1_value = 0.000";
1681 }
1682 } else {
1683 $sql .= ",localtax1_value =0.000";
1684 }
1685
1686 if ($this->localtax2_assuj == 1) {
1687 if ($this->localtax2_value != '') {
1688 $sql .= ",localtax2_value = ".((float) $this->localtax2_value);
1689 } else {
1690 $sql .= ",localtax2_value = 0.000";
1691 }
1692 } else {
1693 $sql .= ",localtax2_value = 0.000";
1694 }
1695
1696 $sql .= ",capital = ".($this->capital === null ? "null" : $this->capital);
1697
1698 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1699
1700 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1701 if (isset($this->stcomm_id)) {
1702 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1703 }
1704 if (isset($this->typent_id)) {
1705 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1706 }
1707
1708 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape((string) $this->forme_juridique_code)."'" : "null");
1709
1710 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape((string) $this->mode_reglement_id)."'" : "null");
1711 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape((string) $this->cond_reglement_id)."'" : "null");
1712 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape((string) $this->deposit_percent)."'" : "null");
1713 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape((string) $this->transport_mode_id)."'" : "null");
1714 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape((string) $this->mode_reglement_supplier_id)."'" : "null");
1715 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape((string) $this->cond_reglement_supplier_id)."'" : "null");
1716 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape((string) $this->transport_mode_supplier_id)."'" : "null");
1717 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape((string) $this->shipping_method_id)."'" : "null");
1718
1719 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1720 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1721 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1722 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1723 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1724 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1725 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1726 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1727 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1728 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1729 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1730 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1731 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1732 if ($customer) {
1733 $sql .= ", accountancy_code_customer_general = ".(!empty($this->accountancy_code_customer_general) ? "'".$this->db->escape($this->accountancy_code_customer_general)."'" : "null");
1734 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1735 }
1736
1737 if ($supplier) {
1738 $sql .= ", accountancy_code_supplier_general = ".(!empty($this->accountancy_code_supplier_general) ? "'".$this->db->escape($this->accountancy_code_supplier_general)."'" : "null");
1739 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1740 }
1741 }
1742 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1743 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1744
1745 //Incoterms
1746 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1747 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1748
1749 if ($customer) {
1750 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1751 }
1752
1753 if ($supplier) {
1754 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1755 }
1756 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1757 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1758 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1759 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1760 $sql .= " WHERE rowid = ".(int) $id;
1761
1762 $resql = $this->db->query($sql);
1763 if ($resql) {
1764 if (is_object($this->oldcopy)) { // If we have information on old values
1765 if ($this->oldcopy->country_id != $this->country_id) {
1766 unset($this->country_code);
1767 unset($this->country);
1768 }
1769 if ($this->oldcopy->state_id != $this->state_id) {
1770 unset($this->state_code);
1771 unset($this->state);
1772 }
1773 } else {
1774 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1775 unset($this->country);
1776 unset($this->state_code);
1777 unset($this->state);
1778 }
1779
1780 $nbrowsaffected = $this->db->affected_rows($resql);
1781
1782 if (!$error && $nbrowsaffected) {
1783 // Update information on linked member if it is an update
1784 if (!$nosyncmember && isModEnabled('member')) {
1785 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1786
1787 dol_syslog(get_class($this)."::update update linked member");
1788
1789 $lmember = new Adherent($this->db);
1790 $result = $lmember->fetch(0, '0', $this->id);
1791
1792 if ($result > 0) {
1793 $lmember->company = $this->name;
1794 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1795 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1796 $lmember->address = $this->address;
1797 $lmember->zip = $this->zip;
1798 $lmember->town = $this->town;
1799 $lmember->email = $this->email;
1800 $lmember->socialnetworks = $this->socialnetworks;
1801 $lmember->phone = $this->phone;
1802 $lmember->state_id = $this->state_id;
1803 $lmember->country_id = $this->country_id;
1804 $lmember->default_lang = $this->default_lang;
1805
1806 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1807 if ($result < 0) {
1808 $this->error = $lmember->error;
1809 $this->errors = array_merge($this->errors, $lmember->errors);
1810 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1811 $error++;
1812 }
1813 } elseif ($result < 0) {
1814 $this->error = $lmember->error;
1815 $error++;
1816 }
1817 }
1818 }
1819
1820 $action = 'update';
1821
1822 // update accountancy for this entity
1823 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1824 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1825
1826 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1827 $sql .= " fk_soc";
1828 $sql .= ", entity";
1829 $sql .= ", vat_reverse_charge";
1830 $sql .= ", accountancy_code_customer_general";
1831 $sql .= ", accountancy_code_customer";
1832 $sql .= ", accountancy_code_supplier_general";
1833 $sql .= ", accountancy_code_supplier";
1834 $sql .= ", accountancy_code_buy";
1835 $sql .= ", accountancy_code_sell";
1836 $sql .= ") VALUES (";
1837 $sql .= $this->id;
1838 $sql .= ", ".((int) $conf->entity);
1839 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1840 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1841 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1842 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1843 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1844 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1845 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1846 $sql .= ")";
1847 $result = $this->db->query($sql);
1848 if (!$result) {
1849 $error++;
1850 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1851 }
1852 }
1853
1854 // Actions on extra fields
1855 if (!$error) {
1856 $result = $this->insertExtraFields();
1857 if ($result < 0) {
1858 $error++;
1859 }
1860 }
1861 // Actions on extra languages
1862 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1863 $result = $this->insertExtraLanguages();
1864 if ($result < 0) {
1865 $error++;
1866 }
1867 }
1868
1869 if (!$error && $call_trigger) {
1870 // Call trigger
1871 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1872 if ($result < 0) {
1873 $error++;
1874 }
1875 // End call triggers
1876 }
1877
1878 if (!$error) {
1879 dol_syslog(get_class($this)."::Update success");
1880 $this->db->commit();
1881 return 1;
1882 } else {
1883 $this->db->rollback();
1884 return -1;
1885 }
1886 } else {
1887 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1888 // Doublon
1889 $this->error = $langs->trans("ErrorDuplicateField");
1890 $result = -1;
1891 } else {
1892 $this->error = $this->db->lasterror();
1893 $result = -2;
1894 }
1895 $this->db->rollback();
1896 return $result;
1897 }
1898 } else {
1899 $this->db->rollback();
1900 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1901 return -3;
1902 }
1903 }
1904
1924 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1925 {
1926 global $langs;
1927 global $conf;
1928
1929 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)) {
1930 return -1;
1931 }
1932
1933 $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';
1934 $sql .= ', s.status, s.fk_warehouse';
1935 $sql .= ', s.price_level';
1936 $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1937 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1938 $sql .= ', s.socialnetworks';
1939 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1940 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1941 $sql .= ', s.capital, s.tva_intra';
1942 $sql .= ', s.fk_typent as typent_id';
1943 $sql .= ', s.fk_effectif as effectif_id';
1944 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1945 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1946 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1947 $sql .= ', s.accountancy_code_customer_general, s.code_compta';
1948 $sql .= ', s.accountancy_code_supplier_general, s.code_compta_fournisseur';
1949 $sql .= ', s.accountancy_code_buy, s.accountancy_code_sell';
1950 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1951 } else {
1952 $sql .= ', spe.accountancy_code_customer_general, spe.accountancy_code_customer as code_compta';
1953 $sql .= ', spe.accountancy_code_supplier_general, spe.accountancy_code_supplier as code_compta_fournisseur';
1954 $sql .= ', spe.accountancy_code_buy, spe.accountancy_code_sell';
1955 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1956 }
1957 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1958 $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';
1959 $sql .= ', s.fk_account, s.tva_assuj';
1960 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1961 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1962 $sql .= ', s.fk_shipping_method';
1963 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1964 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1965 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1966 $sql .= ', fj.libelle as forme_juridique';
1967 $sql .= ', e.libelle as effectif';
1968 $sql .= ', c.code as country_code, c.label as country';
1969 $sql .= ', d.code_departement as state_code, d.nom as state';
1970 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1971 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1972 $sql .= ', te.code as typent_code';
1973 $sql .= ', i.libelle as label_incoterms';
1974 if (!isModEnabled('multicompany')) {
1975 $sql .= ', s.remise_client, s.remise_supplier';
1976 } else {
1977 $sql .= ', sr.remise_client, sr2.remise_supplier';
1978 }
1979 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1980 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1981 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1982 }
1983 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1984 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1985 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1986 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1987 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1988 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1989 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1990 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1991 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1992 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1993 if (isModEnabled('multicompany')) {
1994 $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').'))';
1995 $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').'))';
1996 }
1997 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1998
1999 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
2000 if ($is_client) {
2001 $sql .= ' AND s.client > 0';
2002 }
2003 if ($is_supplier) {
2004 $sql .= ' AND s.fournisseur > 0';
2005 } // if both false, no test (the thirdparty can be client and/or supplier)
2006
2007 if ($rowid) {
2008 $sql .= ' AND s.rowid = '.((int) $rowid);
2009 }
2010 if ($ref) {
2011 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
2012 }
2013 if ($ref_alias) {
2014 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
2015 }
2016 if ($ref_ext) {
2017 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
2018 }
2019 if ($barcode) {
2020 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
2021 }
2022 if ($idprof1) {
2023 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
2024 }
2025 if ($idprof2) {
2026 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
2027 }
2028 if ($idprof3) {
2029 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
2030 }
2031 if ($idprof4) {
2032 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
2033 }
2034 if ($idprof5) {
2035 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
2036 }
2037 if ($idprof6) {
2038 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
2039 }
2040 if ($email) {
2041 $sql .= " AND s.email = '".$this->db->escape($email)."'";
2042 }
2043
2044 $resql = $this->db->query($sql);
2045 if ($resql) {
2046 $num = $this->db->num_rows($resql);
2047 if ($num > 1) {
2048 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2049 dol_syslog($this->error, LOG_ERR);
2050 $result = -2;
2051 } elseif ($num) { // $num = 1
2052 $obj = $this->db->fetch_object($resql);
2053
2054 $this->id = $obj->rowid;
2055 $this->entity = $obj->entity;
2056 $this->canvas = $obj->canvas;
2057
2058 $this->ref = $obj->name;
2059 $this->name = $obj->name;
2060 $this->nom = $obj->name; // deprecated
2061 $this->name_alias = $obj->name_alias;
2062 $this->ref_ext = $obj->ref_ext;
2063
2064 $this->date_creation = $this->db->jdate($obj->date_creation);
2065 $this->date_modification = $this->db->jdate($obj->date_modification);
2066 $this->user_creation_id = $obj->fk_user_creat;
2067 $this->user_modification_id = $obj->fk_user_modif;
2068
2069 $this->address = $obj->address;
2070 $this->zip = $obj->zip;
2071 $this->town = $obj->town;
2072
2073 $this->country_id = $obj->country_id;
2074 $this->country_code = $obj->country_id ? $obj->country_code : '';
2075 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
2076
2077 $this->state_id = $obj->state_id;
2078 $this->state_code = $obj->state_code;
2079 $this->region_id = $obj->region_id;
2080 $this->region_code = $obj->region_code;
2081 $this->state = ($obj->state != '-' ? $obj->state : '');
2082
2083 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
2084 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
2085 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
2086 $this->status_prospect_label = $label; // label status prospect
2087 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
2088
2089 $this->email = $obj->email;
2090 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
2091
2092 $this->url = $obj->url;
2093 $this->phone = $obj->phone;
2094 $this->phone_mobile = $obj->phone_mobile;
2095 $this->fax = $obj->fax;
2096
2097 $this->parent = $obj->parent;
2098
2099 $this->idprof1 = $obj->idprof1;
2100 $this->idprof2 = $obj->idprof2;
2101 $this->idprof3 = $obj->idprof3;
2102 $this->idprof4 = $obj->idprof4;
2103 $this->idprof5 = $obj->idprof5;
2104 $this->idprof6 = $obj->idprof6;
2105
2106 $this->capital = $obj->capital;
2107
2108 $this->code_client = $obj->code_client;
2109 $this->code_fournisseur = $obj->code_fournisseur;
2110
2111 $this->accountancy_code_customer_general = $obj->accountancy_code_customer_general;
2112 $this->code_compta_client = $obj->code_compta;
2113 $this->accountancy_code_supplier_general = $obj->accountancy_code_supplier_general;
2114 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
2115
2116 $this->barcode = $obj->barcode;
2117
2118 $this->tva_assuj = $obj->tva_assuj;
2119 $this->tva_intra = $obj->tva_intra;
2120
2121 if (!empty($obj->spe_vat_reverse_charge)) {
2122 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2123 } elseif (!empty($obj->soc_vat_reverse_charge)) {
2124 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2125 } else {
2126 $this->vat_reverse_charge = 0;
2127 }
2128
2129 $this->status = $obj->status;
2130
2131 // Local Taxes
2132 $this->localtax1_assuj = $obj->localtax1_assuj;
2133 $this->localtax2_assuj = $obj->localtax2_assuj;
2134
2135 $this->localtax1_value = $obj->localtax1_value;
2136 $this->localtax2_value = $obj->localtax2_value;
2137
2138 $this->typent_id = $obj->typent_id;
2139 $this->typent_code = $obj->typent_code;
2140
2141 $this->effectif_id = $obj->effectif_id;
2142 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2143
2144 $this->forme_juridique_code = $obj->forme_juridique_code;
2145 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2146
2147 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2148
2149 $this->prefix_comm = $obj->prefix_comm;
2150
2151 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2152 $this->remise_supplier_percent = $obj->remise_supplier;
2153
2154 $this->mode_reglement_id = $obj->mode_reglement;
2155 $this->cond_reglement_id = $obj->cond_reglement;
2156 $this->deposit_percent = $obj->deposit_percent;
2157 $this->transport_mode_id = $obj->transport_mode;
2158 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2159 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2160 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2161 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2162 $this->fk_account = $obj->fk_account;
2163
2164 $this->client = $obj->client;
2165 $this->fournisseur = $obj->fournisseur;
2166
2167 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2168 $this->note_private = $obj->note_private;
2169 $this->note_public = $obj->note_public;
2170 $this->model_pdf = $obj->model_pdf;
2171 $this->default_lang = $obj->default_lang;
2172 $this->logo = $obj->logo;
2173 $this->logo_squarred = $obj->logo_squarred;
2174
2175 $this->webservices_url = $obj->webservices_url;
2176 $this->webservices_key = $obj->webservices_key;
2177
2178 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2179 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2180
2181 $this->outstanding_limit = $obj->outstanding_limit;
2182 $this->order_min_amount = $obj->order_min_amount;
2183 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2184
2185 // multiprix
2186 $this->price_level = $obj->price_level;
2187
2188 // warehouse
2189 $this->fk_warehouse = $obj->fk_warehouse;
2190
2191 $this->import_key = $obj->import_key;
2192
2193 //Incoterms
2194 $this->fk_incoterms = $obj->fk_incoterms;
2195 $this->location_incoterms = $obj->location_incoterms;
2196 $this->label_incoterms = $obj->label_incoterms;
2197
2198 // multicurrency
2199 $this->fk_multicurrency = $obj->fk_multicurrency;
2200 $this->multicurrency_code = $obj->multicurrency_code;
2201
2202 // pdf
2203 $this->model_pdf = $obj->model_pdf;
2204 $this->last_main_doc = $obj->last_main_doc;
2205
2206 $result = $this->id;
2207
2208 // fetch optionals attributes and labels
2209 $this->fetch_optionals();
2210 } else {
2211 $result = 0;
2212 }
2213
2214 $this->db->free($resql);
2215 } else {
2216 $this->error = $this->db->lasterror();
2217 $this->errors[] = $this->db->lasterror();
2218 $result = -3;
2219 }
2220
2221 // Use first price level if level not defined for third party
2222 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->price_level)) {
2223 $this->price_level = 1;
2224 }
2225
2226 return $result;
2227 }
2228
2249 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
2250 {
2251 // A rowid is known, it is a unique key so we found it
2252 if ($rowid) {
2253 return $rowid;
2254 }
2255
2256 dol_syslog(get_class($this)."::findNearest", LOG_DEBUG);
2257 $tmpthirdparty = new Societe($this->db);
2258
2259 // We try to find the thirdparty with exact matching on all fields
2260 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2261 if ($result != 0) {
2262 return $result;
2263 }
2264
2265 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2266 dol_syslog("Thirdparty not found with exact match so we try barcode search", LOG_DEBUG);
2267 if ($barcode) {
2268 $result = $tmpthirdparty->fetch(0, '', '', $barcode, '', '', '', '', '', '', '', '', $is_client, $is_supplier);
2269 if ($result != 0) {
2270 return $result;
2271 }
2272 }
2273
2274 $sqlstart = "SELECT s.rowid as id FROM ".MAIN_DB_PREFIX."societe as s";
2275 $sqlstart .= ' WHERE s.entity IN ('.getEntity($this->element).')';
2276 if ($is_client) {
2277 $sqlstart .= ' AND s.client > 0';
2278 }
2279 if ($is_supplier) {
2280 $sqlstart .= ' AND s.fournisseur > 0';
2281 } // if both false, no test (the thirdparty can be client and/or supplier)
2282
2283 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2284 dol_syslog("Thirdparty not found with barcode search so we try profids search", LOG_DEBUG);
2285 $sqlprof = "";
2286 if ($idprof1) {
2287 $sqlprof .= " s.siren = '".$this->db->escape($idprof1)."'";
2288 }
2289 if ($idprof2) {
2290 if ($sqlprof) {
2291 $sqlprof .= " OR";
2292 }
2293 $sqlprof .= " s.siret = '".$this->db->escape($idprof2)."'";
2294 }
2295 if ($idprof3) {
2296 if ($sqlprof) {
2297 $sqlprof .= " OR";
2298 }
2299 $sqlprof .= " s.ape = '".$this->db->escape($idprof3)."'";
2300 }
2301 if ($idprof4) {
2302 if ($sqlprof) {
2303 $sqlprof .= " OR";
2304 }
2305 $sqlprof .= " s.idprof4 = '".$this->db->escape($idprof4)."'";
2306 }
2307 if ($idprof5) {
2308 if ($sqlprof) {
2309 $sqlprof .= " OR";
2310 }
2311 $sqlprof .= " s.idprof5 = '".$this->db->escape($idprof5)."'";
2312 }
2313 if ($idprof6) {
2314 if ($sqlprof) {
2315 $sqlprof .= " OR";
2316 }
2317 $sqlprof .= " s.idprof6 = '".$this->db->escape($idprof6)."'";
2318 }
2319
2320 if ($sqlprof) {
2321 $sqlprofquery = $sqlstart . " AND (".$sqlprof." )";
2322 $resql = $this->db->query($sqlprofquery);
2323 if ($resql) {
2324 $num = $this->db->num_rows($resql);
2325 if ($num > 1) {
2326 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2327 dol_syslog($this->error, LOG_ERR);
2328 $result = -2;
2329 } elseif ($num) {
2330 $obj = $this->db->fetch_object($resql);
2331 $result = $obj->id;
2332 } else {
2333 $result = 0;
2334 }
2335 } else {
2336 $this->error = $this->db->lasterror();
2337 $this->errors[] = $this->db->lasterror();
2338 $result = -3;
2339 }
2340 if ($result != 0) {
2341 return $result;
2342 }
2343 }
2344
2345 // Then search on email (+ restriction on is_client and is_supplier)
2346 dol_syslog("Thirdparty not found with profids search so we try email search", LOG_DEBUG);
2347 if ($email) {
2348 $result = $tmpthirdparty->fetch(0, '', '', '', '', '', '', '', '', '', $email, '', $is_client, $is_supplier);
2349 if ($result != 0) {
2350 return $result;
2351 }
2352 }
2353
2354 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2355 dol_syslog("Thirdparty not found with email search so we try ref, ref_ext or ref_alias search", LOG_DEBUG);
2356 $sqlref = "";
2357 if ($ref) {
2358 $sqlref .= " s.nom = '".$this->db->escape($ref)."'";
2359 }
2360 if ($ref_alias) {
2361 if ($sqlref) {
2362 $sqlref .= " OR";
2363 }
2364 $sqlref .= " s.name_alias = '".$this->db->escape($ref_alias)."'";
2365 }
2366 if ($ref_ext) {
2367 if ($sqlref) {
2368 $sqlref .= " OR";
2369 }
2370 $sqlref .= " s.ref_ext = '".$this->db->escape($ref_ext)."'";
2371 }
2372
2373 if ($sqlref) {
2374 $sqlrefquery = $sqlstart . " AND (".$sqlref." )";
2375 $resql = $this->db->query($sqlrefquery);
2376 if ($resql) {
2377 $num = $this->db->num_rows($resql);
2378 if ($num > 1) {
2379 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2380 dol_syslog($this->error, LOG_ERR);
2381 $result = -2;
2382 } elseif ($num) {
2383 $obj = $this->db->fetch_object($resql);
2384 $result = $obj->id;
2385 } else {
2386 $result = 0;
2387 }
2388 } else {
2389 $this->error = $this->db->lasterror();
2390 $this->errors[] = $this->db->lasterror();
2391 $result = -3;
2392 }
2393 }
2394 return $result;
2395 }
2396
2405 public function delete($id, $fuser = null, $call_trigger = 1)
2406 {
2407 global $conf, $user;
2408
2409 if (empty($fuser)) {
2410 $fuser = $user;
2411 }
2412
2413 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2414
2415 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2416
2417 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2418 $error = 0;
2419
2420 // Test if child exists
2421 $objectisused = $this->isObjectUsed($id);
2422 if (empty($objectisused)) {
2423 $this->db->begin();
2424
2425 // User is mandatory for trigger call
2426 if (!$error && $call_trigger) {
2427 // Call trigger
2428 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2429 if ($result < 0) {
2430 $error++;
2431 }
2432 // End call triggers
2433 }
2434
2435 if (!$error) {
2436 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2437 $static_cat = new Categorie($this->db);
2438 $toute_categs = array();
2439
2440 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2441 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2442 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2443
2444 // Remove each "Categorie"
2445 foreach ($toute_categs as $type => $categs_type) {
2446 foreach ($categs_type as $cat) {
2447 $cat->del_type($this, $type);
2448 }
2449 }
2450 }
2451
2452 if (!$error) {
2453 foreach ($this->childtablesoncascade as $tabletodelete) {
2454 $deleteFromObject = explode(':', $tabletodelete, 4);
2455 if (count($deleteFromObject) >= 2) {
2456 $className = str_replace('@', '', $deleteFromObject[0]);
2457 $filepath = $deleteFromObject[1];
2458 $columnName = $deleteFromObject[2];
2459 if (dol_include_once($filepath)) {
2460 $child_object = new $className($this->db);
2461 '@phan-var-force CommonObject $child_object';
2462 $result = $child_object->deleteByParentField($id, $columnName);
2463 if ($result < 0) {
2464 $error++;
2465 $this->errors[] = $child_object->error;
2466 break;
2467 }
2468 } else {
2469 $error++;
2470 $this->errors[] = 'Cannot include child class file '.$filepath;
2471 break;
2472 }
2473 } else {
2474 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2475 $sql .= " WHERE fk_soc = ".((int) $id);
2476 if (!$this->db->query($sql)) {
2477 $error++;
2478 $this->errors[] = $this->db->lasterror();
2479 break;
2480 }
2481 }
2482 }
2483 }
2484
2485 // Removed extrafields
2486 if (!$error) {
2487 $result = $this->deleteExtraFields();
2488 if ($result < 0) {
2489 $error++;
2490 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2491 }
2492 }
2493
2494 // Remove links to subsidiaries companies
2495 if (!$error) {
2496 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2497 $sql .= " SET parent = NULL";
2498 $sql .= " WHERE parent = ".((int) $id);
2499 if (!$this->db->query($sql)) {
2500 $error++;
2501 $this->errors[] = $this->db->lasterror();
2502 }
2503 }
2504
2505 // Remove third party
2506 if (!$error) {
2507 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2508 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2509 $sql .= " WHERE fk_soc = ".((int) $id);
2510 if (!$this->db->query($sql)) {
2511 $error++;
2512 $this->errors[] = $this->db->lasterror();
2513 }
2514 }
2515
2516 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2517 $sql .= " WHERE rowid = ".((int) $id);
2518 if (!$this->db->query($sql)) {
2519 $error++;
2520 $this->errors[] = $this->db->lasterror();
2521 }
2522 }
2523
2524 if (!$error) {
2525 $this->db->commit();
2526
2527 // Delete directory
2528 if (!empty($conf->societe->multidir_output[$entity])) {
2529 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2530 if (dol_is_dir($docdir)) {
2531 dol_delete_dir_recursive($docdir);
2532 }
2533 }
2534
2535 return 1;
2536 } else {
2537 dol_syslog($this->error, LOG_ERR);
2538 $this->db->rollback();
2539 return -1;
2540 }
2541 } else {
2542 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2543 }
2544 return 0;
2545 }
2546
2547 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2555 public function set_as_client()
2556 {
2557 // phpcs:enable
2558 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2559 return $this->setAsCustomer();
2560 }
2561
2568 public function setAsCustomer()
2569 {
2570 if ($this->id) {
2571 $newclient = 1;
2572 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2573 $newclient = 3; //If prospect, we keep prospect tag
2574 }
2575 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2576 $sql .= " SET client = ".((int) $newclient);
2577 $sql .= " WHERE rowid = ".((int) $this->id);
2578
2579 $resql = $this->db->query($sql);
2580 if ($resql) {
2581 $this->client = $newclient;
2582 return 1;
2583 } else {
2584 return -1;
2585 }
2586 }
2587 return 0;
2588 }
2589
2590 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2599 public function set_remise_client($remise, $note, User $user)
2600 {
2601 // phpcs:enable
2602 global $conf, $langs;
2603
2604 // Parameter cleaning
2605 $note = trim($note);
2606 if (!$note) {
2607 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2608 return -2;
2609 }
2610
2611 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2612
2613 if ($this->id) {
2614 $this->db->begin();
2615
2616 $now = dol_now();
2617
2618 // Position current discount
2619 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2620 $sql .= " SET remise_client = '".$this->db->escape((string) $remise)."'";
2621 $sql .= " WHERE rowid = ".((int) $this->id);
2622 $resql = $this->db->query($sql);
2623 if (!$resql) {
2624 $this->db->rollback();
2625 $this->error = $this->db->error();
2626 return -1;
2627 }
2628
2629 // Writes trace in discount history
2630 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2631 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2632 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape((string) $remise)."',";
2633 $sql .= " '".$this->db->escape($note)."',";
2634 $sql .= " ".((int) $user->id);
2635 $sql .= ")";
2636
2637 $resql = $this->db->query($sql);
2638 if (!$resql) {
2639 $this->db->rollback();
2640 $this->error = $this->db->lasterror();
2641 return -1;
2642 }
2643
2644 $this->db->commit();
2645
2646 return 1;
2647 }
2648 return -1;
2649 }
2650
2651 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2660 public function set_remise_supplier($remise, $note, User $user)
2661 {
2662 // phpcs:enable
2663 global $conf, $langs;
2664
2665 // Parameter cleaning
2666 $note = trim($note);
2667 if (!$note) {
2668 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2669 return -2;
2670 }
2671
2672 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2673
2674 if ($this->id) {
2675 $this->db->begin();
2676
2677 $now = dol_now();
2678
2679 // Position current discount
2680 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2681 $sql .= " SET remise_supplier = ".((float) $remise);
2682 $sql .= " WHERE rowid = ".((int) $this->id);
2683 $resql = $this->db->query($sql);
2684 if (!$resql) {
2685 $this->db->rollback();
2686 $this->error = $this->db->error();
2687 return -1;
2688 }
2689
2690 // Writes trace in discount history
2691 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2692 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2693 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", ".((float) $remise).",";
2694 $sql .= " '".$this->db->escape($note)."',";
2695 $sql .= " ".((int) $user->id);
2696 $sql .= ")";
2697
2698 $resql = $this->db->query($sql);
2699 if (!$resql) {
2700 $this->db->rollback();
2701 $this->error = $this->db->lasterror();
2702 return -1;
2703 }
2704
2705 $this->db->commit();
2706 return 1;
2707 }
2708
2709 return -1;
2710 }
2711
2712 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2724 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2725 {
2726 // phpcs:enable
2727 global $langs;
2728
2729 // Clean parameters
2730 $remise = (float) price2num($remise);
2731 $desc = trim($desc);
2732
2733 // Check parameters
2734 if (!($remise > 0)) {
2735 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2736 return -1;
2737 }
2738 if (!$desc) {
2739 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2740 return -2;
2741 }
2742
2743 if ($this->id > 0) {
2744 // Clean vat code
2745 $reg = array();
2746 $vat_src_code = '';
2747 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2748 $vat_src_code = $reg[1];
2749 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2750 }
2751
2752 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2753
2754 $discount = new DiscountAbsolute($this->db);
2755 $discount->fk_soc = $this->id;
2756 $discount->socid = $this->id;
2757
2758 $discount->discount_type = $discount_type;
2759 $discount->multicurrency_code = $this->multicurrency_code;
2760 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
2761 $discount->multicurrency_tx = $this->multicurrency_tx;
2762
2763 if ($price_base_type == 'TTC') {
2764 $discount->total_ttc = (float) price2num($remise, 'MT');
2765 $discount->total_ht = (float) price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2766 $discount->total_tva = (float) price2num((float) $discount->total_ttc - (float) $discount->total_ht, 'MT');
2767
2768 $discount->multicurrency_total_ttc = (float) price2num((float) $remise * (float) $discount->multicurrency_tx, 'MT');
2769 $discount->multicurrency_total_ht = (float) price2num(((float) $remise / (1 + (float) $vatrate / 100)) * (float) $discount->multicurrency_tx, 'MT');
2770 $discount->multicurrency_total_tva = (float) price2num(((float) $discount->total_ttc - (float) $discount->total_ht) * (float) $discount->multicurrency_tx, 'MT');
2771 } else {
2772 $discount->total_ht = (float) price2num($remise, 'MT');
2773 $discount->total_tva = (float) price2num((float) $remise * (float) $vatrate / 100, 'MT');
2774 $discount->total_ttc = (float) price2num((float) $discount->total_ht + (float) $discount->total_tva, 'MT');
2775
2776 $discount->multicurrency_total_ht = (float) price2num((float) $remise * (float) $discount->multicurrency_tx, 'MT');
2777 $discount->multicurrency_total_tva = (float) price2num(((float) $remise * (float) $vatrate / 100) * (float) $discount->multicurrency_tx, 'MT');
2778 $discount->multicurrency_total_ttc = (float) price2num(((float) $discount->total_ht + (float) $discount->total_tva) * (float) $discount->multicurrency_tx, 'MT');
2779 }
2780
2781 // For backward compatibility
2782 $discount->amount_ht = $discount->total_ht;
2783 $discount->amount_tva = $discount->total_tva;
2784 $discount->amount_ttc = $discount->total_ttc;
2785 $discount->multicurrency_amount_ht = $discount->multicurrency_total_ht;
2786 $discount->multicurrency_amount_tva = $discount->multicurrency_total_tva;
2787 $discount->multicurrency_amount_ttc = $discount->multicurrency_total_ttc;
2788
2789
2790 $discount->tva_tx = (float) price2num($vatrate);
2791 $discount->vat_src_code = $vat_src_code;
2792
2793 $discount->description = $desc;
2794
2795 $result = $discount->create($user);
2796 if ($result > 0) {
2797 return $result;
2798 } else {
2799 $this->error = $discount->error;
2800 return -3;
2801 }
2802 } else {
2803 return 0;
2804 }
2805 }
2806
2816 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2817 {
2818 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2819
2820 $discountstatic = new DiscountAbsolute($this->db);
2821 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2822 if ($result >= 0) {
2823 return $result;
2824 } else {
2825 $this->error = $discountstatic->error;
2826 return -1;
2827 }
2828 }
2829
2839 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2840 {
2841 global $conf;
2842
2843 $reparray = array();
2844
2845 $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";
2846 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2847 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2848 // Condition here should be the same than into select_dolusers()
2849 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2850 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2851 } else {
2852 $sql .= " WHERE entity IN (0, ".((int) $conf->entity).")";
2853 }
2854
2855 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2856 if (empty($sortfield)) {
2857 $sortfield = 'u.lastname,u.firstname';
2858 }
2859 if (empty($sortorder)) {
2860 $sortorder = str_repeat('ASC,', count(explode(',', $sortfield)) - 1) . 'ASC';
2861 }
2862 $sql .= $this->db->order($sortfield, $sortorder);
2863
2864 $resql = $this->db->query($sql);
2865 if ($resql) {
2866 $num = $this->db->num_rows($resql);
2867 $i = 0;
2868 while ($i < $num) {
2869 $obj = $this->db->fetch_object($resql);
2870
2871 if (empty($mode)) {
2872 $reparray[$i]['id'] = (int) $obj->rowid;
2873 $reparray[$i]['lastname'] = $obj->lastname;
2874 $reparray[$i]['firstname'] = $obj->firstname;
2875 $reparray[$i]['email'] = $obj->email;
2876 $reparray[$i]['phone'] = $obj->office_phone;
2877 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2878 $reparray[$i]['office_fax'] = $obj->office_fax;
2879 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2880 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2881 $reparray[$i]['job'] = $obj->job;
2882 $reparray[$i]['statut'] = $obj->status; // deprecated
2883 $reparray[$i]['status'] = $obj->status;
2884 $reparray[$i]['entity'] = $obj->entity;
2885 $reparray[$i]['login'] = $obj->login;
2886 $reparray[$i]['photo'] = $obj->photo;
2887 $reparray[$i]['gender'] = $obj->gender;
2888 } else {
2889 $reparray[] = (int) $obj->rowid;
2890 }
2891 $i++;
2892 }
2893 return $reparray;
2894 } else {
2895 dol_print_error($this->db);
2896 return -1;
2897 }
2898 }
2899
2907 public function setPriceLevel($price_level, User $user)
2908 {
2909 if ($this->id) {
2910 $now = dol_now();
2911
2912 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2913 $sql .= " SET price_level = ".((int) $price_level);
2914 $sql .= " WHERE rowid = ".((int) $this->id);
2915
2916 if (!$this->db->query($sql)) {
2917 dol_print_error($this->db);
2918 return -1;
2919 }
2920
2921 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2922 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2923 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2924
2925 if (!$this->db->query($sql)) {
2926 dol_print_error($this->db);
2927 return -1;
2928 }
2929 return 1;
2930 }
2931 return -1;
2932 }
2933
2934 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2942 public function add_commercial(User $user, $commid)
2943 {
2944 // phpcs:enable
2945 $error = 0;
2946
2947 if ($this->id > 0 && $commid > 0) {
2948 $this->db->begin();
2949
2950 if (!$error) {
2951 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2952 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2953
2954 $resql = $this->db->query($sql);
2955 if (!$resql) {
2956 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2957 $error++;
2958 }
2959 }
2960
2961 if (!$error) {
2962 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2963 $sql .= " (fk_soc, fk_user)";
2964 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2965
2966 $resql = $this->db->query($sql);
2967 if (!$resql) {
2968 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2969 $error++;
2970 }
2971 }
2972
2973 if (!$error) {
2974 $this->context = array('commercial_modified' => $commid);
2975
2976 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2977 if ($result < 0) {
2978 $error++;
2979 }
2980 }
2981
2982 if (!$error) {
2983 $this->db->commit();
2984 return 1;
2985 } else {
2986 $this->db->rollback();
2987 return -1;
2988 }
2989 }
2990
2991 return 0;
2992 }
2993
2994 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3002 public function del_commercial(User $user, $commid)
3003 {
3004 // phpcs:enable
3005 $error = 0;
3006 $this->context = array('commercial_modified' => $commid);
3007
3008 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
3009 if ($result < 0) {
3010 $error++;
3011 }
3012
3013 if ($this->id > 0 && $commid > 0) {
3014 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
3015 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3016
3017 if (!$this->db->query($sql)) {
3018 $error++;
3019 dol_syslog(get_class($this)."::del_commercial Erreur");
3020 }
3021 }
3022
3023 if ($error) {
3024 return -1;
3025 } else {
3026 return 1;
3027 }
3028 }
3029
3037 public function getTooltipContentArray($params)
3038 {
3039 global $conf, $langs, $user;
3040
3041 $langs->loadLangs(['companies', 'commercial']);
3042
3043 $datas = array();
3044
3045 $option = $params['option'] ?? '';
3046 $nofetch = !empty($params['nofetch']);
3047
3048 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
3049
3050 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3051 return ['optimize' => $langs->trans("ShowCompany")];
3052 }
3053
3054 if (!empty($this->logo) && class_exists('Form')) {
3055 $photo = '<div class="photointooltip floatright">';
3056 $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.
3057 $photo .= '</div>';
3058 $datas['photo'] = $photo;
3059 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
3060 /*$label.= '<div class="photointooltip">';
3061 $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.
3062 $label.= '</div><div style="clear: both;"></div>';*/
3063 // }
3064
3065 $datas['divopen'] = '<div class="centpercent">';
3066
3067 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3068 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
3069 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3070 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
3071 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3072 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
3073 } elseif ($option == 'agenda') {
3074 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3075 } elseif ($option == 'project') {
3076 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3077 } elseif ($option == 'margin') {
3078 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3079 } elseif ($option == 'contact') {
3080 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3081 } elseif ($option == 'ban') {
3082 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3083 }
3084
3085 // By default
3086 if (empty($datas['picto'])) {
3087 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3088 }
3089 if (isset($this->status)) {
3090 $datas['status'] = ' '.$this->getLibStatut(5);
3091 }
3092 if (isset($this->client) && isset($this->fournisseur)) {
3093 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1, '', 0, 'span');
3094 }
3095 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
3096 if (!empty($this->name_alias) && empty($noaliasinname)) {
3097 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
3098 }
3099 if (!empty($this->email)) {
3100 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
3101 }
3102 if (!empty($this->url)) {
3103 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
3104 }
3105 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
3106 $phonelist = array();
3107 if ($this->phone) {
3108 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3109 }
3110 // deliberately not making new list because fax uses same list as phone
3111 if ($this->phone_mobile) {
3112 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3113 }
3114 if ($this->fax) {
3115 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3116 }
3117 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
3118 }
3119
3120 if (!empty($this->address)) {
3121 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ', ', $langs); // Address + country
3122 } elseif (!empty($this->country_code)) {
3123 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
3124 }
3125 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
3126 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
3127 }
3128
3129 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
3130 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
3131 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
3132 }
3133 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
3134 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
3135 }
3136 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
3137 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
3138 }
3139 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
3140 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
3141 }
3142 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
3143 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
3144 }
3145 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
3146 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
3147 }
3148 }
3149
3150 $datas['separator'] = '<br>';
3151
3152 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
3153 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
3154 }
3155 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
3156 $langs->load('compta');
3157 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
3158 }
3159 // show categories for this record only in ajax to not overload lists
3160 if (!$nofetch && isModEnabled('category') && $this->client) {
3161 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3162 $form = new Form($this->db);
3163 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
3164 }
3165 if (!empty($this->code_fournisseur) && $this->fournisseur) {
3166 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
3167 }
3168 if (isModEnabled('accounting') && $this->fournisseur) {
3169 $langs->load('compta');
3170 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
3171 }
3172 // show categories for this record only in ajax to not overload lists
3173 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
3174 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3175 $form = new Form($this->db);
3176 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
3177 }
3178
3179 $datas['divclose'] = '</div>';
3180
3181 return $datas;
3182 }
3183
3197 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
3198 {
3199 global $conf, $langs, $hookmanager, $user;
3200
3201 if (!empty($conf->dol_no_mouse_hover)) {
3202 $notooltip = 1; // Force disable tooltips
3203 }
3204
3205 $name = $this->name ? $this->name : $this->nom;
3206
3207 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3208 if (empty($option) && $this->client > 0) {
3209 $option = 'customer';
3210 }
3211 if (empty($option) && $this->fournisseur > 0) {
3212 $option = 'supplier';
3213 }
3214 }
3215
3216 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3217 $code = '';
3218 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3219 $code = $this->code_client.' - ';
3220 }
3221
3222 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3223 $code .= $this->code_fournisseur.' - ';
3224 }
3225
3226 if ($code) {
3227 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3228 $name = $code.' '.$name;
3229 } else {
3230 $name = $code;
3231 }
3232 }
3233 }
3234
3235 if (!empty($this->name_alias) && empty($noaliasinname)) {
3236 $name .= ' ('.$this->name_alias.')';
3237 }
3238
3239 $result = '';
3240 $params = [
3241 'id' => $this->id,
3242 'objecttype' => $this->element,
3243 'option' => $option,
3244 'nofetch' => 1,
3245 ];
3246 $classfortooltip = 'classfortooltip';
3247 $dataparams = '';
3248 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3249 $classfortooltip = 'classforajaxtooltip';
3250 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3251 $label = '';
3252 } else {
3253 $label = implode($this->getTooltipContentArray($params));
3254 }
3255
3256 $linkstart = '';
3257 $linkend = '';
3258
3259 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3260 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3261 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3262 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3263 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3264 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3265 } elseif ($option == 'agenda') {
3266 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3267 } elseif ($option == 'project') {
3268 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3269 } elseif ($option == 'margin') {
3270 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3271 } elseif ($option == 'contact') {
3272 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3273 } elseif ($option == 'ban') {
3274 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3275 }
3276
3277 // By default
3278 if (empty($linkstart)) {
3279 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3280 }
3281
3282 // Add type of canvas
3283 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3284 // Add param to save lastsearch_values or not
3285 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3286 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3287 $add_save_lastsearch_values = 1;
3288 }
3289 if ($add_save_lastsearch_values) {
3290 $linkstart .= '&save_lastsearch_values=1';
3291 }
3292 $linkstart .= '"';
3293
3294 $linkclose = '';
3295 if (empty($notooltip)) {
3296 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3297 $label = $langs->trans("ShowCompany");
3298 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3299 }
3300 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3301 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
3302 $target_value = array('_self', '_blank', '_parent', '_top');
3303 if (in_array($target, $target_value)) {
3304 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3305 }
3306 } else {
3307 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3308 }
3309 $linkstart .= $linkclose.'>';
3310 $linkend = '</a>';
3311
3312 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3313 $linkstart = '';
3314 $linkend = '';
3315 }
3316
3317 $result .= $linkstart;
3318 if ($withpicto) {
3319 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3320 }
3321 if ($withpicto != 2) {
3322 $result .= dol_escape_htmltag($maxlen ? dol_trunc((string) $name, $maxlen) : $name);
3323 }
3324 $result .= $linkend;
3325
3326 global $action;
3327 $hookmanager->initHooks(array('thirdpartydao'));
3328 $parameters = array(
3329 'id' => $this->id,
3330 'getnomurl' => &$result,
3331 'withpicto ' => $withpicto,
3332 'option' => $option,
3333 'maxlen' => $maxlen,
3334 'notooltip' => $notooltip,
3335 'save_lastsearch_value' => $save_lastsearch_value
3336 );
3337 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3338 if ($reshook > 0) {
3339 $result = $hookmanager->resPrint;
3340 } else {
3341 $result .= $hookmanager->resPrint;
3342 }
3343
3344 return $result;
3345 }
3346
3356 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3357 {
3358 global $langs;
3359
3360 $s = '';
3361 if (empty($option) || preg_match('/prospect/', $option)) {
3362 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3363 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.dolPrintHTMLForAttribute($langs->trans("Prospect")).'"';
3364 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3365 $s .= '>'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3366 }
3367 }
3368 if (empty($option) || preg_match('/customer/', $option)) {
3369 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3370 $s .= '<'.$tag.' class="customer-back" title="'.dolPrintHTMLForAttribute($langs->trans("Customer")).'"';
3371 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3372 $s .= '>'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3373 }
3374 }
3375 if (empty($option) || preg_match('/supplier/', $option)) {
3376 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3377 $s .= '<'.$tag.' class="vendor-back" title="'.dolPrintHTMLForAttribute($langs->trans("Supplier")).'"';
3378 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'"' : '';
3379 $s .= '>'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3380 }
3381 }
3382
3383 return $s;
3384 }
3385
3386
3393 public function getLibStatut($mode = 0)
3394 {
3395 return $this->LibStatut($this->status, $mode);
3396 }
3397
3398 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3406 public function LibStatut($status, $mode = 0)
3407 {
3408 // phpcs:enable
3409 global $langs;
3410 $langs->load('companies');
3411
3412 $statusType = 'status4';
3413 if ($status == 0) {
3414 $statusType = 'status6';
3415 }
3416
3417 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3418 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3419 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3420 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3421 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3422 }
3423
3424 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3425 }
3426
3427 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3434 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3435 {
3436 // phpcs:enable
3437 global $langs;
3438
3439 $contact_emails = $this->contact_property_array('email', 1);
3440
3441 if ($this->email && $addthirdparty) {
3442 if (empty($this->name)) {
3443 $this->name = $this->nom;
3444 }
3445 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3446 }
3447
3448 //var_dump($contact_emails)
3449 return $contact_emails;
3450 }
3451
3452 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3459 {
3460 // phpcs:enable
3461 global $langs;
3462
3463 $contact_phone = $this->contact_property_array('mobile');
3464
3465 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3466 if (empty($this->name)) {
3467 $this->name = $this->nom;
3468 }
3469 // TODO: Tester si tel non deja present dans tableau contact
3470 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3471 }
3472 return $contact_phone;
3473 }
3474
3475 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3483 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3484 {
3485 // phpcs:enable
3486 global $langs;
3487
3488 $contact_property = array();
3489
3490
3491 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3492 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3493 $sql .= " WHERE fk_soc = ".((int) $this->id);
3494 $sql .= " AND entity IN (".getEntity($this->element).")";
3495 $sql .= " ORDER BY lastname, firstname";
3496
3497 $resql = $this->db->query($sql);
3498 if ($resql) {
3499 $nump = $this->db->num_rows($resql);
3500 if ($nump) {
3501 $sepa = "(";
3502 $sepb = ")";
3503 if ($mode == 'email') {
3504 //$sepa="&lt;"; $sepb="&gt;";
3505 $sepa = "<";
3506 $sepb = ">";
3507 }
3508 $i = 0;
3509 while ($i < $nump) {
3510 $obj = $this->db->fetch_object($resql);
3511 if ($mode == 'email') {
3512 $property = $obj->email;
3513 } elseif ($mode == 'mobile') {
3514 $property = $obj->phone_mobile;
3515 } else {
3516 $property = $obj->$mode;
3517 }
3518
3519 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3520 if ($obj->status == 1 || empty($hidedisabled)) {
3521 if (empty($property)) {
3522 if ($mode == 'email') {
3523 $property = $langs->transnoentitiesnoconv("NoEMail");
3524 } elseif ($mode == 'mobile') {
3525 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3526 }
3527 }
3528
3529 if (!empty($obj->poste)) {
3530 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3531 } else {
3532 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3533 }
3534 }
3535 $i++;
3536 }
3537 }
3538 } else {
3539 dol_print_error($this->db);
3540 }
3541 return $contact_property;
3542 }
3543
3544
3545 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3551 public function contact_array()
3552 {
3553 // phpcs:enable
3554 $contacts = array();
3555
3556 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3557 $resql = $this->db->query($sql);
3558 if ($resql) {
3559 $nump = $this->db->num_rows($resql);
3560 if ($nump) {
3561 $i = 0;
3562 while ($i < $nump) {
3563 $obj = $this->db->fetch_object($resql);
3564 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3565 $i++;
3566 }
3567 }
3568 } else {
3569 dol_print_error($this->db);
3570 }
3571 return $contacts;
3572 }
3573
3574 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3580 public function contact_array_objects()
3581 {
3582 // phpcs:enable
3583 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3584 $contacts = array();
3585
3586 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3587 $resql = $this->db->query($sql);
3588 if ($resql) {
3589 $nump = $this->db->num_rows($resql);
3590 if ($nump) {
3591 $i = 0;
3592 while ($i < $nump) {
3593 $obj = $this->db->fetch_object($resql);
3594 $contact = new Contact($this->db);
3595 $contact->fetch($obj->rowid);
3596 $contacts[] = $contact;
3597 $i++;
3598 }
3599 }
3600 } else {
3601 dol_print_error($this->db);
3602 }
3603 return $contacts;
3604 }
3605
3606 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3614 public function contact_get_property($rowid, $mode)
3615 {
3616 // phpcs:enable
3617 $contact_property = '';
3618
3619 if (empty($rowid)) {
3620 return '';
3621 }
3622
3623 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3624 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3625 $sql .= " WHERE rowid = ".((int) $rowid);
3626
3627 $resql = $this->db->query($sql);
3628 if ($resql) {
3629 $nump = $this->db->num_rows($resql);
3630
3631 if ($nump) {
3632 $obj = $this->db->fetch_object($resql);
3633
3634 if ($mode == 'email') {
3635 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3636 } elseif ($mode == 'mobile') {
3637 $contact_property = $obj->phone_mobile;
3638 }
3639 }
3640 return $contact_property;
3641 } else {
3642 dol_print_error($this->db);
3643 }
3644
3645 return '';
3646 }
3647
3648
3649 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3656 public function display_rib($mode = 'label')
3657 {
3658 // phpcs:enable
3659 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3660
3661 $bac = new CompanyBankAccount($this->db);
3662 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3663 $bac->fetch(0, '', $this->id);
3664
3665 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3666 if ($mode == 'label') {
3667 return $bac->getRibLabel(true);
3668 } elseif ($mode == 'rum') {
3669 if (empty($bac->rum)) {
3670 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3671 $prelevement = new BonPrelevement($this->db);
3672 $bac->fetch_thirdparty();
3673 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, (string) $bac->id);
3674 }
3675 return $bac->rum;
3676 } elseif ($mode == 'format') {
3677 return $bac->frstrecur;
3678 } else {
3679 return 'BadParameterToFunctionDisplayRib';
3680 }
3681 } else {
3682 return '';
3683 }
3684 }
3685
3686 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3692 public function get_all_rib()
3693 {
3694 // phpcs:enable
3695 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3696 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3697 $result = $this->db->query($sql);
3698 if (!$result) {
3699 $this->error = $this->db->lasterror();
3700 $this->errors[] = $this->db->lasterror();
3701 return 0;
3702 } else {
3703 $num_rows = $this->db->num_rows($result);
3704 $rib_array = array();
3705 if ($num_rows) {
3706 while ($obj = $this->db->fetch_object($result)) {
3707 $rib = new CompanyBankAccount($this->db);
3708 $rib->fetch($obj->rowid);
3709 $rib_array[] = $rib;
3710 }
3711 }
3712 return $rib_array;
3713 }
3714 }
3715
3719 public function getDefaultRib()
3720 {
3721 // phpcs:enable
3722 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3723 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND default_rib = 1 AND fk_soc = ". (int) $this->id;
3724 $resql = $this->db->query($sql);
3725 if (!$resql) {
3726 $this->error = $this->db->lasterror();
3727 $this->errors[] = $this->db->lasterror();
3728 return -1;
3729 } else {
3730 $num_rows = $this->db->num_rows($resql);
3731 $rib_array = array();
3732 if ($num_rows) {
3733 while ($obj = $this->db->fetch_object($resql)) {
3734 return $obj->rowid;
3735 }
3736 }
3737 return 0;
3738 }
3739 }
3740
3741
3742 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3751 public function get_codeclient($objsoc = null, $type = 0)
3752 {
3753 // phpcs:enable
3754 global $conf;
3755 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3756 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3757
3758 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3759 foreach ($dirsociete as $dirroot) {
3760 $res = dol_include_once($dirroot.$module.'.php');
3761 if ($res) {
3762 break;
3763 }
3764 }
3766 $mod = new $module($this->db);
3767 '@phan-var-force ModeleThirdPartyCode $mod';
3768
3769 $this->code_client = $mod->getNextValue($objsoc, $type);
3770 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3771
3772 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3773 }
3774 }
3775
3776 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3785 public function get_codefournisseur($objsoc = null, $type = 1)
3786 {
3787 // phpcs:enable
3788 global $conf;
3789 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3790 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3791
3792 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3793 foreach ($dirsociete as $dirroot) {
3794 $res = dol_include_once($dirroot.$module.'.php');
3795 if ($res) {
3796 break;
3797 }
3798 }
3800 $mod = new $module($this->db);
3801 '@phan-var-force ModeleThirdPartyCode $mod';
3802
3803 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3804
3805 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3806 }
3807 }
3808
3809 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3816 public function codeclient_modifiable()
3817 {
3818 // phpcs:enable
3819 global $conf;
3820 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3821 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3822
3823 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3824 foreach ($dirsociete as $dirroot) {
3825 $res = dol_include_once($dirroot.$module.'.php');
3826 if ($res) {
3827 break;
3828 }
3829 }
3830
3831 $mod = new $module($this->db);
3832 '@phan-var-force ModeleThirdPartyCode $mod';
3833
3834 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3835 if ($mod->code_modifiable_null && !$this->code_client) {
3836 return 1;
3837 }
3838 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3839 return 1;
3840 }
3841 if ($mod->code_modifiable) {
3842 return 1; // A mettre en dernier
3843 }
3844 return 0;
3845 } else {
3846 return 0;
3847 }
3848 }
3849
3850
3851 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3858 {
3859 // phpcs:enable
3860 global $conf;
3861 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3862 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3863
3864 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3865 foreach ($dirsociete as $dirroot) {
3866 $res = dol_include_once($dirroot.$module.'.php');
3867 if ($res) {
3868 break;
3869 }
3870 }
3871
3872 $mod = new $module($this->db);
3873 '@phan-var-force ModeleThirdPartyCode $mod';
3874
3875 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3876 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3877 return 1;
3878 }
3879 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3880 return 1;
3881 }
3882 if ($mod->code_modifiable) {
3883 return 1; // A mettre en dernier
3884 }
3885 return 0;
3886 } else {
3887 return 0;
3888 }
3889 }
3890
3891
3892 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3904 public function check_codeclient()
3905 {
3906 // phpcs:enable
3907 global $conf;
3908 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3909 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3910
3911 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3912 foreach ($dirsociete as $dirroot) {
3913 $res = dol_include_once($dirroot.$module.'.php');
3914 if ($res) {
3915 break;
3916 }
3917 }
3918
3919 $mod = new $module($this->db);
3920 '@phan-var-force ModeleThirdPartyCode $mod';
3921
3922 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3923 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3924 if ($result) { // If error
3925 $this->error = $mod->error;
3926 $this->errors = $mod->errors;
3927 }
3928 return $result;
3929 } else {
3930 return 0;
3931 }
3932 }
3933
3934 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3946 public function check_codefournisseur()
3947 {
3948 // phpcs:enable
3949 global $conf;
3950 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3951 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3952
3953 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3954 foreach ($dirsociete as $dirroot) {
3955 $res = dol_include_once($dirroot.$module.'.php');
3956 if ($res) {
3957 break;
3958 }
3959 }
3960
3961 $mod = new $module($this->db);
3962 '@phan-var-force ModeleThirdPartyCode $mod';
3963
3964 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3965 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3966 if ($result) { // If error
3967 $this->error = $mod->error;
3968 $this->errors = $mod->errors;
3969 }
3970 return $result;
3971 } else {
3972 return 0;
3973 }
3974 }
3975
3976 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3985 public function get_codecompta($type)
3986 {
3987 // phpcs:enable
3988 global $conf;
3989
3990 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3991 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
3992 $res = false;
3993 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3994 foreach ($dirsociete as $dirroot) {
3995 $res = dol_include_once($dirroot.$module.'.php');
3996 if ($res) {
3997 break;
3998 }
3999 }
4000
4001 if ($res) {
4002 $mod = new $module();
4003 '@phan-var-force ModeleAccountancyCode $mod';
4004
4005 // Set code count in $mod->code
4006 $result = $mod->get_code($this->db, $this, $type);
4007
4008 if ($type == 'customer') {
4009 $this->code_compta_client = $mod->code;
4010 } elseif ($type == 'supplier') {
4011 $this->code_compta_fournisseur = $mod->code;
4012 }
4013
4014 return $result;
4015 } else {
4016 $this->error = 'ErrorAccountancyCodeNotDefined';
4017 return -1;
4018 }
4019 } else {
4020 if ($type == 'customer') {
4021 $this->code_compta_client = '';
4022 } elseif ($type == 'supplier') {
4023 $this->code_compta_fournisseur = '';
4024 }
4025
4026 return 0;
4027 }
4028 }
4029
4036 public function setParent($id)
4037 {
4038 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
4039
4040 if ($this->id) {
4041 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
4042 if ($id > 0) {
4043 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
4044 if ($sameparent < 0) {
4045 return -1;
4046 }
4047 if ($sameparent == 1) {
4048 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
4049 return -1;
4050 }
4051 }
4052
4053 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
4054
4055 $resql = $this->db->query($sql);
4056 if ($resql) {
4057 $this->parent = $id;
4058 return 1;
4059 } else {
4060 return -1;
4061 }
4062 }
4063
4064 return -1;
4065 }
4066
4075 public function validateFamilyTree($idparent, $idchild, $counter = 0)
4076 {
4077 if ($counter > 100) {
4078 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
4079 }
4080
4081 $sql = 'SELECT s.parent';
4082 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
4083 $sql .= ' WHERE rowid = '.((int) $idparent);
4084 $resql = $this->db->query($sql);
4085 if ($resql) {
4086 $obj = $this->db->fetch_object($resql);
4087
4088 if ($obj->parent == '') {
4089 return 0;
4090 } elseif ($obj->parent == $idchild) {
4091 return 1;
4092 } else {
4093 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
4094 }
4095 return $sameparent;
4096 } else {
4097 return -1;
4098 }
4099 }
4100
4108 public function getParentsForCompany($company_id, $parents = array())
4109 {
4110 global $langs;
4111
4112 if ($company_id > 0) {
4113 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
4114 $resql = $this->db->query($sql);
4115 if ($resql) {
4116 if ($obj = $this->db->fetch_object($resql)) {
4117 $parent = $obj->parent;
4118 if ($parent > 0 && !in_array($parent, $parents)) {
4119 $parents[] = $parent;
4120 return $this->getParentsForCompany($parent, $parents);
4121 } else {
4122 return $parents;
4123 }
4124 }
4125 $this->db->free($resql);
4126 } else {
4127 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
4128 }
4129 }
4130 // Return a default value when $company_id is not greater than 0
4131 return array();
4132 }
4133
4134 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4141 public function id_prof_verifiable($idprof)
4142 {
4143 // phpcs:enable
4144 global $conf;
4145
4146 switch ($idprof) {
4147 case 1:
4148 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
4149 break;
4150 case 2:
4151 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
4152 break;
4153 case 3:
4154 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
4155 break;
4156 case 4:
4157 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
4158 break;
4159 case 5:
4160 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
4161 break;
4162 case 6:
4163 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
4164 break;
4165 default:
4166 $ret = false;
4167 }
4168
4169 return $ret;
4170 }
4171
4172 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4181 public function id_prof_exists($idprof, $value, $socid = 0)
4182 {
4183 // phpcs:enable
4184 $field = $idprof;
4185
4186 switch ($idprof) { // For backward compatibility
4187 case '1':
4188 case 'idprof1':
4189 $field = "siren";
4190 break;
4191 case '2':
4192 case 'idprof2':
4193 $field = "siret";
4194 break;
4195 case '3':
4196 case 'idprof3':
4197 $field = "ape";
4198 break;
4199 case '4':
4200 case 'idprof4':
4201 $field = "idprof4";
4202 break;
4203 case '5':
4204 $field = "idprof5";
4205 break;
4206 case '6':
4207 $field = "idprof6";
4208 break;
4209 }
4210
4211 //Verify duplicate entries
4212 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
4213 if ($socid) {
4214 $sql .= " AND rowid <> ".$socid;
4215 }
4216 $resql = $this->db->query($sql);
4217 if ($resql) {
4218 $obj = $this->db->fetch_object($resql);
4219 $count = $obj->nb;
4220 } else {
4221 $count = 0;
4222 print $this->db->error();
4223 }
4224 $this->db->free($resql);
4225
4226 if ($count > 0) {
4227 return true;
4228 } else {
4229 return false;
4230 }
4231 }
4232
4233 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4242 public function id_prof_check($idprof, $soc)
4243 {
4244 // phpcs:enable
4245 global $conf;
4246
4247 // load the library necessary to check the professional identifiers
4248 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4249
4250 $ok = 1;
4251
4252 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4253 return 1;
4254 }
4255
4256 // Check SIREN
4257 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
4258 return -1;
4259 }
4260
4261 // Check SIRET
4262 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
4263 return -1;
4264 }
4265
4266 //Verify CIF/NIF/NIE if pays ES
4267 if ($idprof == 1 && $soc->country_code == 'ES') {
4268 return isValidTinForES($this->idprof1);
4269 }
4270
4271 //Verify NIF if country is PT
4272 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
4273 return -1;
4274 }
4275
4276 //Verify NIF if country is DZ
4277 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
4278 return -1;
4279 }
4280
4281 //Verify ID Prof 1 if country is BE
4282 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
4283 return -1;
4284 }
4285
4286 return $ok;
4287 }
4288
4289 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4298 public function id_prof_url($idprof, $thirdparty)
4299 {
4300 // phpcs:enable
4301 global $conf, $langs, $hookmanager;
4302
4303 $url = '';
4304 $action = '';
4305
4306 $hookmanager->initHooks(array('idprofurl'));
4307 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4308 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4309 if (empty($reshook)) {
4310 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4311 return '';
4312 }
4313
4314 // TODO Move links to validate professional ID into a dictionary table "country" + "link"
4315 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4316 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4317 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
4318 }
4319 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4320 $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
4321 }
4322 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4323 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
4324 }
4325 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4326 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4327 }
4328 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4329 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
4330 }
4331 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4332 $url = 'http://www.nif.pt/'.$strippedIdProf1;
4333 }
4334
4335 if ($url) {
4336 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4337 }
4338 } else {
4339 return $hookmanager->resPrint;
4340 }
4341
4342 return '';
4343 }
4344
4345 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4351 public function has_projects()
4352 {
4353 // phpcs:enable
4354 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4355 $resql = $this->db->query($sql);
4356 if ($resql) {
4357 $obj = $this->db->fetch_object($resql);
4358 $count = $obj->numproj;
4359 } else {
4360 $count = 0;
4361 print $this->db->error();
4362 }
4363 $this->db->free($resql);
4364 return ($count > 0);
4365 }
4366
4367
4374 public function info($id)
4375 {
4376 $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4377 $sql .= " fk_user_creat, fk_user_modif";
4378 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4379 $sql .= " WHERE s.rowid = ".((int) $id);
4380
4381 $result = $this->db->query($sql);
4382 if ($result) {
4383 if ($this->db->num_rows($result)) {
4384 $obj = $this->db->fetch_object($result);
4385
4386 $this->id = $obj->rowid;
4387
4388 $this->user_creation_id = $obj->fk_user_creat;
4389 $this->user_modification_id = $obj->fk_user_modif;
4390 $this->date_creation = $this->db->jdate($obj->datec);
4391 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4392
4393 $this->ref = $obj->name;
4394 }
4395
4396 $this->db->free($result);
4397 } else {
4398 dol_print_error($this->db);
4399 }
4400 }
4401
4407 public function isACompany()
4408 {
4409 // Define if third party is treated as company (or not) when nature is unknown
4410 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES', 1); // default if not set is 1 because it was like this in all past versions
4411
4412 // Now try to guess using different tips
4413 if (!empty($this->tva_intra)) {
4414 $isACompany = 1;
4415 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4416 $isACompany = 1;
4417 } else {
4418 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) { // never or rarely set
4419 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) { // TODO Add a field is_a_company into dictionary
4420 $isACompany = 0;
4421 }
4422 } else {
4423 $isACompany = 1;
4424 }
4425 }
4426
4427 return (bool) $isACompany;
4428 }
4429
4435 public function isInEEC()
4436 {
4437 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4438 return isInEEC($this);
4439 }
4440
4446 public function isInSEPA()
4447 {
4448 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4449 return isInSEPA($this);
4450 }
4451
4452 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4458 public function LoadSupplierCateg()
4459 {
4460 // phpcs:enable
4461 $this->SupplierCategories = array();
4462 $sql = "SELECT rowid, label";
4463 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4464 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4465
4466 $resql = $this->db->query($sql);
4467 if ($resql) {
4468 while ($obj = $this->db->fetch_object($resql)) {
4469 $this->SupplierCategories[$obj->rowid] = $obj->label;
4470 }
4471 return 0;
4472 } else {
4473 return -1;
4474 }
4475 }
4476
4477 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4484 public function AddFournisseurInCategory($categorie_id)
4485 {
4486 // phpcs:enable
4487 if ($categorie_id > 0 && $this->id > 0) {
4488 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4489 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4490
4491 if ($resql = $this->db->query($sql)) {
4492 return 0;
4493 }
4494 } else {
4495 return 0;
4496 }
4497 return -1;
4498 }
4499
4505 public function getNbOfEMailings()
4506 {
4507 $sql = "SELECT count(mc.email) as nb";
4508 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4509 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4510 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4511
4512 $resql = $this->db->query($sql);
4513 if ($resql) {
4514 $obj = $this->db->fetch_object($resql);
4515 $nb = $obj->nb;
4516
4517 $this->db->free($resql);
4518 return $nb;
4519 } else {
4520 $this->error = $this->db->error();
4521 return -1;
4522 }
4523 }
4524
4532 public function setNoEmail($no_email, $unsubscribegroup = '')
4533 {
4534 $error = 0;
4535
4536 // Update mass emailing flag into table mailing_unsubscribe
4537 if ($this->email) {
4538 $this->db->begin();
4539
4540 if ($no_email) {
4541 // TODO Add $unsubscribegroup
4542 $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)."'";
4543 $resql = $this->db->query($sql);
4544 if ($resql) {
4545 $obj = $this->db->fetch_object($resql);
4546 $noemail = $obj->nb;
4547 if (empty($noemail)) {
4548 // TODO Add $unsubscribegroup
4549 $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())."')";
4550 $resql = $this->db->query($sql);
4551 if (!$resql) {
4552 $error++;
4553 $this->error = $this->db->lasterror();
4554 $this->errors[] = $this->error;
4555 }
4556 }
4557 } else {
4558 $error++;
4559 $this->error = $this->db->lasterror();
4560 $this->errors[] = $this->error;
4561 }
4562 } else {
4563 // TODO Add $unsubscribegroup
4564 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4565 $resql = $this->db->query($sql);
4566 if (!$resql) {
4567 $error++;
4568 $this->error = $this->db->lasterror();
4569 $this->errors[] = $this->error;
4570 }
4571 }
4572
4573 if (empty($error)) {
4574 $this->no_email = $no_email;
4575 $this->db->commit();
4576 return 1;
4577 } else {
4578 $this->db->rollback();
4579 return $error * -1;
4580 }
4581 }
4582
4583 return 0;
4584 }
4585
4592 public function getNoEmail()
4593 {
4594 if ($this->email) {
4595 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4596 $resql = $this->db->query($sql);
4597 if ($resql) {
4598 $obj = $this->db->fetch_object($resql);
4599 $this->no_email = $obj->nb;
4600 return 1;
4601 } else {
4602 $this->error = $this->db->lasterror();
4603 $this->errors[] = $this->error;
4604 return -1;
4605 }
4606 }
4607 return 0;
4608 }
4609
4610 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4620 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4621 {
4622 // phpcs:enable
4623 global $user, $langs;
4624
4625 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4626 $fullname = $member->getFullName($langs);
4627
4628 if ($member->morphy == 'mor') {
4629 if (empty($socname)) {
4630 $socname = $member->company ? $member->company : $member->societe;
4631 }
4632 if (!empty($fullname) && empty($socalias)) {
4633 $socalias = $fullname;
4634 }
4635 } elseif (empty($socname) && $member->morphy == 'phy') {
4636 if (empty($socname)) {
4637 $socname = $fullname;
4638 }
4639 if (!empty($member->company) && empty($socalias)) {
4640 $socalias = $member->company;
4641 }
4642 }
4643
4644 $name = $socname;
4645 $alias = $socalias ? $socalias : '';
4646
4647 // Positionne parameters
4648 $this->nom = $name; // TODO deprecated
4649 $this->name = $name;
4650 $this->name_alias = $alias;
4651 $this->address = $member->address;
4652 $this->zip = $member->zip;
4653 $this->town = $member->town;
4654 $this->country_code = $member->country_code;
4655 $this->country_id = $member->country_id;
4656 $this->phone = $member->phone; // Prof phone
4657 $this->email = $member->email;
4658 $this->socialnetworks = $member->socialnetworks;
4659 $this->entity = $member->entity;
4660
4661 $this->client = 1; // A member is a customer by default
4662 if (getDolGlobalString('THIRDPARTY_CUSTOMERCODE_EQUALS_MEMBERREF')) {
4663 $this->code_client = $member->ref; // set Customer Code equal to existing Member Reference
4664 } else {
4665 $this->code_client = ($customercode ? $customercode : -1); // set new auto-incremented Customer Code
4666 }
4667 $this->code_fournisseur = '-1';
4668 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4669 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4670
4671 $this->db->begin();
4672
4673 // Cree et positionne $this->id
4674 $result = $this->create($user);
4675
4676 if ($result >= 0) {
4677 // Auto-create contact on thirdparty creation
4678 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4679 // Fill fields needed by contact
4680 $this->name_bis = $member->lastname;
4681 $this->firstname = $member->firstname;
4682 $this->civility_id = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4683 $this->civility_code = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4684
4685 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4686 $result = $this->create_individual($user);
4687
4688 if ($result < 0) {
4689 setEventMessages($this->error, $this->errors, 'errors');
4690 $this->db->rollback();
4691 return -1;
4692 }
4693 }
4694
4695 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4696 $sql .= " SET fk_soc = ".((int) $this->id);
4697 $sql .= " WHERE rowid = ".((int) $member->id);
4698
4699 $resql = $this->db->query($sql);
4700 if ($resql) {
4701 $this->db->commit();
4702 return $this->id;
4703 } else {
4704 $this->error = $this->db->error();
4705
4706 $this->db->rollback();
4707 return -1;
4708 }
4709 } else {
4710 // $this->error deja positionne
4711 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4712
4713 $this->db->rollback();
4714 return $result;
4715 }
4716 }
4717
4724 public function setMysoc(Conf $conf)
4725 {
4726 global $langs;
4727
4728 $this->id = 0;
4729 $this->entity = $conf->entity;
4730 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4731 $this->nom = $this->name; // deprecated
4732 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4733 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4734 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4735 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4736
4737 $this->currency_code = getDolGlobalString('MAIN_MONNAIE');
4738
4739 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4740
4741 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4742
4743 // We define country_id, country_code and country
4744 $country_id = 0;
4745 $country_code = $country_label = '';
4746 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4747 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4748 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4749 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4750 $country_code = $tmp[1];
4751 $country_label = $tmp[2];
4752 } else {
4753 // For backward compatibility
4754 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4755 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4756 $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
4757 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4758 }
4759 }
4760 $this->country_id = $country_id;
4761 $this->country_code = $country_code;
4762 $this->country = $country_label;
4763 if (is_object($langs)) {
4764 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4765 }
4766
4767 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4768 // We define state_id, state_code and state
4769 $state_id = 0;
4770 $state_code = '';
4771 $state_label = '';
4772 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4773 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4774 $state_id = (int) $tmp[0];
4775 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4776 $state_code = $tmp[1];
4777 $state_label = $tmp[2];
4778 } else { // For backward compatibility
4779 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);
4780 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4781 $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
4782 $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
4783 }
4784 }
4785 $this->state_id = $state_id;
4786 $this->state_code = $state_code;
4787 $this->state = $state_label;
4788 if (is_object($langs)) {
4789 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4790 }
4791
4792 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4793 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4794 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4795 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4796
4797 // Social networks
4798 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4799 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4800 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4801 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4802 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4803 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4804 $this->socialnetworks = array();
4805 if (!empty($facebook_url)) {
4806 $this->socialnetworks['facebook'] = $facebook_url;
4807 }
4808 if (!empty($twitter_url)) {
4809 $this->socialnetworks['twitter'] = $twitter_url;
4810 }
4811 if (!empty($linkedin_url)) {
4812 $this->socialnetworks['linkedin'] = $linkedin_url;
4813 }
4814 if (!empty($instagram_url)) {
4815 $this->socialnetworks['instagram'] = $instagram_url;
4816 }
4817 if (!empty($youtube_url)) {
4818 $this->socialnetworks['youtube'] = $youtube_url;
4819 }
4820 if (!empty($github_url)) {
4821 $this->socialnetworks['github'] = $github_url;
4822 }
4823
4824 // Id prof generiques
4825 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4826 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4827 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4828 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4829 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4830 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4831 $this->idprof7 = getDolGlobalString('MAIN_INFO_PROFID7');
4832 $this->idprof8 = getDolGlobalString('MAIN_INFO_PROFID8');
4833 $this->idprof9 = getDolGlobalString('MAIN_INFO_PROFID9');
4834 $this->idprof10 = getDolGlobalString('MAIN_INFO_PROFID10');
4835 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4836 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4837 $this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;
4838 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4839 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4840 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4841 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4842 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4843 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4844 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4845 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4846 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4847
4848 // Define if company use vat or not
4849 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4850
4851 // Define if company use local taxes
4852 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4853 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4854
4855 $this->termsofsale = getDolGlobalString('MAIN_INFO_SOCIETE_TERMSOFSALE');
4856 }
4857
4865 public function initAsSpecimen()
4866 {
4867 $now = dol_now();
4868
4869 // Initialize parameters
4870 $this->id = 0;
4871 $this->entity = 1;
4872 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4873 $this->ref_ext = 'Ref ext';
4874 $this->specimen = 1;
4875 $this->address = '21 jump street';
4876 $this->zip = '99999';
4877 $this->town = 'MyTown';
4878 $this->state_id = 1;
4879 $this->state_code = 'AA';
4880 $this->state = 'MyState';
4881 $this->country_id = 1;
4882 $this->country_code = 'FR';
4883 $this->email = 'specimen@specimen.com';
4884 $this->socialnetworks = array(
4885 'skype' => 'skypepseudo',
4886 'twitter' => 'twitterpseudo',
4887 'facebook' => 'facebookpseudo',
4888 'linkedin' => 'linkedinpseudo',
4889 );
4890 $this->url = 'http://www.specimen.com';
4891
4892 $this->phone = '0909090901';
4893 $this->phone_mobile = '0909090901';
4894 $this->fax = '0909090909';
4895
4896 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4897 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4898 $this->typent_code = 'TE_OTHER';
4899 $this->capital = 10000;
4900 $this->client = 1;
4901 $this->prospect = 1;
4902 $this->fournisseur = 1;
4903 $this->tva_assuj = 1;
4904 $this->tva_intra = 'EU1234567';
4905 $this->note_public = 'This is a comment (public)';
4906 $this->note_private = 'This is a comment (private)';
4907
4908 $this->idprof1 = 'idprof1';
4909 $this->idprof2 = 'idprof2';
4910 $this->idprof3 = 'idprof3';
4911 $this->idprof4 = 'idprof4';
4912 $this->idprof5 = 'idprof5';
4913 $this->idprof6 = 'idprof6';
4914
4915 return 1;
4916 }
4917
4924 public function useLocalTax($localTaxNum = 0)
4925 {
4926 $sql = "SELECT t.localtax1, t.localtax2";
4927 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4928 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4929 $sql .= " AND t.active = 1";
4930 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4931 if (empty($localTaxNum)) {
4932 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4933 } elseif ($localTaxNum == 1) {
4934 $sql .= " AND t.localtax1_type <> '0'";
4935 } elseif ($localTaxNum == 2) {
4936 $sql .= " AND t.localtax2_type <> '0'";
4937 }
4938
4939 $resql = $this->db->query($sql);
4940 if ($resql) {
4941 return ($this->db->num_rows($resql) > 0);
4942 } else {
4943 return false;
4944 }
4945 }
4946
4952 public function useNPR()
4953 {
4954 $sql = "SELECT t.rowid";
4955 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4956 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4957 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4958 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4959
4960 dol_syslog("useNPR", LOG_DEBUG);
4961 $resql = $this->db->query($sql);
4962 if ($resql) {
4963 return ($this->db->num_rows($resql) > 0);
4964 } else {
4965 return false;
4966 }
4967 }
4968
4975 public function useRevenueStamp()
4976 {
4977 $sql = "SELECT COUNT(*) as nb";
4978 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4979 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4980 $sql .= " AND r.active = 1";
4981
4982 dol_syslog("useRevenueStamp", LOG_DEBUG);
4983 $resql = $this->db->query($sql);
4984 if ($resql) {
4985 $obj = $this->db->fetch_object($resql);
4986 return ($obj->nb > 0);
4987 } else {
4988 $this->error = $this->db->lasterror();
4989 return false;
4990 }
4991 }
4992
4998 public function getLibProspLevel()
4999 {
5000 return $this->LibProspLevel($this->fk_prospectlevel);
5001 }
5002
5003 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5010 public function LibProspLevel($fk_prospectlevel)
5011 {
5012 // phpcs:enable
5013 global $langs;
5014
5015 $label = '';
5016 if ($fk_prospectlevel != '') {
5017 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
5018 // If label is not found in language file, we get label from cache/database
5019 if ($label == "ProspectLevel".$fk_prospectlevel) {
5020 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
5021 }
5022 }
5023
5024 return $label;
5025 }
5026
5034 public function getLibProspCommStatut($mode = 0, $label = '')
5035 {
5036 return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
5037 }
5038
5039 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5053 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
5054 {
5055 // phpcs:enable
5056 global $langs;
5057
5058 $langs->load('customers');
5059
5060 if ($mode == 2) {
5061 if ($status == '-1' || $status == 'ST_NO') {
5062 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5063 } elseif ($status == '0' || $status == 'ST_NEVER') {
5064 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5065 } elseif ($status == '1' || $status == 'ST_TODO') {
5066 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5067 } elseif ($status == '2' || $status == 'ST_PEND') {
5068 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5069 } elseif ($status == '3' || $status == 'ST_DONE') {
5070 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5071 } else {
5072 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);
5073 }
5074 } elseif ($mode == 3) {
5075 if ($status == '-1' || $status == 'ST_NO') {
5076 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
5077 } elseif ($status == '0' || $status == 'ST_NEVER') {
5078 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
5079 } elseif ($status == '1' || $status == 'ST_TODO') {
5080 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
5081 } elseif ($status == '2' || $status == 'ST_PEND') {
5082 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
5083 } elseif ($status == '3' || $status == 'ST_DONE') {
5084 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
5085 } else {
5086 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
5087 }
5088 } elseif ($mode == 4) {
5089 if ($status == '-1' || $status == 'ST_NO') {
5090 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5091 } elseif ($status == '0' || $status == 'ST_NEVER') {
5092 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5093 } elseif ($status == '1' || $status == 'ST_TODO') {
5094 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5095 } elseif ($status == '2' || $status == 'ST_PEND') {
5096 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5097 } elseif ($status == '3' || $status == 'ST_DONE') {
5098 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5099 } else {
5100 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);
5101 }
5102 }
5103
5104 return "Error, mode/status not found";
5105 }
5106
5113 public function getOutstandingProposals($mode = 'customer')
5114 {
5115 $table = 'propal';
5116 if ($mode == 'supplier') {
5117 $table = 'supplier_proposal';
5118 }
5119
5120 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5121 $sql .= " WHERE fk_soc = ".((int) $this->id);
5122 if ($mode == 'supplier') {
5123 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
5124 } else {
5125 $sql .= " AND entity IN (".getEntity('propal').")";
5126 }
5127
5128 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
5129
5130 $resql = $this->db->query($sql);
5131 if ($resql) {
5132 $outstandingOpened = 0;
5133 $outstandingTotal = 0;
5134 $outstandingTotalIncTax = 0;
5135 $arrayofref = array();
5136 while ($obj = $this->db->fetch_object($resql)) {
5137 $arrayofref[$obj->rowid] = $obj->ref;
5138 $outstandingTotal += $obj->total_ht;
5139 $outstandingTotalIncTax += $obj->total_ttc;
5140 if ($obj->status != 0) {
5141 // Not a draft
5142 $outstandingOpened += $obj->total_ttc;
5143 }
5144 }
5145 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5146 } else {
5147 return array();
5148 }
5149 }
5150
5157 public function getOutstandingOrders($mode = 'customer')
5158 {
5159 $table = 'commande';
5160 if ($mode == 'supplier') {
5161 $table = 'commande_fournisseur';
5162 }
5163
5164 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5165 $sql .= " WHERE fk_soc = ".((int) $this->id);
5166 if ($mode == 'supplier') {
5167 $sql .= " AND entity IN (".getEntity('supplier_order').")";
5168 } else {
5169 $sql .= " AND entity IN (".getEntity('commande').")";
5170 }
5171
5172 dol_syslog("getOutstandingOrders", LOG_DEBUG);
5173 $resql = $this->db->query($sql);
5174 if ($resql) {
5175 $outstandingOpened = 0;
5176 $outstandingTotal = 0;
5177 $outstandingTotalIncTax = 0;
5178 $arrayofref = array();
5179 while ($obj = $this->db->fetch_object($resql)) {
5180 $arrayofref[$obj->rowid] = $obj->ref;
5181 $outstandingTotal += $obj->total_ht;
5182 $outstandingTotalIncTax += $obj->total_ttc;
5183 if ($obj->status != 0) {
5184 // Not a draft
5185 $outstandingOpened += $obj->total_ttc;
5186 }
5187 }
5188 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5189 } else {
5190 return array();
5191 }
5192 }
5193
5201 public function getOutstandingBills($mode = 'customer', $late = 0)
5202 {
5203 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5204
5205 $table = 'facture';
5206 if ($mode == 'supplier') {
5207 $table = 'facture_fourn';
5208 }
5209
5210 /* Accurate value of remain to pay is to sum remaintopay for each invoice
5211 $paiement = $invoice->getSommePaiement();
5212 $creditnotes=$invoice->getSumCreditNotesUsed();
5213 $deposits=$invoice->getSumDepositsUsed();
5214 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
5215 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
5216 */
5217 $today = dol_get_first_hour(dol_now('tzuser')); // Returns today at 00:00 in the user's time zone
5218
5219 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
5220 $sql .= " WHERE fk_soc = ".((int) $this->id);
5221 if (!empty($late)) {
5222 $sql .= " AND date_lim_reglement < '".$this->db->idate($today)."'";
5223 }
5224 if ($mode == 'supplier') {
5225 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
5226 } else {
5227 $sql .= " AND entity IN (".getEntity('invoice').")";
5228 }
5229
5230 dol_syslog("getOutstandingBills", LOG_DEBUG);
5231 $resql = $this->db->query($sql);
5232 if ($resql) {
5233 $outstandingOpened = 0;
5234 $outstandingTotal = 0;
5235 $outstandingTotalIncTax = 0;
5236 $arrayofref = array();
5237 $arrayofrefopened = array();
5238 if ($mode == 'supplier') {
5239 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5240 $tmpobject = new FactureFournisseur($this->db);
5241 } else {
5242 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
5243 $tmpobject = new Facture($this->db);
5244 }
5245 while ($obj = $this->db->fetch_object($resql)) {
5246 $arrayofref[$obj->rowid] = $obj->ref;
5247 $tmpobject->id = $obj->rowid;
5248
5249 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5250 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5251 ) {
5252 $outstandingTotal += $obj->total_ht;
5253 $outstandingTotalIncTax += $obj->total_ttc;
5254 }
5255
5256 $remaintopay = 0;
5257
5258 if ($obj->paye == 0
5259 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5260 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5261 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5262 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5263 $paiement = $tmpobject->getSommePaiement();
5264 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5265 $deposits = $tmpobject->getSumDepositsUsed();
5266
5267 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5268 $outstandingOpened += $remaintopay;
5269 }
5270
5271 //if credit note is converted but not used
5272 // TODO Do this also for customer ?
5273 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5274 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5275 $remaintopay -= $remainingcreditnote;
5276 $outstandingOpened -= $remainingcreditnote;
5277 }
5278
5279 if ($remaintopay) {
5280 $arrayofrefopened[$obj->rowid] = $obj->ref;
5281 }
5282 }
5283 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'incl taxes'
5284 } else {
5285 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5286 return array();
5287 }
5288 }
5289
5296 public function getLibCustProspStatut()
5297 {
5298 return $this->LibCustProspStatut($this->client);
5299 }
5300
5301 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5308 public function LibCustProspStatut($status)
5309 {
5310 // phpcs:enable
5311 global $langs;
5312 $langs->load('companies');
5313
5314 if ($status == 0) {
5315 return $langs->trans("NorProspectNorCustomer");
5316 } elseif ($status == 1) {
5317 return $langs->trans("Customer");
5318 } elseif ($status == 2) {
5319 return $langs->trans("Prospect");
5320 } elseif ($status == 3) {
5321 return $langs->trans("ProspectCustomer");
5322 }
5323
5324 return '';
5325 }
5326
5327
5339 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5340 {
5341 global $langs;
5342
5343 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5344 $modelpath = "core/modules/bank/doc/";
5345
5346 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5347 $companybankaccount = new CompanyBankAccount($this->db);
5348 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5349 if (!$result) {
5350 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5351 }
5352 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5353 $this->last_main_doc = $companybankaccount->last_main_doc;
5354 } else {
5355 // Positionne le modele sur le nom du modele a utiliser
5356 if (!dol_strlen($modele)) {
5357 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5358 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5359 } else {
5360 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5361 return 0;
5362 }
5363 }
5364
5365 if (!isset($this->bank_account)) {
5366 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5367 $bac = new CompanyBankAccount($this->db);
5368 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5369 $result = $bac->fetch(0, '', $this->id);
5370 if ($result > 0) {
5371 $this->bank_account = $bac;
5372 } else {
5373 $this->bank_account = '';
5374 }
5375 }
5376
5377 $modelpath = "core/modules/societe/doc/";
5378
5379 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5380 }
5381
5382 return $result;
5383 }
5384
5385
5397 public function setCategories($categories, $type_categ)
5398 {
5399 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5400
5401 // Decode type
5402 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5403 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5404 return -1;
5405 }
5406
5407 return parent::setCategoriesCommon($categories, $type_categ);
5408 }
5409
5417 public function setSalesRep($salesrep, $onlyAdd = false)
5418 {
5419 global $user;
5420
5421 // Handle single user
5422 if (!is_array($salesrep)) {
5423 $salesrep = array($salesrep);
5424 }
5425
5426 $to_del = array(); // Nothing to delete
5427 $to_add = $salesrep;
5428 if ($onlyAdd === false) {
5429 // Get current users
5430 $existing = $this->getSalesRepresentatives($user, 1);
5431
5432 // Diff
5433 if (is_array($existing)) {
5434 $to_del = array_diff($existing, $salesrep);
5435 $to_add = array_diff($salesrep, $existing);
5436 }
5437 }
5438
5439 $error = 0;
5440
5441 // Process
5442 foreach ($to_del as $del) {
5443 $this->del_commercial($user, $del);
5444 }
5445 foreach ($to_add as $add) {
5446 $result = $this->add_commercial($user, $add);
5447 if ($result < 0) {
5448 $error++;
5449 break;
5450 }
5451 }
5452
5453 return $error ? -1 : 1;
5454 }
5455
5462 public function setThirdpartyType($typent_id)
5463 {
5464 global $user;
5465
5466 dol_syslog(__METHOD__, LOG_DEBUG);
5467
5468 if ($this->id) {
5469 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5470
5471 if ($result > 0) {
5472 $this->typent_id = $typent_id;
5473 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5474 return 1;
5475 } else {
5476 return -1;
5477 }
5478 } else {
5479 return -1;
5480 }
5481 }
5482
5492 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5493 {
5494 if ($origin_id == $dest_id) {
5495 dol_syslog('Error: Try to merge a thirdparty into itself');
5496 return false;
5497 }
5498
5499 // 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.
5500 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5501 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5502 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5503 $sql .= ' SELECT fk_user ';
5504 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5505 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5506
5507 $resql = $dbs->query($sql);
5508 while ($obj = $dbs->fetch_object($resql)) {
5509 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5510 }
5511
5512 // The table llx_societe_extrafields must NOT be in this list because we don't care about the old thirdparty extrafields that are managed directly into mergeCompany.
5513 // Do not include llx_societe because it will be replaced later.
5514 $tables = array(
5515 'societe_account',
5516 'societe_commerciaux',
5517 'societe_prices',
5518 'societe_remise',
5519 'societe_remise_except',
5520 'societe_rib'
5521 );
5522
5523 // TODO When we merge societe_account, we may get 2 lines for the stripe account. Must fix this.
5524
5525 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5526 }
5527
5536 public function setAccountancyCode($type, $value)
5537 {
5538 global $user, $langs, $conf;
5539
5540 $this->db->begin();
5541
5542 if ($type == 'buy') {
5543 $field = 'accountancy_code_buy';
5544 } elseif ($type == 'sell') {
5545 $field = 'accountancy_code_sell';
5546 } else {
5547 return -1;
5548 }
5549
5550 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5551 $sql .= $field." = '".$this->db->escape($value)."'";
5552 $sql .= " WHERE rowid = ".((int) $this->id);
5553
5554 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5555 $resql = $this->db->query($sql);
5556
5557 if ($resql) {
5558 // Call triggers
5559 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5560 $interface = new Interfaces($this->db);
5561 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5562 if ($result < 0) {
5563 $this->errors = $interface->errors;
5564 $this->db->rollback();
5565 return -1;
5566 }
5567 // End call triggers
5568
5569 $this->$field = $value;
5570
5571 $this->db->commit();
5572 return 1;
5573 } else {
5574 $this->error = $this->db->lasterror();
5575 $this->db->rollback();
5576 return -1;
5577 }
5578 }
5579
5586 public function fetchPartnerships($mode)
5587 {
5588 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5589
5590 $this->partnerships[] = array();
5591
5592 return 1;
5593 }
5594
5602 public function getKanbanView($option = '', $arraydata = array())
5603 {
5604 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5605
5606 $return = '<div class="box-flex-item box-flex-grow-zero">';
5607 $return .= '<div class="info-box info-box-sm">';
5608 $return .= '<span class="info-box-icon bg-infobox-action">';
5609 $return .= img_picto('', $this->picto);
5610 $return .= '</span>';
5611 $return .= '<div class="info-box-content">';
5612 $return .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref);
5613 $return .= '</div>';
5614 if (!empty($this->phone)) {
5615 $return .= '<div class="inline-block valignmiddle">';
5616 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5617 $return .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
5618 $return .= '</div>';
5619 }
5620 if (!empty($this->email)) {
5621 $return .= '<div class="inline-block valignmiddle">';
5622 $return .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
5623 $return .= '</div>';
5624 }
5625 if ($selected >= 0) {
5626 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5627 }
5628 if (property_exists($this, 'code_client')) {
5629 $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5630 }
5631 if (method_exists($this, 'getLibStatut')) {
5632 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5633 }
5634 $return .= '</div>'; // end info-box-content
5635 $return .= '</div>';
5636 $return .= '</div>';
5637
5638 return $return;
5639 }
5640
5649 public function getContacts($list = 0, $code = '', $element = '')
5650 {
5651 // phpcs:enable
5652 global $langs;
5653
5654 $tab = array();
5655
5656 $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
5657 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5658 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5659 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5660 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5661 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5662 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5663 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5664 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5665 if (!empty($element)) {
5666 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5667 }
5668 if ($code) {
5669 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5670 }
5671 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5672 $sql .= " AND tc.source = 'external'";
5673 $sql .= " AND tc.active = 1";
5674
5675 $sql .= " ORDER BY t.lastname ASC";
5676
5677 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5678 $resql = $this->db->query($sql);
5679 if ($resql) {
5680 $num = $this->db->num_rows($resql);
5681 $i = 0;
5682 while ($i < $num) {
5683 $obj = $this->db->fetch_object($resql);
5684
5685 if (!$list) {
5686 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5687 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5688 $tab[$i] = array(
5689 'source' => $obj->source,
5690 'socid' => $obj->socid,
5691 'id' => $obj->id,
5692 'nom' => $obj->lastname, // For backward compatibility
5693 'civility' => $obj->civility,
5694 'lastname' => $obj->lastname,
5695 'firstname' => $obj->firstname,
5696 'email' => $obj->email,
5697 'login' => (empty($obj->login) ? '' : $obj->login),
5698 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5699 'statuscontact' => $obj->statuscontact,
5700 'rowid' => $obj->rowid,
5701 'code' => $obj->code,
5702 'element' => $obj->element,
5703 'libelle' => $libelle_type,
5704 'status' => $obj->statuslink,
5705 'fk_c_type_contact' => $obj->fk_c_type_contact
5706 );
5707 } else {
5708 $tab[$i] = $obj->id;
5709 }
5710
5711 $i++;
5712 }
5713
5714 return $tab;
5715 } else {
5716 $this->error = $this->db->lasterror();
5717 dol_print_error($this->db);
5718 return -1;
5719 }
5720 }
5721
5732 public function mergeCompany($soc_origin_id)
5733 {
5734 global $conf, $langs, $hookmanager, $user, $action;
5735
5736 $error = 0;
5737 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5738
5739 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5740
5741 if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5742 $this->error = $langs->trans('ErrorRecordNotFound');
5743 $error++;
5744 }
5745
5746 if (!$error) {
5747 $this->db->begin();
5748
5749 // Recopy some data
5750 $this->client |= $soc_origin->client;
5751 $this->fournisseur |= $soc_origin->fournisseur;
5752 $listofproperties = array(
5753 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5754 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5755 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5756 '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',
5757 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5758 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5759 );
5760 foreach ($listofproperties as $property) {
5761 if (empty($this->$property)) {
5762 $this->$property = $soc_origin->$property;
5763 }
5764 }
5765
5766 if ($this->typent_id == -1) {
5767 $this->typent_id = $soc_origin->typent_id;
5768 }
5769
5770 // Concat some data
5771 $listofproperties = array(
5772 'note_public', 'note_private'
5773 );
5774 foreach ($listofproperties as $property) {
5775 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5776 }
5777
5778 // Merge extrafields
5779 if (is_array($soc_origin->array_options)) {
5780 foreach ($soc_origin->array_options as $key => $val) {
5781 if (empty($this->array_options[$key])) {
5782 $this->array_options[$key] = $val;
5783 }
5784 }
5785 }
5786
5787 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5788 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5789 $this->name_bis = $this->name;
5790 }
5791
5792 // Merge categories
5793 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5794 $static_cat = new Categorie($this->db);
5795
5796 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5797 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5798 $custcats = array_merge($custcats, $custcats_ori);
5799 $this->setCategories($custcats, 'customer');
5800
5801 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5802 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5803 $suppcats = array_merge($suppcats, $suppcats_ori);
5804 $this->setCategories($suppcats, 'supplier');
5805
5806 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5807 if ($soc_origin->code_client == $this->code_client
5808 || $soc_origin->code_fournisseur == $this->code_fournisseur
5809 || $soc_origin->barcode == $this->barcode) {
5810 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5811 $soc_origin->code_client = '';
5812 $soc_origin->code_fournisseur = '';
5813 $soc_origin->barcode = '';
5814 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5815 }
5816
5817 // Update
5818 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5819
5820 if ($result < 0) {
5821 $error++;
5822 }
5823
5824 // Move links
5825 if (!$error) {
5826 $objects = array(
5827 'Adherent' => '/adherents/class/adherent.class.php',
5828 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5829 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5830 'Propal' => '/comm/propal/class/propal.class.php',
5831 'Commande' => '/commande/class/commande.class.php',
5832 'Facture' => '/compta/facture/class/facture.class.php',
5833 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5834 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5835 'Contact' => '/contact/class/contact.class.php',
5836 'Contrat' => '/contrat/class/contrat.class.php',
5837 'Expedition' => '/expedition/class/expedition.class.php',
5838 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5839 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5840 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5841 'Reception' => '/reception/class/reception.class.php',
5842 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5843 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5844 'Product' => '/product/class/product.class.php',
5845 //'ProductThirparty' => '...', // for llx_product_thirdparty
5846 'Project' => '/projet/class/project.class.php',
5847 'User' => '/user/class/user.class.php',
5848 'Account' => '/compta/bank/class/account.class.php',
5849 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5850 'Societe' => '/societe/class/societe.class.php',
5851 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
5852 );
5853 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5854 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5855 }
5856 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5857 $objects['Mo'] = '/mrp/class/mo.class.php';
5858 }
5859 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5860 $objects['Don'] = '/don/class/don.class.php';
5861 }
5862 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5863 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5864 }
5865 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5866 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5867 }
5868 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5869 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5870 }
5871
5872 //First, all core objects must update their tables
5873 foreach ($objects as $object_name => $object_file) {
5874 /* $object_file is never an array -> code commented
5875 if (is_array($object_file)) {
5876 if (empty($object_file['enabled'])) {
5877 continue;
5878 }
5879 $object_file = $object_file['file'];
5880 }
5881 */
5882
5883 require_once DOL_DOCUMENT_ROOT.$object_file;
5884
5885 if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5886 $error++;
5887 $this->error = $this->db->lasterror();
5888 break;
5889 }
5890 }
5891 }
5892
5893 // External modules should update their ones too
5894 if (!$error) {
5895 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5896 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5897
5898 if ($reshook < 0) {
5899 $this->error = $hookmanager->error;
5900 $this->errors = $hookmanager->errors;
5901 $error++;
5902 }
5903 }
5904
5905
5906 if (!$error) {
5907 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5908
5909 // Call trigger
5910 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5911 if ($result < 0) {
5912 $error++;
5913 }
5914 // End call triggers
5915 }
5916
5917 if (!$error) {
5918 // We finally remove the old thirdparty
5919 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5920 $this->error = $soc_origin->error;
5921 $this->errors = $soc_origin->errors;
5922 $error++;
5923 }
5924 }
5925
5926
5927 if (!$error) {
5928 // Move files from the dir of the third party to delete into the dir of the third party to keep
5929 if (!empty($conf->societe->multidir_output[$this->entity])) {
5930 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5931 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5932
5933 if (dol_is_dir($srcdir)) {
5934 $dirlist = dol_dir_list($srcdir, 'files', 1);
5935 foreach ($dirlist as $filetomove) {
5936 $destfile = $destdir.'/'.$filetomove['relativename'];
5937 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5938 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5939 }
5940 //exit;
5941 }
5942 }
5943 }
5944
5945 if (!$error) {
5946 $this->db->commit();
5947 return 0;
5948 } else {
5949 $langs->load("errors");
5950 $this->error = $langs->trans('ErrorsThirdpartyMerge');
5951 $this->db->rollback();
5952 return -1;
5953 }
5954 }
5955
5956 return -1;
5957 }
5958}
$object ref
Definition info.php:90
Class to manage members of a foundation.
Class to manage withdrawal receipts.
Class to manage categories.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
setErrorsFromObject($object)
setErrorsFromObject
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
deleteExtraFields()
Delete all extra fields values for the current object.
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra languages values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
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 getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage third parties objects (customers, suppliers, prospects...)
setParent($id)
Define parent company of current company.
getLibProspLevel()
Return prostect level.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
setAsCustomer()
Define third party as a customer.
findNearest($rowid=0, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Search the thirdparty that match the most the provided parameters.
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
contact_get_property($rowid, $mode)
Return property of contact from its id.
check_codeclient()
Check customer code.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
isInSEPA()
Return if a company is inside the SEPA zone (Single Euro Payment Area)
getContacts($list=0, $code='', $element='')
Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for a...
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
get_all_rib()
Return Array of RIB.
get_codecompta($type)
Assigns a accounting code from the accounting code module.
__construct($db)
Constructor.
del_commercial(User $user, $commid)
Add link to sales representative.
info($id)
Load information for tab info.
has_projects()
Indicates if the company has projects.
setThirdpartyType($typent_id)
Define third-party type of current company.
isACompany()
Check if third party is a company (Business) or an end user (Consumer)
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
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 $mysoc in most ca...
id_prof_verifiable($idprof)
Returns if a profid should be verified to be unique.
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
getParentsForCompany($company_id, $parents=array())
Get parents for company.
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0, $price_base_type='HT')
Add a discount for third party.
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
const CUSTOMER
Third party type is a customer.
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Load a third party from database into memory.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
LoadSupplierCateg()
Load the list of provider categories.
getAvailableDiscounts($user=null, $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company.
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
contact_array_objects()
Return the contact list of this company.
isInEEC()
Return if a company is inside the EEC (European Economic Community)
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
fetchPartnerships($mode)
Function to get partnerships array.
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
mergeCompany($soc_origin_id)
Merge a company with current one, deleting the given company $soc_origin_id.
const NO_SUPPLIER
Third party supplier flag is not supplier.
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
setNoEmail($no_email, $unsubscribegroup='')
Set "blacklist" mailing status.
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
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.
deprecatedProperties()
Provide list of deprecated properties and replacements.
getTooltipContentArray($params)
getTooltipContentArray
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
getKanbanView($option='', $arraydata=array())
Return clickable link of object (with optional picto)
const SUPPLIER
Third party supplier flag is a supplier.
check_codefournisseur()
Check supplier code.
contact_array()
Return the contact list of this company.
initAsSpecimen()
Initialise an instance with random values.
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
setMysoc(Conf $conf)
Set properties with value into $conf.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
trait CommonSocialNetworks
Superclass for social networks.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:660
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=0)
Move a file into another name.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
div refaddress div address
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
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:161