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->multicurrency_amount_ttc = price2num($remise * (float) $discount->multicurrency_tx, 'MT');
2765 $discount->multicurrency_amount_ht = price2num(((float) $remise / (1 + (float) $vatrate / 100)) * (float) $discount->multicurrency_tx, 'MT');
2766 $discount->multicurrency_amount_tva = price2num(((float) $discount->amount_ttc - (float) $discount->amount_ht) * (float) $discount->multicurrency_tx, 'MT');
2767
2768 $discount->amount_ttc = price2num($remise, 'MT');
2769 $discount->amount_ht = price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2770 $discount->amount_tva = price2num((float) $discount->amount_ttc - (float) $discount->amount_ht, 'MT');
2771 } else {
2772 $discount->amount_ht = price2num($remise, 'MT');
2773 $discount->amount_tva = price2num((float) $remise * (float) $vatrate / 100, 'MT');
2774 $discount->amount_ttc = price2num((float) $discount->amount_ht + (float) $discount->amount_tva, 'MT');
2775
2776 $discount->multicurrency_amount_ht = price2num($remise * (float) $discount->multicurrency_tx, 'MT');
2777 $discount->multicurrency_amount_tva = price2num(((float) $remise * (float) $vatrate / 100) * (float) $discount->multicurrency_tx, 'MT');
2778 $discount->multicurrency_amount_ttc = price2num(((float) $discount->amount_ht + (float) $discount->amount_tva) * (float) $discount->multicurrency_tx, 'MT');
2779 }
2780
2781 $discount->tva_tx = (float) price2num($vatrate);
2782 $discount->vat_src_code = $vat_src_code;
2783
2784 $discount->description = $desc;
2785
2786 $result = $discount->create($user);
2787 if ($result > 0) {
2788 return $result;
2789 } else {
2790 $this->error = $discount->error;
2791 return -3;
2792 }
2793 } else {
2794 return 0;
2795 }
2796 }
2797
2807 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2808 {
2809 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2810
2811 $discountstatic = new DiscountAbsolute($this->db);
2812 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2813 if ($result >= 0) {
2814 return $result;
2815 } else {
2816 $this->error = $discountstatic->error;
2817 return -1;
2818 }
2819 }
2820
2830 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2831 {
2832 global $conf;
2833
2834 $reparray = array();
2835
2836 $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";
2837 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2838 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2839 // Condition here should be the same than into select_dolusers()
2840 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2841 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2842 } else {
2843 $sql .= " WHERE entity IN (0, ".((int) $conf->entity).")";
2844 }
2845
2846 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2847 if (empty($sortfield)) {
2848 $sortfield = 'u.lastname,u.firstname';
2849 }
2850 if (empty($sortorder)) {
2851 $sortorder = str_repeat('ASC,', count(explode(',', $sortfield)) - 1) . 'ASC';
2852 }
2853 $sql .= $this->db->order($sortfield, $sortorder);
2854
2855 $resql = $this->db->query($sql);
2856 if ($resql) {
2857 $num = $this->db->num_rows($resql);
2858 $i = 0;
2859 while ($i < $num) {
2860 $obj = $this->db->fetch_object($resql);
2861
2862 if (empty($mode)) {
2863 $reparray[$i]['id'] = (int) $obj->rowid;
2864 $reparray[$i]['lastname'] = $obj->lastname;
2865 $reparray[$i]['firstname'] = $obj->firstname;
2866 $reparray[$i]['email'] = $obj->email;
2867 $reparray[$i]['phone'] = $obj->office_phone;
2868 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2869 $reparray[$i]['office_fax'] = $obj->office_fax;
2870 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2871 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2872 $reparray[$i]['job'] = $obj->job;
2873 $reparray[$i]['statut'] = $obj->status; // deprecated
2874 $reparray[$i]['status'] = $obj->status;
2875 $reparray[$i]['entity'] = $obj->entity;
2876 $reparray[$i]['login'] = $obj->login;
2877 $reparray[$i]['photo'] = $obj->photo;
2878 $reparray[$i]['gender'] = $obj->gender;
2879 } else {
2880 $reparray[] = (int) $obj->rowid;
2881 }
2882 $i++;
2883 }
2884 return $reparray;
2885 } else {
2886 dol_print_error($this->db);
2887 return -1;
2888 }
2889 }
2890
2898 public function setPriceLevel($price_level, User $user)
2899 {
2900 if ($this->id) {
2901 $now = dol_now();
2902
2903 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2904 $sql .= " SET price_level = ".((int) $price_level);
2905 $sql .= " WHERE rowid = ".((int) $this->id);
2906
2907 if (!$this->db->query($sql)) {
2908 dol_print_error($this->db);
2909 return -1;
2910 }
2911
2912 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2913 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2914 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2915
2916 if (!$this->db->query($sql)) {
2917 dol_print_error($this->db);
2918 return -1;
2919 }
2920 return 1;
2921 }
2922 return -1;
2923 }
2924
2925 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2933 public function add_commercial(User $user, $commid)
2934 {
2935 // phpcs:enable
2936 $error = 0;
2937
2938 if ($this->id > 0 && $commid > 0) {
2939 $this->db->begin();
2940
2941 if (!$error) {
2942 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2943 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2944
2945 $resql = $this->db->query($sql);
2946 if (!$resql) {
2947 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2948 $error++;
2949 }
2950 }
2951
2952 if (!$error) {
2953 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2954 $sql .= " (fk_soc, fk_user)";
2955 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2956
2957 $resql = $this->db->query($sql);
2958 if (!$resql) {
2959 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2960 $error++;
2961 }
2962 }
2963
2964 if (!$error) {
2965 $this->context = array('commercial_modified' => $commid);
2966
2967 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2968 if ($result < 0) {
2969 $error++;
2970 }
2971 }
2972
2973 if (!$error) {
2974 $this->db->commit();
2975 return 1;
2976 } else {
2977 $this->db->rollback();
2978 return -1;
2979 }
2980 }
2981
2982 return 0;
2983 }
2984
2985 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2993 public function del_commercial(User $user, $commid)
2994 {
2995 // phpcs:enable
2996 $error = 0;
2997 $this->context = array('commercial_modified' => $commid);
2998
2999 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
3000 if ($result < 0) {
3001 $error++;
3002 }
3003
3004 if ($this->id > 0 && $commid > 0) {
3005 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
3006 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3007
3008 if (!$this->db->query($sql)) {
3009 $error++;
3010 dol_syslog(get_class($this)."::del_commercial Erreur");
3011 }
3012 }
3013
3014 if ($error) {
3015 return -1;
3016 } else {
3017 return 1;
3018 }
3019 }
3020
3028 public function getTooltipContentArray($params)
3029 {
3030 global $conf, $langs, $user;
3031
3032 $langs->loadLangs(['companies', 'commercial']);
3033
3034 $datas = array();
3035
3036 $option = $params['option'] ?? '';
3037 $nofetch = !empty($params['nofetch']);
3038
3039 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
3040
3041 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3042 return ['optimize' => $langs->trans("ShowCompany")];
3043 }
3044
3045 if (!empty($this->logo) && class_exists('Form')) {
3046 $photo = '<div class="photointooltip floatright">';
3047 $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.
3048 $photo .= '</div>';
3049 $datas['photo'] = $photo;
3050 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
3051 /*$label.= '<div class="photointooltip">';
3052 $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.
3053 $label.= '</div><div style="clear: both;"></div>';*/
3054 // }
3055
3056 $datas['divopen'] = '<div class="centpercent">';
3057
3058 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3059 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
3060 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3061 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
3062 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3063 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
3064 } elseif ($option == 'agenda') {
3065 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3066 } elseif ($option == 'project') {
3067 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3068 } elseif ($option == 'margin') {
3069 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3070 } elseif ($option == 'contact') {
3071 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3072 } elseif ($option == 'ban') {
3073 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3074 }
3075
3076 // By default
3077 if (empty($datas['picto'])) {
3078 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3079 }
3080 if (isset($this->status)) {
3081 $datas['status'] = ' '.$this->getLibStatut(5);
3082 }
3083 if (isset($this->client) && isset($this->fournisseur)) {
3084 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1, '', 0, 'span');
3085 }
3086 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
3087 if (!empty($this->name_alias) && empty($noaliasinname)) {
3088 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
3089 }
3090 if (!empty($this->email)) {
3091 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
3092 }
3093 if (!empty($this->url)) {
3094 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
3095 }
3096 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
3097 $phonelist = array();
3098 if ($this->phone) {
3099 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3100 }
3101 // deliberately not making new list because fax uses same list as phone
3102 if ($this->phone_mobile) {
3103 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3104 }
3105 if ($this->fax) {
3106 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3107 }
3108 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
3109 }
3110
3111 if (!empty($this->address)) {
3112 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ', ', $langs); // Address + country
3113 } elseif (!empty($this->country_code)) {
3114 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
3115 }
3116 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
3117 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
3118 }
3119
3120 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
3121 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
3122 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
3123 }
3124 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
3125 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
3126 }
3127 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
3128 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
3129 }
3130 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
3131 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
3132 }
3133 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
3134 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
3135 }
3136 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
3137 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
3138 }
3139 }
3140
3141 $datas['separator'] = '<br>';
3142
3143 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
3144 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
3145 }
3146 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
3147 $langs->load('compta');
3148 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
3149 }
3150 // show categories for this record only in ajax to not overload lists
3151 if (!$nofetch && isModEnabled('category') && $this->client) {
3152 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3153 $form = new Form($this->db);
3154 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
3155 }
3156 if (!empty($this->code_fournisseur) && $this->fournisseur) {
3157 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
3158 }
3159 if (isModEnabled('accounting') && $this->fournisseur) {
3160 $langs->load('compta');
3161 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
3162 }
3163 // show categories for this record only in ajax to not overload lists
3164 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
3165 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3166 $form = new Form($this->db);
3167 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
3168 }
3169
3170 $datas['divclose'] = '</div>';
3171
3172 return $datas;
3173 }
3174
3188 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
3189 {
3190 global $conf, $langs, $hookmanager, $user;
3191
3192 if (!empty($conf->dol_no_mouse_hover)) {
3193 $notooltip = 1; // Force disable tooltips
3194 }
3195
3196 $name = $this->name ? $this->name : $this->nom;
3197
3198 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3199 if (empty($option) && $this->client > 0) {
3200 $option = 'customer';
3201 }
3202 if (empty($option) && $this->fournisseur > 0) {
3203 $option = 'supplier';
3204 }
3205 }
3206
3207 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3208 $code = '';
3209 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3210 $code = $this->code_client.' - ';
3211 }
3212
3213 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3214 $code .= $this->code_fournisseur.' - ';
3215 }
3216
3217 if ($code) {
3218 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3219 $name = $code.' '.$name;
3220 } else {
3221 $name = $code;
3222 }
3223 }
3224 }
3225
3226 if (!empty($this->name_alias) && empty($noaliasinname)) {
3227 $name .= ' ('.$this->name_alias.')';
3228 }
3229
3230 $result = '';
3231 $params = [
3232 'id' => $this->id,
3233 'objecttype' => $this->element,
3234 'option' => $option,
3235 'nofetch' => 1,
3236 ];
3237 $classfortooltip = 'classfortooltip';
3238 $dataparams = '';
3239 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3240 $classfortooltip = 'classforajaxtooltip';
3241 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3242 $label = '';
3243 } else {
3244 $label = implode($this->getTooltipContentArray($params));
3245 }
3246
3247 $linkstart = '';
3248 $linkend = '';
3249
3250 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3251 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3252 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3253 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3254 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3255 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3256 } elseif ($option == 'agenda') {
3257 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3258 } elseif ($option == 'project') {
3259 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3260 } elseif ($option == 'margin') {
3261 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3262 } elseif ($option == 'contact') {
3263 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3264 } elseif ($option == 'ban') {
3265 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3266 }
3267
3268 // By default
3269 if (empty($linkstart)) {
3270 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3271 }
3272
3273 // Add type of canvas
3274 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3275 // Add param to save lastsearch_values or not
3276 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3277 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3278 $add_save_lastsearch_values = 1;
3279 }
3280 if ($add_save_lastsearch_values) {
3281 $linkstart .= '&save_lastsearch_values=1';
3282 }
3283 $linkstart .= '"';
3284
3285 $linkclose = '';
3286 if (empty($notooltip)) {
3287 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3288 $label = $langs->trans("ShowCompany");
3289 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3290 }
3291 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3292 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
3293 $target_value = array('_self', '_blank', '_parent', '_top');
3294 if (in_array($target, $target_value)) {
3295 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3296 }
3297 } else {
3298 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3299 }
3300 $linkstart .= $linkclose.'>';
3301 $linkend = '</a>';
3302
3303 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3304 $linkstart = '';
3305 $linkend = '';
3306 }
3307
3308 $result .= $linkstart;
3309 if ($withpicto) {
3310 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3311 }
3312 if ($withpicto != 2) {
3313 $result .= dol_escape_htmltag($maxlen ? dol_trunc((string) $name, $maxlen) : $name);
3314 }
3315 $result .= $linkend;
3316
3317 global $action;
3318 $hookmanager->initHooks(array('thirdpartydao'));
3319 $parameters = array(
3320 'id' => $this->id,
3321 'getnomurl' => &$result,
3322 'withpicto ' => $withpicto,
3323 'option' => $option,
3324 'maxlen' => $maxlen,
3325 'notooltip' => $notooltip,
3326 'save_lastsearch_value' => $save_lastsearch_value
3327 );
3328 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3329 if ($reshook > 0) {
3330 $result = $hookmanager->resPrint;
3331 } else {
3332 $result .= $hookmanager->resPrint;
3333 }
3334
3335 return $result;
3336 }
3337
3347 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3348 {
3349 global $langs;
3350
3351 $s = '';
3352 if (empty($option) || preg_match('/prospect/', $option)) {
3353 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3354 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.dolPrintHTMLForAttribute($langs->trans("Prospect")).'"';
3355 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3356 $s .= '>'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3357 }
3358 }
3359 if (empty($option) || preg_match('/customer/', $option)) {
3360 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3361 $s .= '<'.$tag.' class="customer-back" title="'.dolPrintHTMLForAttribute($langs->trans("Customer")).'"';
3362 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3363 $s .= '>'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3364 }
3365 }
3366 if (empty($option) || preg_match('/supplier/', $option)) {
3367 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3368 $s .= '<'.$tag.' class="vendor-back" title="'.dolPrintHTMLForAttribute($langs->trans("Supplier")).'"';
3369 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'"' : '';
3370 $s .= '>'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3371 }
3372 }
3373
3374 return $s;
3375 }
3376
3377
3384 public function getLibStatut($mode = 0)
3385 {
3386 return $this->LibStatut($this->status, $mode);
3387 }
3388
3389 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3397 public function LibStatut($status, $mode = 0)
3398 {
3399 // phpcs:enable
3400 global $langs;
3401 $langs->load('companies');
3402
3403 $statusType = 'status4';
3404 if ($status == 0) {
3405 $statusType = 'status6';
3406 }
3407
3408 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3409 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3410 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3411 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3412 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3413 }
3414
3415 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3416 }
3417
3418 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3425 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3426 {
3427 // phpcs:enable
3428 global $langs;
3429
3430 $contact_emails = $this->contact_property_array('email', 1);
3431
3432 if ($this->email && $addthirdparty) {
3433 if (empty($this->name)) {
3434 $this->name = $this->nom;
3435 }
3436 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3437 }
3438
3439 //var_dump($contact_emails)
3440 return $contact_emails;
3441 }
3442
3443 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3450 {
3451 // phpcs:enable
3452 global $langs;
3453
3454 $contact_phone = $this->contact_property_array('mobile');
3455
3456 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3457 if (empty($this->name)) {
3458 $this->name = $this->nom;
3459 }
3460 // TODO: Tester si tel non deja present dans tableau contact
3461 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3462 }
3463 return $contact_phone;
3464 }
3465
3466 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3474 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3475 {
3476 // phpcs:enable
3477 global $langs;
3478
3479 $contact_property = array();
3480
3481
3482 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3483 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3484 $sql .= " WHERE fk_soc = ".((int) $this->id);
3485 $sql .= " AND entity IN (".getEntity($this->element).")";
3486 $sql .= " ORDER BY lastname, firstname";
3487
3488 $resql = $this->db->query($sql);
3489 if ($resql) {
3490 $nump = $this->db->num_rows($resql);
3491 if ($nump) {
3492 $sepa = "(";
3493 $sepb = ")";
3494 if ($mode == 'email') {
3495 //$sepa="&lt;"; $sepb="&gt;";
3496 $sepa = "<";
3497 $sepb = ">";
3498 }
3499 $i = 0;
3500 while ($i < $nump) {
3501 $obj = $this->db->fetch_object($resql);
3502 if ($mode == 'email') {
3503 $property = $obj->email;
3504 } elseif ($mode == 'mobile') {
3505 $property = $obj->phone_mobile;
3506 } else {
3507 $property = $obj->$mode;
3508 }
3509
3510 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3511 if ($obj->status == 1 || empty($hidedisabled)) {
3512 if (empty($property)) {
3513 if ($mode == 'email') {
3514 $property = $langs->transnoentitiesnoconv("NoEMail");
3515 } elseif ($mode == 'mobile') {
3516 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3517 }
3518 }
3519
3520 if (!empty($obj->poste)) {
3521 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3522 } else {
3523 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3524 }
3525 }
3526 $i++;
3527 }
3528 }
3529 } else {
3530 dol_print_error($this->db);
3531 }
3532 return $contact_property;
3533 }
3534
3535
3536 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3542 public function contact_array()
3543 {
3544 // phpcs:enable
3545 $contacts = array();
3546
3547 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3548 $resql = $this->db->query($sql);
3549 if ($resql) {
3550 $nump = $this->db->num_rows($resql);
3551 if ($nump) {
3552 $i = 0;
3553 while ($i < $nump) {
3554 $obj = $this->db->fetch_object($resql);
3555 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3556 $i++;
3557 }
3558 }
3559 } else {
3560 dol_print_error($this->db);
3561 }
3562 return $contacts;
3563 }
3564
3565 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3571 public function contact_array_objects()
3572 {
3573 // phpcs:enable
3574 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3575 $contacts = array();
3576
3577 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3578 $resql = $this->db->query($sql);
3579 if ($resql) {
3580 $nump = $this->db->num_rows($resql);
3581 if ($nump) {
3582 $i = 0;
3583 while ($i < $nump) {
3584 $obj = $this->db->fetch_object($resql);
3585 $contact = new Contact($this->db);
3586 $contact->fetch($obj->rowid);
3587 $contacts[] = $contact;
3588 $i++;
3589 }
3590 }
3591 } else {
3592 dol_print_error($this->db);
3593 }
3594 return $contacts;
3595 }
3596
3597 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3605 public function contact_get_property($rowid, $mode)
3606 {
3607 // phpcs:enable
3608 $contact_property = '';
3609
3610 if (empty($rowid)) {
3611 return '';
3612 }
3613
3614 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3615 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3616 $sql .= " WHERE rowid = ".((int) $rowid);
3617
3618 $resql = $this->db->query($sql);
3619 if ($resql) {
3620 $nump = $this->db->num_rows($resql);
3621
3622 if ($nump) {
3623 $obj = $this->db->fetch_object($resql);
3624
3625 if ($mode == 'email') {
3626 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3627 } elseif ($mode == 'mobile') {
3628 $contact_property = $obj->phone_mobile;
3629 }
3630 }
3631 return $contact_property;
3632 } else {
3633 dol_print_error($this->db);
3634 }
3635
3636 return '';
3637 }
3638
3639
3640 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3647 public function display_rib($mode = 'label')
3648 {
3649 // phpcs:enable
3650 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3651
3652 $bac = new CompanyBankAccount($this->db);
3653 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3654 $bac->fetch(0, '', $this->id);
3655
3656 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3657 if ($mode == 'label') {
3658 return $bac->getRibLabel(true);
3659 } elseif ($mode == 'rum') {
3660 if (empty($bac->rum)) {
3661 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3662 $prelevement = new BonPrelevement($this->db);
3663 $bac->fetch_thirdparty();
3664 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, (string) $bac->id);
3665 }
3666 return $bac->rum;
3667 } elseif ($mode == 'format') {
3668 return $bac->frstrecur;
3669 } else {
3670 return 'BadParameterToFunctionDisplayRib';
3671 }
3672 } else {
3673 return '';
3674 }
3675 }
3676
3677 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3683 public function get_all_rib()
3684 {
3685 // phpcs:enable
3686 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3687 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3688 $result = $this->db->query($sql);
3689 if (!$result) {
3690 $this->error = $this->db->lasterror();
3691 $this->errors[] = $this->db->lasterror();
3692 return 0;
3693 } else {
3694 $num_rows = $this->db->num_rows($result);
3695 $rib_array = array();
3696 if ($num_rows) {
3697 while ($obj = $this->db->fetch_object($result)) {
3698 $rib = new CompanyBankAccount($this->db);
3699 $rib->fetch($obj->rowid);
3700 $rib_array[] = $rib;
3701 }
3702 }
3703 return $rib_array;
3704 }
3705 }
3706
3710 public function getDefaultRib()
3711 {
3712 // phpcs:enable
3713 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3714 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND default_rib = 1 AND fk_soc = ". (int) $this->id;
3715 $resql = $this->db->query($sql);
3716 if (!$resql) {
3717 $this->error = $this->db->lasterror();
3718 $this->errors[] = $this->db->lasterror();
3719 return -1;
3720 } else {
3721 $num_rows = $this->db->num_rows($resql);
3722 $rib_array = array();
3723 if ($num_rows) {
3724 while ($obj = $this->db->fetch_object($resql)) {
3725 return $obj->rowid;
3726 }
3727 }
3728 return 0;
3729 }
3730 }
3731
3732
3733 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3742 public function get_codeclient($objsoc = null, $type = 0)
3743 {
3744 // phpcs:enable
3745 global $conf;
3746 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3747 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3748
3749 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3750 foreach ($dirsociete as $dirroot) {
3751 $res = dol_include_once($dirroot.$module.'.php');
3752 if ($res) {
3753 break;
3754 }
3755 }
3757 $mod = new $module($this->db);
3758 '@phan-var-force ModeleThirdPartyCode $mod';
3759
3760 $this->code_client = $mod->getNextValue($objsoc, $type);
3761 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3762
3763 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3764 }
3765 }
3766
3767 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3776 public function get_codefournisseur($objsoc = null, $type = 1)
3777 {
3778 // phpcs:enable
3779 global $conf;
3780 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3781 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3782
3783 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3784 foreach ($dirsociete as $dirroot) {
3785 $res = dol_include_once($dirroot.$module.'.php');
3786 if ($res) {
3787 break;
3788 }
3789 }
3791 $mod = new $module($this->db);
3792 '@phan-var-force ModeleThirdPartyCode $mod';
3793
3794 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3795
3796 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3797 }
3798 }
3799
3800 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3807 public function codeclient_modifiable()
3808 {
3809 // phpcs:enable
3810 global $conf;
3811 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3812 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3813
3814 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3815 foreach ($dirsociete as $dirroot) {
3816 $res = dol_include_once($dirroot.$module.'.php');
3817 if ($res) {
3818 break;
3819 }
3820 }
3821
3822 $mod = new $module($this->db);
3823 '@phan-var-force ModeleThirdPartyCode $mod';
3824
3825 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3826 if ($mod->code_modifiable_null && !$this->code_client) {
3827 return 1;
3828 }
3829 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3830 return 1;
3831 }
3832 if ($mod->code_modifiable) {
3833 return 1; // A mettre en dernier
3834 }
3835 return 0;
3836 } else {
3837 return 0;
3838 }
3839 }
3840
3841
3842 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3849 {
3850 // phpcs:enable
3851 global $conf;
3852 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3853 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3854
3855 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3856 foreach ($dirsociete as $dirroot) {
3857 $res = dol_include_once($dirroot.$module.'.php');
3858 if ($res) {
3859 break;
3860 }
3861 }
3862
3863 $mod = new $module($this->db);
3864 '@phan-var-force ModeleThirdPartyCode $mod';
3865
3866 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3867 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3868 return 1;
3869 }
3870 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3871 return 1;
3872 }
3873 if ($mod->code_modifiable) {
3874 return 1; // A mettre en dernier
3875 }
3876 return 0;
3877 } else {
3878 return 0;
3879 }
3880 }
3881
3882
3883 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3895 public function check_codeclient()
3896 {
3897 // phpcs:enable
3898 global $conf;
3899 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3900 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3901
3902 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3903 foreach ($dirsociete as $dirroot) {
3904 $res = dol_include_once($dirroot.$module.'.php');
3905 if ($res) {
3906 break;
3907 }
3908 }
3909
3910 $mod = new $module($this->db);
3911 '@phan-var-force ModeleThirdPartyCode $mod';
3912
3913 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3914 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3915 if ($result) { // If error
3916 $this->error = $mod->error;
3917 $this->errors = $mod->errors;
3918 }
3919 return $result;
3920 } else {
3921 return 0;
3922 }
3923 }
3924
3925 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3937 public function check_codefournisseur()
3938 {
3939 // phpcs:enable
3940 global $conf;
3941 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3942 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3943
3944 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3945 foreach ($dirsociete as $dirroot) {
3946 $res = dol_include_once($dirroot.$module.'.php');
3947 if ($res) {
3948 break;
3949 }
3950 }
3951
3952 $mod = new $module($this->db);
3953 '@phan-var-force ModeleThirdPartyCode $mod';
3954
3955 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3956 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3957 if ($result) { // If error
3958 $this->error = $mod->error;
3959 $this->errors = $mod->errors;
3960 }
3961 return $result;
3962 } else {
3963 return 0;
3964 }
3965 }
3966
3967 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3976 public function get_codecompta($type)
3977 {
3978 // phpcs:enable
3979 global $conf;
3980
3981 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3982 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
3983 $res = false;
3984 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3985 foreach ($dirsociete as $dirroot) {
3986 $res = dol_include_once($dirroot.$module.'.php');
3987 if ($res) {
3988 break;
3989 }
3990 }
3991
3992 if ($res) {
3993 $mod = new $module();
3994 '@phan-var-force ModeleAccountancyCode $mod';
3995
3996 // Set code count in $mod->code
3997 $result = $mod->get_code($this->db, $this, $type);
3998
3999 if ($type == 'customer') {
4000 $this->code_compta_client = $mod->code;
4001 } elseif ($type == 'supplier') {
4002 $this->code_compta_fournisseur = $mod->code;
4003 }
4004
4005 return $result;
4006 } else {
4007 $this->error = 'ErrorAccountancyCodeNotDefined';
4008 return -1;
4009 }
4010 } else {
4011 if ($type == 'customer') {
4012 $this->code_compta_client = '';
4013 } elseif ($type == 'supplier') {
4014 $this->code_compta_fournisseur = '';
4015 }
4016
4017 return 0;
4018 }
4019 }
4020
4027 public function setParent($id)
4028 {
4029 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
4030
4031 if ($this->id) {
4032 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
4033 if ($id > 0) {
4034 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
4035 if ($sameparent < 0) {
4036 return -1;
4037 }
4038 if ($sameparent == 1) {
4039 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
4040 return -1;
4041 }
4042 }
4043
4044 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
4045
4046 $resql = $this->db->query($sql);
4047 if ($resql) {
4048 $this->parent = $id;
4049 return 1;
4050 } else {
4051 return -1;
4052 }
4053 }
4054
4055 return -1;
4056 }
4057
4066 public function validateFamilyTree($idparent, $idchild, $counter = 0)
4067 {
4068 if ($counter > 100) {
4069 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
4070 }
4071
4072 $sql = 'SELECT s.parent';
4073 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
4074 $sql .= ' WHERE rowid = '.((int) $idparent);
4075 $resql = $this->db->query($sql);
4076 if ($resql) {
4077 $obj = $this->db->fetch_object($resql);
4078
4079 if ($obj->parent == '') {
4080 return 0;
4081 } elseif ($obj->parent == $idchild) {
4082 return 1;
4083 } else {
4084 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
4085 }
4086 return $sameparent;
4087 } else {
4088 return -1;
4089 }
4090 }
4091
4099 public function getParentsForCompany($company_id, $parents = array())
4100 {
4101 global $langs;
4102
4103 if ($company_id > 0) {
4104 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
4105 $resql = $this->db->query($sql);
4106 if ($resql) {
4107 if ($obj = $this->db->fetch_object($resql)) {
4108 $parent = $obj->parent;
4109 if ($parent > 0 && !in_array($parent, $parents)) {
4110 $parents[] = $parent;
4111 return $this->getParentsForCompany($parent, $parents);
4112 } else {
4113 return $parents;
4114 }
4115 }
4116 $this->db->free($resql);
4117 } else {
4118 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
4119 }
4120 }
4121 // Return a default value when $company_id is not greater than 0
4122 return array();
4123 }
4124
4125 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4132 public function id_prof_verifiable($idprof)
4133 {
4134 // phpcs:enable
4135 global $conf;
4136
4137 switch ($idprof) {
4138 case 1:
4139 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
4140 break;
4141 case 2:
4142 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
4143 break;
4144 case 3:
4145 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
4146 break;
4147 case 4:
4148 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
4149 break;
4150 case 5:
4151 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
4152 break;
4153 case 6:
4154 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
4155 break;
4156 default:
4157 $ret = false;
4158 }
4159
4160 return $ret;
4161 }
4162
4163 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4172 public function id_prof_exists($idprof, $value, $socid = 0)
4173 {
4174 // phpcs:enable
4175 $field = $idprof;
4176
4177 switch ($idprof) { // For backward compatibility
4178 case '1':
4179 case 'idprof1':
4180 $field = "siren";
4181 break;
4182 case '2':
4183 case 'idprof2':
4184 $field = "siret";
4185 break;
4186 case '3':
4187 case 'idprof3':
4188 $field = "ape";
4189 break;
4190 case '4':
4191 case 'idprof4':
4192 $field = "idprof4";
4193 break;
4194 case '5':
4195 $field = "idprof5";
4196 break;
4197 case '6':
4198 $field = "idprof6";
4199 break;
4200 }
4201
4202 //Verify duplicate entries
4203 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
4204 if ($socid) {
4205 $sql .= " AND rowid <> ".$socid;
4206 }
4207 $resql = $this->db->query($sql);
4208 if ($resql) {
4209 $obj = $this->db->fetch_object($resql);
4210 $count = $obj->nb;
4211 } else {
4212 $count = 0;
4213 print $this->db->error();
4214 }
4215 $this->db->free($resql);
4216
4217 if ($count > 0) {
4218 return true;
4219 } else {
4220 return false;
4221 }
4222 }
4223
4224 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4233 public function id_prof_check($idprof, $soc)
4234 {
4235 // phpcs:enable
4236 global $conf;
4237
4238 // load the library necessary to check the professional identifiers
4239 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4240
4241 $ok = 1;
4242
4243 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4244 return 1;
4245 }
4246
4247 // Check SIREN
4248 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
4249 return -1;
4250 }
4251
4252 // Check SIRET
4253 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
4254 return -1;
4255 }
4256
4257 //Verify CIF/NIF/NIE if pays ES
4258 if ($idprof == 1 && $soc->country_code == 'ES') {
4259 return isValidTinForES($this->idprof1);
4260 }
4261
4262 //Verify NIF if country is PT
4263 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
4264 return -1;
4265 }
4266
4267 //Verify NIF if country is DZ
4268 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
4269 return -1;
4270 }
4271
4272 //Verify ID Prof 1 if country is BE
4273 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
4274 return -1;
4275 }
4276
4277 return $ok;
4278 }
4279
4280 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4289 public function id_prof_url($idprof, $thirdparty)
4290 {
4291 // phpcs:enable
4292 global $conf, $langs, $hookmanager;
4293
4294 $url = '';
4295 $action = '';
4296
4297 $hookmanager->initHooks(array('idprofurl'));
4298 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4299 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4300 if (empty($reshook)) {
4301 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4302 return '';
4303 }
4304
4305 // TODO Move links to validate professional ID into a dictionary table "country" + "link"
4306 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4307 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4308 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
4309 }
4310 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4311 $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
4312 }
4313 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4314 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
4315 }
4316 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4317 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4318 }
4319 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4320 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
4321 }
4322 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4323 $url = 'http://www.nif.pt/'.$strippedIdProf1;
4324 }
4325
4326 if ($url) {
4327 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4328 }
4329 } else {
4330 return $hookmanager->resPrint;
4331 }
4332
4333 return '';
4334 }
4335
4336 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4342 public function has_projects()
4343 {
4344 // phpcs:enable
4345 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4346 $resql = $this->db->query($sql);
4347 if ($resql) {
4348 $obj = $this->db->fetch_object($resql);
4349 $count = $obj->numproj;
4350 } else {
4351 $count = 0;
4352 print $this->db->error();
4353 }
4354 $this->db->free($resql);
4355 return ($count > 0);
4356 }
4357
4358
4365 public function info($id)
4366 {
4367 $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4368 $sql .= " fk_user_creat, fk_user_modif";
4369 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4370 $sql .= " WHERE s.rowid = ".((int) $id);
4371
4372 $result = $this->db->query($sql);
4373 if ($result) {
4374 if ($this->db->num_rows($result)) {
4375 $obj = $this->db->fetch_object($result);
4376
4377 $this->id = $obj->rowid;
4378
4379 $this->user_creation_id = $obj->fk_user_creat;
4380 $this->user_modification_id = $obj->fk_user_modif;
4381 $this->date_creation = $this->db->jdate($obj->datec);
4382 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4383
4384 $this->ref = $obj->name;
4385 }
4386
4387 $this->db->free($result);
4388 } else {
4389 dol_print_error($this->db);
4390 }
4391 }
4392
4398 public function isACompany()
4399 {
4400 // Define if third party is treated as company (or not) when nature is unknown
4401 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES', 1); // default if not set is 1 because it was like this in all past versions
4402
4403 // Now try to guess using different tips
4404 if (!empty($this->tva_intra)) {
4405 $isACompany = 1;
4406 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4407 $isACompany = 1;
4408 } else {
4409 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) { // never or rarely set
4410 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) { // TODO Add a field is_a_company into dictionary
4411 $isACompany = 0;
4412 }
4413 } else {
4414 $isACompany = 1;
4415 }
4416 }
4417
4418 return (bool) $isACompany;
4419 }
4420
4426 public function isInEEC()
4427 {
4428 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4429 return isInEEC($this);
4430 }
4431
4437 public function isInSEPA()
4438 {
4439 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4440 return isInSEPA($this);
4441 }
4442
4443 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4449 public function LoadSupplierCateg()
4450 {
4451 // phpcs:enable
4452 $this->SupplierCategories = array();
4453 $sql = "SELECT rowid, label";
4454 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4455 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4456
4457 $resql = $this->db->query($sql);
4458 if ($resql) {
4459 while ($obj = $this->db->fetch_object($resql)) {
4460 $this->SupplierCategories[$obj->rowid] = $obj->label;
4461 }
4462 return 0;
4463 } else {
4464 return -1;
4465 }
4466 }
4467
4468 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4475 public function AddFournisseurInCategory($categorie_id)
4476 {
4477 // phpcs:enable
4478 if ($categorie_id > 0 && $this->id > 0) {
4479 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4480 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4481
4482 if ($resql = $this->db->query($sql)) {
4483 return 0;
4484 }
4485 } else {
4486 return 0;
4487 }
4488 return -1;
4489 }
4490
4496 public function getNbOfEMailings()
4497 {
4498 $sql = "SELECT count(mc.email) as nb";
4499 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4500 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4501 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4502
4503 $resql = $this->db->query($sql);
4504 if ($resql) {
4505 $obj = $this->db->fetch_object($resql);
4506 $nb = $obj->nb;
4507
4508 $this->db->free($resql);
4509 return $nb;
4510 } else {
4511 $this->error = $this->db->error();
4512 return -1;
4513 }
4514 }
4515
4523 public function setNoEmail($no_email, $unsubscribegroup = '')
4524 {
4525 $error = 0;
4526
4527 // Update mass emailing flag into table mailing_unsubscribe
4528 if ($this->email) {
4529 $this->db->begin();
4530
4531 if ($no_email) {
4532 // TODO Add $unsubscribegroup
4533 $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)."'";
4534 $resql = $this->db->query($sql);
4535 if ($resql) {
4536 $obj = $this->db->fetch_object($resql);
4537 $noemail = $obj->nb;
4538 if (empty($noemail)) {
4539 // TODO Add $unsubscribegroup
4540 $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())."')";
4541 $resql = $this->db->query($sql);
4542 if (!$resql) {
4543 $error++;
4544 $this->error = $this->db->lasterror();
4545 $this->errors[] = $this->error;
4546 }
4547 }
4548 } else {
4549 $error++;
4550 $this->error = $this->db->lasterror();
4551 $this->errors[] = $this->error;
4552 }
4553 } else {
4554 // TODO Add $unsubscribegroup
4555 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4556 $resql = $this->db->query($sql);
4557 if (!$resql) {
4558 $error++;
4559 $this->error = $this->db->lasterror();
4560 $this->errors[] = $this->error;
4561 }
4562 }
4563
4564 if (empty($error)) {
4565 $this->no_email = $no_email;
4566 $this->db->commit();
4567 return 1;
4568 } else {
4569 $this->db->rollback();
4570 return $error * -1;
4571 }
4572 }
4573
4574 return 0;
4575 }
4576
4583 public function getNoEmail()
4584 {
4585 if ($this->email) {
4586 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4587 $resql = $this->db->query($sql);
4588 if ($resql) {
4589 $obj = $this->db->fetch_object($resql);
4590 $this->no_email = $obj->nb;
4591 return 1;
4592 } else {
4593 $this->error = $this->db->lasterror();
4594 $this->errors[] = $this->error;
4595 return -1;
4596 }
4597 }
4598 return 0;
4599 }
4600
4601 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4611 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4612 {
4613 // phpcs:enable
4614 global $user, $langs;
4615
4616 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4617 $fullname = $member->getFullName($langs);
4618
4619 if ($member->morphy == 'mor') {
4620 if (empty($socname)) {
4621 $socname = $member->company ? $member->company : $member->societe;
4622 }
4623 if (!empty($fullname) && empty($socalias)) {
4624 $socalias = $fullname;
4625 }
4626 } elseif (empty($socname) && $member->morphy == 'phy') {
4627 if (empty($socname)) {
4628 $socname = $fullname;
4629 }
4630 if (!empty($member->company) && empty($socalias)) {
4631 $socalias = $member->company;
4632 }
4633 }
4634
4635 $name = $socname;
4636 $alias = $socalias ? $socalias : '';
4637
4638 // Positionne parameters
4639 $this->nom = $name; // TODO deprecated
4640 $this->name = $name;
4641 $this->name_alias = $alias;
4642 $this->address = $member->address;
4643 $this->zip = $member->zip;
4644 $this->town = $member->town;
4645 $this->country_code = $member->country_code;
4646 $this->country_id = $member->country_id;
4647 $this->phone = $member->phone; // Prof phone
4648 $this->email = $member->email;
4649 $this->socialnetworks = $member->socialnetworks;
4650 $this->entity = $member->entity;
4651
4652 $this->client = 1; // A member is a customer by default
4653 if (getDolGlobalString('THIRDPARTY_CUSTOMERCODE_EQUALS_MEMBERREF')) {
4654 $this->code_client = $member->ref; // set Customer Code equal to existing Member Reference
4655 } else {
4656 $this->code_client = ($customercode ? $customercode : -1); // set new auto-incremented Customer Code
4657 }
4658 $this->code_fournisseur = '-1';
4659 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4660 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4661
4662 $this->db->begin();
4663
4664 // Cree et positionne $this->id
4665 $result = $this->create($user);
4666
4667 if ($result >= 0) {
4668 // Auto-create contact on thirdparty creation
4669 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4670 // Fill fields needed by contact
4671 $this->name_bis = $member->lastname;
4672 $this->firstname = $member->firstname;
4673 $this->civility_id = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4674 $this->civility_code = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4675
4676 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4677 $result = $this->create_individual($user);
4678
4679 if ($result < 0) {
4680 setEventMessages($this->error, $this->errors, 'errors');
4681 $this->db->rollback();
4682 return -1;
4683 }
4684 }
4685
4686 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4687 $sql .= " SET fk_soc = ".((int) $this->id);
4688 $sql .= " WHERE rowid = ".((int) $member->id);
4689
4690 $resql = $this->db->query($sql);
4691 if ($resql) {
4692 $this->db->commit();
4693 return $this->id;
4694 } else {
4695 $this->error = $this->db->error();
4696
4697 $this->db->rollback();
4698 return -1;
4699 }
4700 } else {
4701 // $this->error deja positionne
4702 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4703
4704 $this->db->rollback();
4705 return $result;
4706 }
4707 }
4708
4715 public function setMysoc(Conf $conf)
4716 {
4717 global $langs;
4718
4719 $this->id = 0;
4720 $this->entity = $conf->entity;
4721 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4722 $this->nom = $this->name; // deprecated
4723 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4724 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4725 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4726 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4727
4728 $this->currency_code = getDolGlobalString('MAIN_MONNAIE');
4729
4730 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4731
4732 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4733
4734 // We define country_id, country_code and country
4735 $country_id = 0;
4736 $country_code = $country_label = '';
4737 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4738 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4739 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4740 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4741 $country_code = $tmp[1];
4742 $country_label = $tmp[2];
4743 } else {
4744 // For backward compatibility
4745 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4746 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4747 $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
4748 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4749 }
4750 }
4751 $this->country_id = $country_id;
4752 $this->country_code = $country_code;
4753 $this->country = $country_label;
4754 if (is_object($langs)) {
4755 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4756 }
4757
4758 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4759 // We define state_id, state_code and state
4760 $state_id = 0;
4761 $state_code = '';
4762 $state_label = '';
4763 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4764 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4765 $state_id = (int) $tmp[0];
4766 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4767 $state_code = $tmp[1];
4768 $state_label = $tmp[2];
4769 } else { // For backward compatibility
4770 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);
4771 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4772 $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
4773 $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
4774 }
4775 }
4776 $this->state_id = $state_id;
4777 $this->state_code = $state_code;
4778 $this->state = $state_label;
4779 if (is_object($langs)) {
4780 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4781 }
4782
4783 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4784 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4785 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4786 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4787
4788 // Social networks
4789 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4790 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4791 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4792 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4793 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4794 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4795 $this->socialnetworks = array();
4796 if (!empty($facebook_url)) {
4797 $this->socialnetworks['facebook'] = $facebook_url;
4798 }
4799 if (!empty($twitter_url)) {
4800 $this->socialnetworks['twitter'] = $twitter_url;
4801 }
4802 if (!empty($linkedin_url)) {
4803 $this->socialnetworks['linkedin'] = $linkedin_url;
4804 }
4805 if (!empty($instagram_url)) {
4806 $this->socialnetworks['instagram'] = $instagram_url;
4807 }
4808 if (!empty($youtube_url)) {
4809 $this->socialnetworks['youtube'] = $youtube_url;
4810 }
4811 if (!empty($github_url)) {
4812 $this->socialnetworks['github'] = $github_url;
4813 }
4814
4815 // Id prof generiques
4816 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4817 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4818 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4819 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4820 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4821 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4822 $this->idprof7 = getDolGlobalString('MAIN_INFO_PROFID7');
4823 $this->idprof8 = getDolGlobalString('MAIN_INFO_PROFID8');
4824 $this->idprof9 = getDolGlobalString('MAIN_INFO_PROFID9');
4825 $this->idprof10 = getDolGlobalString('MAIN_INFO_PROFID10');
4826 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4827 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4828 $this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;
4829 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4830 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4831 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4832 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4833 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4834 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4835 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4836 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4837 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4838
4839 // Define if company use vat or not
4840 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4841
4842 // Define if company use local taxes
4843 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4844 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4845
4846 $this->termsofsale = getDolGlobalString('MAIN_INFO_SOCIETE_TERMSOFSALE');
4847 }
4848
4856 public function initAsSpecimen()
4857 {
4858 $now = dol_now();
4859
4860 // Initialize parameters
4861 $this->id = 0;
4862 $this->entity = 1;
4863 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4864 $this->ref_ext = 'Ref ext';
4865 $this->specimen = 1;
4866 $this->address = '21 jump street';
4867 $this->zip = '99999';
4868 $this->town = 'MyTown';
4869 $this->state_id = 1;
4870 $this->state_code = 'AA';
4871 $this->state = 'MyState';
4872 $this->country_id = 1;
4873 $this->country_code = 'FR';
4874 $this->email = 'specimen@specimen.com';
4875 $this->socialnetworks = array(
4876 'skype' => 'skypepseudo',
4877 'twitter' => 'twitterpseudo',
4878 'facebook' => 'facebookpseudo',
4879 'linkedin' => 'linkedinpseudo',
4880 );
4881 $this->url = 'http://www.specimen.com';
4882
4883 $this->phone = '0909090901';
4884 $this->phone_mobile = '0909090901';
4885 $this->fax = '0909090909';
4886
4887 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4888 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4889 $this->typent_code = 'TE_OTHER';
4890 $this->capital = 10000;
4891 $this->client = 1;
4892 $this->prospect = 1;
4893 $this->fournisseur = 1;
4894 $this->tva_assuj = 1;
4895 $this->tva_intra = 'EU1234567';
4896 $this->note_public = 'This is a comment (public)';
4897 $this->note_private = 'This is a comment (private)';
4898
4899 $this->idprof1 = 'idprof1';
4900 $this->idprof2 = 'idprof2';
4901 $this->idprof3 = 'idprof3';
4902 $this->idprof4 = 'idprof4';
4903 $this->idprof5 = 'idprof5';
4904 $this->idprof6 = 'idprof6';
4905
4906 return 1;
4907 }
4908
4915 public function useLocalTax($localTaxNum = 0)
4916 {
4917 $sql = "SELECT t.localtax1, t.localtax2";
4918 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4919 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4920 $sql .= " AND t.active = 1";
4921 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4922 if (empty($localTaxNum)) {
4923 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4924 } elseif ($localTaxNum == 1) {
4925 $sql .= " AND t.localtax1_type <> '0'";
4926 } elseif ($localTaxNum == 2) {
4927 $sql .= " AND t.localtax2_type <> '0'";
4928 }
4929
4930 $resql = $this->db->query($sql);
4931 if ($resql) {
4932 return ($this->db->num_rows($resql) > 0);
4933 } else {
4934 return false;
4935 }
4936 }
4937
4943 public function useNPR()
4944 {
4945 $sql = "SELECT t.rowid";
4946 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4947 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4948 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4949 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4950
4951 dol_syslog("useNPR", LOG_DEBUG);
4952 $resql = $this->db->query($sql);
4953 if ($resql) {
4954 return ($this->db->num_rows($resql) > 0);
4955 } else {
4956 return false;
4957 }
4958 }
4959
4966 public function useRevenueStamp()
4967 {
4968 $sql = "SELECT COUNT(*) as nb";
4969 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4970 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4971 $sql .= " AND r.active = 1";
4972
4973 dol_syslog("useRevenueStamp", LOG_DEBUG);
4974 $resql = $this->db->query($sql);
4975 if ($resql) {
4976 $obj = $this->db->fetch_object($resql);
4977 return ($obj->nb > 0);
4978 } else {
4979 $this->error = $this->db->lasterror();
4980 return false;
4981 }
4982 }
4983
4989 public function getLibProspLevel()
4990 {
4991 return $this->LibProspLevel($this->fk_prospectlevel);
4992 }
4993
4994 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5001 public function LibProspLevel($fk_prospectlevel)
5002 {
5003 // phpcs:enable
5004 global $langs;
5005
5006 $label = '';
5007 if ($fk_prospectlevel != '') {
5008 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
5009 // If label is not found in language file, we get label from cache/database
5010 if ($label == "ProspectLevel".$fk_prospectlevel) {
5011 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
5012 }
5013 }
5014
5015 return $label;
5016 }
5017
5025 public function getLibProspCommStatut($mode = 0, $label = '')
5026 {
5027 return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
5028 }
5029
5030 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5044 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
5045 {
5046 // phpcs:enable
5047 global $langs;
5048
5049 $langs->load('customers');
5050
5051 if ($mode == 2) {
5052 if ($status == '-1' || $status == 'ST_NO') {
5053 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5054 } elseif ($status == '0' || $status == 'ST_NEVER') {
5055 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5056 } elseif ($status == '1' || $status == 'ST_TODO') {
5057 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5058 } elseif ($status == '2' || $status == 'ST_PEND') {
5059 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5060 } elseif ($status == '3' || $status == 'ST_DONE') {
5061 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5062 } else {
5063 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);
5064 }
5065 } elseif ($mode == 3) {
5066 if ($status == '-1' || $status == 'ST_NO') {
5067 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
5068 } elseif ($status == '0' || $status == 'ST_NEVER') {
5069 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
5070 } elseif ($status == '1' || $status == 'ST_TODO') {
5071 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
5072 } elseif ($status == '2' || $status == 'ST_PEND') {
5073 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
5074 } elseif ($status == '3' || $status == 'ST_DONE') {
5075 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
5076 } else {
5077 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
5078 }
5079 } elseif ($mode == 4) {
5080 if ($status == '-1' || $status == 'ST_NO') {
5081 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5082 } elseif ($status == '0' || $status == 'ST_NEVER') {
5083 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5084 } elseif ($status == '1' || $status == 'ST_TODO') {
5085 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5086 } elseif ($status == '2' || $status == 'ST_PEND') {
5087 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5088 } elseif ($status == '3' || $status == 'ST_DONE') {
5089 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5090 } else {
5091 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);
5092 }
5093 }
5094
5095 return "Error, mode/status not found";
5096 }
5097
5104 public function getOutstandingProposals($mode = 'customer')
5105 {
5106 $table = 'propal';
5107 if ($mode == 'supplier') {
5108 $table = 'supplier_proposal';
5109 }
5110
5111 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5112 $sql .= " WHERE fk_soc = ".((int) $this->id);
5113 if ($mode == 'supplier') {
5114 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
5115 } else {
5116 $sql .= " AND entity IN (".getEntity('propal').")";
5117 }
5118
5119 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
5120
5121 $resql = $this->db->query($sql);
5122 if ($resql) {
5123 $outstandingOpened = 0;
5124 $outstandingTotal = 0;
5125 $outstandingTotalIncTax = 0;
5126 $arrayofref = array();
5127 while ($obj = $this->db->fetch_object($resql)) {
5128 $arrayofref[$obj->rowid] = $obj->ref;
5129 $outstandingTotal += $obj->total_ht;
5130 $outstandingTotalIncTax += $obj->total_ttc;
5131 if ($obj->status != 0) {
5132 // Not a draft
5133 $outstandingOpened += $obj->total_ttc;
5134 }
5135 }
5136 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5137 } else {
5138 return array();
5139 }
5140 }
5141
5148 public function getOutstandingOrders($mode = 'customer')
5149 {
5150 $table = 'commande';
5151 if ($mode == 'supplier') {
5152 $table = 'commande_fournisseur';
5153 }
5154
5155 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5156 $sql .= " WHERE fk_soc = ".((int) $this->id);
5157 if ($mode == 'supplier') {
5158 $sql .= " AND entity IN (".getEntity('supplier_order').")";
5159 } else {
5160 $sql .= " AND entity IN (".getEntity('commande').")";
5161 }
5162
5163 dol_syslog("getOutstandingOrders", LOG_DEBUG);
5164 $resql = $this->db->query($sql);
5165 if ($resql) {
5166 $outstandingOpened = 0;
5167 $outstandingTotal = 0;
5168 $outstandingTotalIncTax = 0;
5169 $arrayofref = array();
5170 while ($obj = $this->db->fetch_object($resql)) {
5171 $arrayofref[$obj->rowid] = $obj->ref;
5172 $outstandingTotal += $obj->total_ht;
5173 $outstandingTotalIncTax += $obj->total_ttc;
5174 if ($obj->status != 0) {
5175 // Not a draft
5176 $outstandingOpened += $obj->total_ttc;
5177 }
5178 }
5179 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5180 } else {
5181 return array();
5182 }
5183 }
5184
5192 public function getOutstandingBills($mode = 'customer', $late = 0)
5193 {
5194 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5195
5196 $table = 'facture';
5197 if ($mode == 'supplier') {
5198 $table = 'facture_fourn';
5199 }
5200
5201 /* Accurate value of remain to pay is to sum remaintopay for each invoice
5202 $paiement = $invoice->getSommePaiement();
5203 $creditnotes=$invoice->getSumCreditNotesUsed();
5204 $deposits=$invoice->getSumDepositsUsed();
5205 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
5206 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
5207 */
5208 $today = dol_get_first_hour(dol_now('tzuser')); // Returns today at 00:00 in the user's time zone
5209
5210 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
5211 $sql .= " WHERE fk_soc = ".((int) $this->id);
5212 if (!empty($late)) {
5213 $sql .= " AND date_lim_reglement < '".$this->db->idate($today)."'";
5214 }
5215 if ($mode == 'supplier') {
5216 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
5217 } else {
5218 $sql .= " AND entity IN (".getEntity('invoice').")";
5219 }
5220
5221 dol_syslog("getOutstandingBills", LOG_DEBUG);
5222 $resql = $this->db->query($sql);
5223 if ($resql) {
5224 $outstandingOpened = 0;
5225 $outstandingTotal = 0;
5226 $outstandingTotalIncTax = 0;
5227 $arrayofref = array();
5228 $arrayofrefopened = array();
5229 if ($mode == 'supplier') {
5230 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5231 $tmpobject = new FactureFournisseur($this->db);
5232 } else {
5233 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
5234 $tmpobject = new Facture($this->db);
5235 }
5236 while ($obj = $this->db->fetch_object($resql)) {
5237 $arrayofref[$obj->rowid] = $obj->ref;
5238 $tmpobject->id = $obj->rowid;
5239
5240 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5241 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5242 ) {
5243 $outstandingTotal += $obj->total_ht;
5244 $outstandingTotalIncTax += $obj->total_ttc;
5245 }
5246
5247 $remaintopay = 0;
5248
5249 if ($obj->paye == 0
5250 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5251 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5252 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5253 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5254 $paiement = $tmpobject->getSommePaiement();
5255 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5256 $deposits = $tmpobject->getSumDepositsUsed();
5257
5258 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5259 $outstandingOpened += $remaintopay;
5260 }
5261
5262 //if credit note is converted but not used
5263 // TODO Do this also for customer ?
5264 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5265 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5266 $remaintopay -= $remainingcreditnote;
5267 $outstandingOpened -= $remainingcreditnote;
5268 }
5269
5270 if ($remaintopay) {
5271 $arrayofrefopened[$obj->rowid] = $obj->ref;
5272 }
5273 }
5274 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'incl taxes'
5275 } else {
5276 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5277 return array();
5278 }
5279 }
5280
5287 public function getLibCustProspStatut()
5288 {
5289 return $this->LibCustProspStatut($this->client);
5290 }
5291
5292 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5299 public function LibCustProspStatut($status)
5300 {
5301 // phpcs:enable
5302 global $langs;
5303 $langs->load('companies');
5304
5305 if ($status == 0) {
5306 return $langs->trans("NorProspectNorCustomer");
5307 } elseif ($status == 1) {
5308 return $langs->trans("Customer");
5309 } elseif ($status == 2) {
5310 return $langs->trans("Prospect");
5311 } elseif ($status == 3) {
5312 return $langs->trans("ProspectCustomer");
5313 }
5314
5315 return '';
5316 }
5317
5318
5330 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5331 {
5332 global $langs;
5333
5334 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5335 $modelpath = "core/modules/bank/doc/";
5336
5337 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5338 $companybankaccount = new CompanyBankAccount($this->db);
5339 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5340 if (!$result) {
5341 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5342 }
5343 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5344 $this->last_main_doc = $companybankaccount->last_main_doc;
5345 } else {
5346 // Positionne le modele sur le nom du modele a utiliser
5347 if (!dol_strlen($modele)) {
5348 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5349 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5350 } else {
5351 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5352 return 0;
5353 }
5354 }
5355
5356 if (!isset($this->bank_account)) {
5357 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5358 $bac = new CompanyBankAccount($this->db);
5359 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5360 $result = $bac->fetch(0, '', $this->id);
5361 if ($result > 0) {
5362 $this->bank_account = $bac;
5363 } else {
5364 $this->bank_account = '';
5365 }
5366 }
5367
5368 $modelpath = "core/modules/societe/doc/";
5369
5370 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5371 }
5372
5373 return $result;
5374 }
5375
5376
5388 public function setCategories($categories, $type_categ)
5389 {
5390 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5391
5392 // Decode type
5393 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5394 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5395 return -1;
5396 }
5397
5398 return parent::setCategoriesCommon($categories, $type_categ);
5399 }
5400
5408 public function setSalesRep($salesrep, $onlyAdd = false)
5409 {
5410 global $user;
5411
5412 // Handle single user
5413 if (!is_array($salesrep)) {
5414 $salesrep = array($salesrep);
5415 }
5416
5417 $to_del = array(); // Nothing to delete
5418 $to_add = $salesrep;
5419 if ($onlyAdd === false) {
5420 // Get current users
5421 $existing = $this->getSalesRepresentatives($user, 1);
5422
5423 // Diff
5424 if (is_array($existing)) {
5425 $to_del = array_diff($existing, $salesrep);
5426 $to_add = array_diff($salesrep, $existing);
5427 }
5428 }
5429
5430 $error = 0;
5431
5432 // Process
5433 foreach ($to_del as $del) {
5434 $this->del_commercial($user, $del);
5435 }
5436 foreach ($to_add as $add) {
5437 $result = $this->add_commercial($user, $add);
5438 if ($result < 0) {
5439 $error++;
5440 break;
5441 }
5442 }
5443
5444 return $error ? -1 : 1;
5445 }
5446
5453 public function setThirdpartyType($typent_id)
5454 {
5455 global $user;
5456
5457 dol_syslog(__METHOD__, LOG_DEBUG);
5458
5459 if ($this->id) {
5460 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5461
5462 if ($result > 0) {
5463 $this->typent_id = $typent_id;
5464 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5465 return 1;
5466 } else {
5467 return -1;
5468 }
5469 } else {
5470 return -1;
5471 }
5472 }
5473
5483 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5484 {
5485 if ($origin_id == $dest_id) {
5486 dol_syslog('Error: Try to merge a thirdparty into itself');
5487 return false;
5488 }
5489
5490 // 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.
5491 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5492 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5493 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5494 $sql .= ' SELECT fk_user ';
5495 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5496 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5497
5498 $resql = $dbs->query($sql);
5499 while ($obj = $dbs->fetch_object($resql)) {
5500 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5501 }
5502
5503 // 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.
5504 // Do not include llx_societe because it will be replaced later.
5505 $tables = array(
5506 'societe_account',
5507 'societe_commerciaux',
5508 'societe_prices',
5509 'societe_remise',
5510 'societe_remise_except',
5511 'societe_rib'
5512 );
5513
5514 // TODO When we merge societe_account, we may get 2 lines for the stripe account. Must fix this.
5515
5516 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5517 }
5518
5527 public function setAccountancyCode($type, $value)
5528 {
5529 global $user, $langs, $conf;
5530
5531 $this->db->begin();
5532
5533 if ($type == 'buy') {
5534 $field = 'accountancy_code_buy';
5535 } elseif ($type == 'sell') {
5536 $field = 'accountancy_code_sell';
5537 } else {
5538 return -1;
5539 }
5540
5541 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5542 $sql .= $field." = '".$this->db->escape($value)."'";
5543 $sql .= " WHERE rowid = ".((int) $this->id);
5544
5545 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5546 $resql = $this->db->query($sql);
5547
5548 if ($resql) {
5549 // Call triggers
5550 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5551 $interface = new Interfaces($this->db);
5552 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5553 if ($result < 0) {
5554 $this->errors = $interface->errors;
5555 $this->db->rollback();
5556 return -1;
5557 }
5558 // End call triggers
5559
5560 $this->$field = $value;
5561
5562 $this->db->commit();
5563 return 1;
5564 } else {
5565 $this->error = $this->db->lasterror();
5566 $this->db->rollback();
5567 return -1;
5568 }
5569 }
5570
5577 public function fetchPartnerships($mode)
5578 {
5579 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5580
5581 $this->partnerships[] = array();
5582
5583 return 1;
5584 }
5585
5593 public function getKanbanView($option = '', $arraydata = array())
5594 {
5595 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5596
5597 $return = '<div class="box-flex-item box-flex-grow-zero">';
5598 $return .= '<div class="info-box info-box-sm">';
5599 $return .= '<span class="info-box-icon bg-infobox-action">';
5600 $return .= img_picto('', $this->picto);
5601 $return .= '</span>';
5602 $return .= '<div class="info-box-content">';
5603 $return .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref);
5604 $return .= '</div>';
5605 if (!empty($this->phone)) {
5606 $return .= '<div class="inline-block valignmiddle">';
5607 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5608 $return .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
5609 $return .= '</div>';
5610 }
5611 if (!empty($this->email)) {
5612 $return .= '<div class="inline-block valignmiddle">';
5613 $return .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
5614 $return .= '</div>';
5615 }
5616 if ($selected >= 0) {
5617 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5618 }
5619 if (property_exists($this, 'code_client')) {
5620 $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5621 }
5622 if (method_exists($this, 'getLibStatut')) {
5623 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5624 }
5625 $return .= '</div>'; // end info-box-content
5626 $return .= '</div>';
5627 $return .= '</div>';
5628
5629 return $return;
5630 }
5631
5640 public function getContacts($list = 0, $code = '', $element = '')
5641 {
5642 // phpcs:enable
5643 global $langs;
5644
5645 $tab = array();
5646
5647 $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
5648 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5649 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5650 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5651 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5652 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5653 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5654 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5655 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5656 if (!empty($element)) {
5657 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5658 }
5659 if ($code) {
5660 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5661 }
5662 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5663 $sql .= " AND tc.source = 'external'";
5664 $sql .= " AND tc.active = 1";
5665
5666 $sql .= " ORDER BY t.lastname ASC";
5667
5668 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5669 $resql = $this->db->query($sql);
5670 if ($resql) {
5671 $num = $this->db->num_rows($resql);
5672 $i = 0;
5673 while ($i < $num) {
5674 $obj = $this->db->fetch_object($resql);
5675
5676 if (!$list) {
5677 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5678 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5679 $tab[$i] = array(
5680 'source' => $obj->source,
5681 'socid' => $obj->socid,
5682 'id' => $obj->id,
5683 'nom' => $obj->lastname, // For backward compatibility
5684 'civility' => $obj->civility,
5685 'lastname' => $obj->lastname,
5686 'firstname' => $obj->firstname,
5687 'email' => $obj->email,
5688 'login' => (empty($obj->login) ? '' : $obj->login),
5689 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5690 'statuscontact' => $obj->statuscontact,
5691 'rowid' => $obj->rowid,
5692 'code' => $obj->code,
5693 'element' => $obj->element,
5694 'libelle' => $libelle_type,
5695 'status' => $obj->statuslink,
5696 'fk_c_type_contact' => $obj->fk_c_type_contact
5697 );
5698 } else {
5699 $tab[$i] = $obj->id;
5700 }
5701
5702 $i++;
5703 }
5704
5705 return $tab;
5706 } else {
5707 $this->error = $this->db->lasterror();
5708 dol_print_error($this->db);
5709 return -1;
5710 }
5711 }
5712
5723 public function mergeCompany($soc_origin_id)
5724 {
5725 global $conf, $langs, $hookmanager, $user, $action;
5726
5727 $error = 0;
5728 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5729
5730 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5731
5732 if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5733 $this->error = $langs->trans('ErrorRecordNotFound');
5734 $error++;
5735 }
5736
5737 if (!$error) {
5738 $this->db->begin();
5739
5740 // Recopy some data
5741 $this->client |= $soc_origin->client;
5742 $this->fournisseur |= $soc_origin->fournisseur;
5743 $listofproperties = array(
5744 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5745 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5746 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5747 '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',
5748 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5749 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5750 );
5751 foreach ($listofproperties as $property) {
5752 if (empty($this->$property)) {
5753 $this->$property = $soc_origin->$property;
5754 }
5755 }
5756
5757 if ($this->typent_id == -1) {
5758 $this->typent_id = $soc_origin->typent_id;
5759 }
5760
5761 // Concat some data
5762 $listofproperties = array(
5763 'note_public', 'note_private'
5764 );
5765 foreach ($listofproperties as $property) {
5766 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5767 }
5768
5769 // Merge extrafields
5770 if (is_array($soc_origin->array_options)) {
5771 foreach ($soc_origin->array_options as $key => $val) {
5772 if (empty($this->array_options[$key])) {
5773 $this->array_options[$key] = $val;
5774 }
5775 }
5776 }
5777
5778 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5779 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5780 $this->name_bis = $this->name;
5781 }
5782
5783 // Merge categories
5784 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5785 $static_cat = new Categorie($this->db);
5786
5787 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5788 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5789 $custcats = array_merge($custcats, $custcats_ori);
5790 $this->setCategories($custcats, 'customer');
5791
5792 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5793 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5794 $suppcats = array_merge($suppcats, $suppcats_ori);
5795 $this->setCategories($suppcats, 'supplier');
5796
5797 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5798 if ($soc_origin->code_client == $this->code_client
5799 || $soc_origin->code_fournisseur == $this->code_fournisseur
5800 || $soc_origin->barcode == $this->barcode) {
5801 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5802 $soc_origin->code_client = '';
5803 $soc_origin->code_fournisseur = '';
5804 $soc_origin->barcode = '';
5805 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5806 }
5807
5808 // Update
5809 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5810
5811 if ($result < 0) {
5812 $error++;
5813 }
5814
5815 // Move links
5816 if (!$error) {
5817 $objects = array(
5818 'Adherent' => '/adherents/class/adherent.class.php',
5819 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5820 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5821 'Propal' => '/comm/propal/class/propal.class.php',
5822 'Commande' => '/commande/class/commande.class.php',
5823 'Facture' => '/compta/facture/class/facture.class.php',
5824 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5825 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5826 'Contact' => '/contact/class/contact.class.php',
5827 'Contrat' => '/contrat/class/contrat.class.php',
5828 'Expedition' => '/expedition/class/expedition.class.php',
5829 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5830 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5831 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5832 'Reception' => '/reception/class/reception.class.php',
5833 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5834 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5835 'Product' => '/product/class/product.class.php',
5836 //'ProductThirparty' => '...', // for llx_product_thirdparty
5837 'Project' => '/projet/class/project.class.php',
5838 'User' => '/user/class/user.class.php',
5839 'Account' => '/compta/bank/class/account.class.php',
5840 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5841 'Societe' => '/societe/class/societe.class.php',
5842 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
5843 );
5844 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5845 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5846 }
5847 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5848 $objects['Mo'] = '/mrp/class/mo.class.php';
5849 }
5850 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5851 $objects['Don'] = '/don/class/don.class.php';
5852 }
5853 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5854 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5855 }
5856 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5857 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5858 }
5859 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5860 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5861 }
5862
5863 //First, all core objects must update their tables
5864 foreach ($objects as $object_name => $object_file) {
5865 /* $object_file is never an array -> code commented
5866 if (is_array($object_file)) {
5867 if (empty($object_file['enabled'])) {
5868 continue;
5869 }
5870 $object_file = $object_file['file'];
5871 }
5872 */
5873
5874 require_once DOL_DOCUMENT_ROOT.$object_file;
5875
5876 if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5877 $error++;
5878 $this->error = $this->db->lasterror();
5879 break;
5880 }
5881 }
5882 }
5883
5884 // External modules should update their ones too
5885 if (!$error) {
5886 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5887 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5888
5889 if ($reshook < 0) {
5890 $this->error = $hookmanager->error;
5891 $this->errors = $hookmanager->errors;
5892 $error++;
5893 }
5894 }
5895
5896
5897 if (!$error) {
5898 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5899
5900 // Call trigger
5901 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5902 if ($result < 0) {
5903 $error++;
5904 }
5905 // End call triggers
5906 }
5907
5908 if (!$error) {
5909 // We finally remove the old thirdparty
5910 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5911 $this->error = $soc_origin->error;
5912 $this->errors = $soc_origin->errors;
5913 $error++;
5914 }
5915 }
5916
5917
5918 if (!$error) {
5919 // Move files from the dir of the third party to delete into the dir of the third party to keep
5920 if (!empty($conf->societe->multidir_output[$this->entity])) {
5921 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5922 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5923
5924 if (dol_is_dir($srcdir)) {
5925 $dirlist = dol_dir_list($srcdir, 'files', 1);
5926 foreach ($dirlist as $filetomove) {
5927 $destfile = $destdir.'/'.$filetomove['relativename'];
5928 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5929 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5930 }
5931 //exit;
5932 }
5933 }
5934 }
5935
5936 if (!$error) {
5937 $this->db->commit();
5938 return 0;
5939 } else {
5940 $langs->load("errors");
5941 $this->error = $langs->trans('ErrorsThirdpartyMerge');
5942 $this->db->rollback();
5943 return -1;
5944 }
5945 }
5946
5947 return -1;
5948 }
5949}
$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