dolibarr 25.0.0-alpha
societe.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5 * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2013-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
12 * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16 * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17 * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18 * Copyright (C) 2019-2026 Frédéric France <frederic.france@free.fr>
19 * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20 * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
21 * Copyright (C) 2023-2024 Alexandre Janniaux <alexandre.janniaux@gmail.com>
22 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
23 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
24 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
25 * Copyright (C) 2026 Nick Fragoulis
26 *
27 * This program is free software; you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation; either version 3 of the License, or
30 * (at your option) any later version.
31 *
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
36 *
37 * You should have received a copy of the GNU General Public License
38 * along with this program. If not, see <https://www.gnu.org/licenses/>.
39 */
40
46require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
48require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
49require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
50require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
51require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
52
53
57class Societe extends CommonObject
58{
59 use CommonIncoterm;
61 use CommonPeople;
62
67 public $TRIGGER_PREFIX = 'COMPANY'; // to be overridden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
68
72 public $module = 'societe';
73
77 public $element = 'societe';
78
82 public $table_element = 'societe';
83
87 public $fk_element = 'fk_soc';
88
92 public $fieldsforcombobox = 'nom,name_alias';
93
97 protected $childtables = array(
98 'supplier_proposal' => array('name' => 'SupplierProposal'),
99 'propal' => array('name' => 'Proposal'),
100 'commande' => array('name' => 'Order'),
101 'facture' => array('name' => 'Invoice'),
102 'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
103 'contrat' => array('name' => 'Contract'),
104 'fichinter' => array('name' => 'Fichinter'),
105 'facture_fourn' => array('name' => 'SupplierInvoice'),
106 'commande_fournisseur' => array('name' => 'SupplierOrder'),
107 'projet' => array('name' => 'Project'),
108 'expedition' => array('name' => 'Shipment'),
109 'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
110 'adherent' => array('name' => 'Member')
111 );
112
117 protected $childtablesoncascade = array(
118 'societe_prices',
119 'product_fournisseur_price',
120 'product_customer_price_log',
121 'product_customer_price',
122 '@Contact:/contact/class/contact.class.php:fk_soc',
123 'adherent',
124 'societe_account',
125 'societe_rib',
126 'societe_remise',
127 'societe_remise_except',
128 'societe_commerciaux',
129 'categorie',
130 'notify',
131 'notify_def',
132 'actioncomm',
133 );
134
138 public $picto = 'company';
139
144 public $restrictiononfksoc = 1;
145
150 public $supplierCategories = array();
151
156 public $prefixCustomerIsRequired;
157
187 public $fields = array(
188 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
189 'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
190 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
191 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
192 'nom' => array('type' => 'varchar(128)', 'length' => 128, 'label' => 'Nom', 'enabled' => 1, 'visible' => 1, 'position' => 35, 'showoncombobox' => 1, 'csslist' => 'tdoverflowmax150'),
193 'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
194 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
195 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
196 'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
197 'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
198 'tp_payment_reference' => array('type' => 'varchar(25)', 'label' => 'PaymentReference', 'enabled' => 1, 'visible' => -1, 'position' => 61),
199 'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
200 'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
201 'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
202 'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
203 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
204 'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
205 'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
206 'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
207 'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
208 'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
209 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
210 'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
211 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
212 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
213 'fk_typent' => array('type' => 'integer', 'label' => 'ThirdPartyType', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
214 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
215 'birth' => array('type' => 'date', 'label' => 'CompanyBirthDate', 'enabled' => 1, 'visible' => -1, 'position' => 182),
216 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
217 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
218 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
219 'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
220 'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
221 'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
222 'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
223 'tva_intra' => array('type' => 'varchar(20)', 'label' => 'VATIntra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
224 'euid' => array('type' => 'varchar(20)', 'label' => 'EUIDShort', 'enabled' => 1, 'visible' => -1, 'position' => 213),
225 'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
226 'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
227 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225, 'uieditable' => 1),
228 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230, 'uieditable' => 1),
229 'client' => array('type' => 'tinyint(4)', 'label' => 'Customer', 'enabled' => 1, 'visible' => -1, 'position' => 240),
230 'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Supplier', 'enabled' => 1, 'visible' => -1, 'position' => 245),
231 'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
232 'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
233 'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
234 'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
235 'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
236 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
237 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
238 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
239 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
240 'mode_reglement' => array('type' => 'smallint(6)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
241 'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
242 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
243 'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
244 'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
245 'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
246 'order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Order min amount', 'enabled' => 'isModEnabled("order") && getDolGlobalInt("ORDER_MANAGE_MIN_AMOUNT")', 'visible' => -1, 'position' => 315, 'isameasure' => 1),
247 'supplier_order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Supplier order min amount', 'enabled' => 'isModEnabled("order") && getDolGlobalInt("ORDER_MANAGE_MIN_AMOUNT")', 'visible' => -1, 'position' => 320, 'isameasure' => 1),
248 'fk_shipping_method' => array('type' => 'integer', 'label' => 'ShippingMode', 'enabled' => 1, 'visible' => -1, 'position' => 330),
249 'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'VATIsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 335),
250 'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'LocalTax1IsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 340),
251 'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'LocalTax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
252 'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'LocalTax2IsUsed', 'enabled' => 1, 'visible' => -1, 'position' => 350),
253 'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'LocalTax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
254 'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
255 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
256 'price_level' => array('type' => 'integer', 'label' => 'Price level', 'enabled' => 'getDolGlobalString("PRODUIT_MULTIPRICES") || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES") || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES")', 'visible' => -1, 'position' => 365),
257 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
258 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
259 'fk_barcode_type' => array('type' => 'integer', 'label' => 'BarcodeType', 'enabled' => 1, 'visible' => -1, 'position' => 405),
260 'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
261 'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
262 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 1, 'visible' => -1, 'position' => 425),
263 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
264 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
265 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
266 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
267 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
268 'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
269 'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
270 'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
271 'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
272 'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
273 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
274 );
275
282 public $nom;
283
287 public $name;
288
293 public $name_alias;
294
298 public $particulier;
299
304 public $status = 1;
305
309 public $region_code;
310
314 public $region;
315
319 public $country_id;
320
326 public $departement_code;
327
333 public $departement;
334
340 public $pays;
341
346 public $phone;
351 public $phone_mobile;
356 public $fax;
357
362 public $email;
363
368 public $no_email;
369
375 public $skype;
376
382 public $twitter;
383
389 public $facebook;
390
396 public $linkedin;
397
402 public $url;
403
408 public $barcode;
409
410 // 6 professional id (usage depends on country)
411
416 public $idprof1;
417
423 public $siren;
424
425
430 public $idprof2;
431
437 public $siret;
438
443 public $idprof3;
444
450 public $ape;
451
456 public $idprof4;
457
462 public $idprof5;
463
468 public $idprof6;
469
474 public $idprof7;
475
480 public $idprof8;
481
486 public $idprof9;
487
492 public $idprof10;
493
498 public $socialobject;
499
503 public $prefix_comm;
504
508 public $tva_assuj = 1;
509
513 public $tva_intra;
514
518 public $euid;
519
523 public $vat_reverse_charge = 0;
524
525 // Local taxes
529 public $localtax1_assuj;
533 public $localtax1_value;
537 public $localtax2_assuj;
541 public $localtax2_value;
542
546 public $managers;
547
551 public $capital;
552
556 public $typent_id = 0;
557
561 public $typent_code;
562
566 public $effectif;
567
571 public $effectif_id = 0;
575 public $forme_juridique_code = 0;
580 public $forme_juridique;
584 public $birth;
585
589 public $remise_percent;
593 public $remise_supplier_percent;
594
598 public $mode_reglement_id;
602 public $cond_reglement_id;
606 public $deposit_percent;
610 public $mode_reglement_supplier_id;
614 public $cond_reglement_supplier_id;
618 public $transport_mode_supplier_id;
619
623 public $fk_prospectlevel;
624
628 public $name_bis;
629
635 public $user_modification;
636
642 public $user_creation;
643
648 public $client = 0;
649
654 public $prospect = 0;
655
660 public $fournisseur;
661
666 public $code_client;
667
672 public $code_fournisseur;
673
679 public $tp_payment_reference;
680
685 public $code_compta_client;
686
691 public $accountancy_code_customer_general;
692
697 public $accountancy_code_customer;
698
703 public $code_compta_fournisseur;
704
709 public $accountancy_code_supplier_general;
710
715 public $accountancy_code_supplier;
716
721 public $code_compta_product;
722
728 public $note;
729
734 public $note_private;
735
740 public $note_public;
741
746 public $stcomm_id;
747
752 public $stcomm_picto;
753
758 public $status_prospect_label;
759
764 public $price_level;
765
769 public $outstanding_limit;
770
774 public $order_min_amount;
775
779 public $supplier_order_min_amount;
780
785 public $commercial_id;
786
791 public $parent;
792
797 public $default_lang;
798
802 public $ref;
803
809 public $ref_ext;
810
814 public $ip;
815
822 public $import_key;
823
828 public $webservices_url;
829
834 public $webservices_key;
835
839 public $logo;
840
844 public $logo_small;
845
849 public $logo_mini;
850
854 public $logo_squarred;
855
859 public $logo_squarred_small;
860
864 public $logo_squarred_mini;
865
869 public $accountancy_code_sell;
870
874 public $accountancy_code_buy;
875
879 public $currency_code;
880
881 // Multicurrency
885 public $fk_multicurrency;
886
890 public $multicurrency_code;
891
892 // Warehouse
896 public $fk_warehouse;
897
901 public $termsofsale;
902
903
904 // Fields loaded by fetchPartnerships()
905
909 public $partnerships = array();
910
911
915 public $bank_account;
916
922 public $code_compta;
923
924
925 const STATUS_CEASED = 0;
926 const STATUS_INACTIVITY = 1;
927
931 const NO_CUSTOMER = 0;
932
936 const CUSTOMER = 1;
937
941 const PROSPECT = 2;
942
947
951 const NO_SUPPLIER = 0;
952
956 const SUPPLIER = 1;
957
963 protected function deprecatedProperties()
964 {
965 return
966 array(
967 'code_compta' => 'code_compta_client',
968 )
969 + parent::deprecatedProperties();
970 }
971
972
973
979 public function __construct($db)
980 {
981 $this->db = $db;
982
983 $this->ismultientitymanaged = 1;
984 $this->isextrafieldmanaged = 1;
985 $this->client = 0;
986 $this->prospect = 0;
987 $this->fournisseur = 0;
988 $this->typent_id = 0;
989 $this->effectif_id = 0;
990 $this->forme_juridique_code = 0;
991 $this->tva_assuj = 1;
992 $this->vat_reverse_charge = 0;
993 $this->status = 1;
994
995 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
996 $this->fields['address']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
997 $this->fields['zip']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
998 $this->fields['town']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
999 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
1000 }
1001 }
1002
1011 public function create(User $user, $notrigger = 0)
1012 {
1013 global $langs, $conf;
1014
1015 $error = 0;
1016
1017 // Clean parameters
1018 if (empty($this->status)) {
1019 $this->status = 0;
1020 }
1021 $this->name = $this->name ? trim((string) $this->name) : trim((string) $this->nom);
1022 $this->setUpperOrLowerCase();
1023 $this->nom = $this->name; // For backward compatibility
1024
1025 if (empty($this->client)) {
1026 $this->client = 0;
1027 }
1028 if (empty($this->fournisseur)) {
1029 $this->fournisseur = 0;
1030 }
1031 $this->import_key = trim((string) $this->import_key);
1032
1033 $this->code_compta_client = trim($this->code_compta_client ?? '');
1034
1035 $this->accountancy_code_customer_general = trim($this->accountancy_code_customer_general ?? '');
1036 if ($this->accountancy_code_customer_general === '-1') {
1037 $this->accountancy_code_customer_general = '';
1038 }
1039 $this->accountancy_code_customer = trim((string) $this->code_compta_client);
1040 $this->accountancy_code_supplier_general = trim($this->accountancy_code_supplier_general ?? '');
1041 if ($this->accountancy_code_supplier_general === '-1') {
1042 $this->accountancy_code_supplier_general = '';
1043 }
1044 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
1045 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1046 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1047
1048 if (!empty($this->multicurrency_code)) {
1049 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1050 }
1051 if (empty($this->fk_multicurrency)) {
1052 $this->multicurrency_code = '';
1053 $this->fk_multicurrency = 0;
1054 }
1055
1056 dol_syslog(get_class($this)."::create ".$this->name);
1057
1058 $now = dol_now();
1059
1060 if (empty($this->date_creation)) {
1061 $this->date_creation = $now;
1062 }
1063
1064 $this->db->begin();
1065
1066 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1067 if ($this->code_client == -1 || $this->code_client === 'auto') {
1068 $this->get_codeclient($this, 0);
1069 }
1070 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1071 $this->get_codefournisseur($this, 1);
1072 }
1073
1074 // Check more parameters (including mandatory setup
1075 // If error, this->errors[] is filled
1076 $result = $this->verify();
1077
1078 if ($result >= 0) {
1079 $this->entity = setEntity($this);
1080
1081 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
1082 $sql .= "nom";
1083 $sql .= ", name_alias";
1084 $sql .= ", entity";
1085 $sql .= ", datec";
1086 $sql .= ", fk_user_creat";
1087 $sql .= ", fk_typent";
1088 $sql .= ", canvas";
1089 $sql .= ", status";
1090 $sql .= ", ref_ext";
1091 $sql .= ", fk_stcomm";
1092 $sql .= ", fk_incoterms";
1093 $sql .= ", location_incoterms";
1094 $sql .= ", import_key";
1095 $sql .= ", fk_multicurrency";
1096 $sql .= ", multicurrency_code";
1097 $sql .= ", ip";
1098 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1099 $sql .= ", vat_reverse_charge";
1100 $sql .= ", accountancy_code_buy";
1101 $sql .= ", accountancy_code_sell";
1102 }
1103 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
1104 $sql .= " '".$this->db->escape($this->name_alias)."',";
1105 $sql .= " ".((int) $this->entity).",";
1106 $sql .= " '".$this->db->idate($this->date_creation)."'";
1107 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
1108 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
1109 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
1110 $sql .= ", ".((int) $this->status);
1111 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1112 $sql .= ", 0";
1113 $sql .= ", ".(int) $this->fk_incoterms;
1114 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1115 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1116 $sql .= ", ".(int) $this->fk_multicurrency;
1117 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1118 $sql .= ", ".(empty($this->ip) ? "null" : "'".$this->db->escape($this->ip)."'");
1119 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1120 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1121 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1122 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1123 }
1124 $sql .= ")";
1125
1126 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1127
1128 $result = $this->db->query($sql);
1129 if ($result) {
1130 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1131
1132 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1133
1134 // Addition of the assigned sales representative
1135 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1136 $this->add_commercial($user, $this->commercial_id);
1137 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1138 // If a sales representative creates a customer, they are automatically assigned to them.
1139 $this->add_commercial($user, $user->id);
1140 }
1141
1142 if ($ret >= 0) {
1143 if (! $notrigger) {
1144 // Call trigger
1145 $result = $this->call_trigger('COMPANY_CREATE', $user);
1146 if ($result < 0) {
1147 $error++;
1148 }
1149 // End call triggers
1150 }
1151 } else {
1152 $error++;
1153 }
1154
1155 if (!$error) {
1156 dol_syslog(get_class($this)."::Create success id=".$this->id);
1157 $this->db->commit();
1158 return $this->id;
1159 } else {
1160 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1161 $this->db->rollback();
1162 return -4;
1163 }
1164 } else {
1165 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1166 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1167 $result = -1;
1168 } else {
1169 $this->error = $this->db->lasterror();
1170 $result = -2;
1171 }
1172 $this->db->rollback();
1173 return $result;
1174 }
1175 } else {
1176 $this->db->rollback();
1177 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1178 return -3;
1179 }
1180 }
1181
1182
1183 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1193 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1194 {
1195 $error = 0;
1196
1197 $this->db->begin();
1198
1199 // phpcs:enable
1200 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1201 $contact = new Contact($this->db);
1202
1203 $contact->name = $this->name_bis;
1204 $contact->firstname = $this->firstname;
1205 $contact->civility_id = $this->civility_id;
1206 $contact->socid = $this->id; // fk_soc
1207 $contact->statut = 1; // deprecated
1208 $contact->status = 1;
1209 $contact->priv = 0;
1210 $contact->country_id = $this->country_id;
1211 $contact->state_id = $this->state_id;
1212 $contact->address = $this->address;
1213 $contact->email = $this->email;
1214 $contact->zip = $this->zip;
1215 $contact->town = $this->town;
1216 $this->setUpperOrLowerCase();
1217 $contact->phone_pro = $this->phone;
1218 if (getDolGlobalString('CONTACTS_DEFAULT_ROLES')) {
1219 $contact->roles = explode(',', getDolGlobalString('CONTACTS_DEFAULT_ROLES'));
1220 }
1221
1222 $contactId = $contact->create($user, $notrigger);
1223 if ($contactId < 0) {
1224 $error++;
1225 $this->setErrorsFromObject($contact);
1226 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1227 }
1228
1229 if (empty($error) && is_array($tags) && !empty($tags)) {
1230 $result = $contact->setCategories($tags);
1231 if ($result < 0) {
1232 $error++;
1233 $this->setErrorsFromObject($contact);
1234 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1235 $contactId = $result;
1236 }
1237 }
1238
1239 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1240 $result = $contact->setNoEmail($no_email);
1241 if ($result < 0) {
1242 $this->setErrorsFromObject($contact);
1243 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1244 $contactId = $result;
1245 }
1246 }
1247
1248 if (empty($error)) {
1249 dol_syslog(get_class($this)."::create_individual success");
1250 $this->db->commit();
1251 } else {
1252 $this->db->rollback();
1253 }
1254
1255 return $contactId;
1256 }
1257
1264 public function verify()
1265 {
1266 global $langs, $mysoc;
1267
1268 $error = 0;
1269 $this->errors = array();
1270
1271 $result = 0;
1272 $this->name = trim((string) $this->name);
1273 $this->nom = $this->name; // For backward compatibility
1274
1275 if (!$this->name) {
1276 $this->errors[] = 'ErrorBadThirdPartyName';
1277 $result = -2;
1278 }
1279
1280 if ($this->client) {
1281 $rescode = $this->check_codeclient();
1282 if ($rescode != 0 && $rescode != -5) {
1283 if ($rescode == -1) {
1284 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1285 } elseif ($rescode == -2) {
1286 $this->errors[] = 'ErrorCustomerCodeRequired';
1287 } elseif ($rescode == -3) {
1288 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1289 } elseif ($rescode == -4) {
1290 $this->errors[] = 'ErrorPrefixRequired';
1291 } else {
1292 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1293 }
1294
1295 $result = -3;
1296 }
1297 }
1298
1299 if ($this->fournisseur) {
1300 $rescode = $this->check_codefournisseur();
1301 if ($rescode != 0 && $rescode != -5) {
1302 if ($rescode == -1) {
1303 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1304 } elseif ($rescode == -2) {
1305 $this->errors[] = 'ErrorSupplierCodeRequired';
1306 } elseif ($rescode == -3) {
1307 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1308 } elseif ($rescode == -4) {
1309 $this->errors[] = 'ErrorPrefixRequired';
1310 } else {
1311 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1312 }
1313 $result = -3;
1314 }
1315 }
1316
1317 // Check for duplicate or mandatory fields defined into setup
1318 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'EUID', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1319 foreach ($array_to_check as $key) {
1320 $keymin = strtolower($key);
1321 $keyfield_db = $keymin;
1322 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1323 $keymin = 'code_compta_client';
1324 $keyfield_db = 'code_compta';
1325 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1326 $keymin = 'code_compta_fournisseur';
1327 $keyfield_db = 'code_compta_fournisseur';
1328 }
1329 $i = (int) preg_replace('/[^0-9]/', '', $key);
1330 $vallabel = $this->$keymin;
1331
1332 if ($i > 0) {
1333 if ($mysoc != null && $this->isACompany()) {
1334 // Check for mandatory prof id (but only if country is same than ours)
1335 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1336 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1337 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1338 $langs->load("errors");
1339 $error++;
1340 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1341 }
1342 }
1343 }
1344
1345 // Check for unicity on profid
1346 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1347 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1348 $langs->load("errors");
1349 $error++;
1350 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1351 }
1352 }
1353 } else {
1354 if ($key == 'EMAIL') {
1355 // Check for mandatory
1356 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1357 $langs->load("errors");
1358 $error++;
1359 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1360 }
1361
1362 // Check for unicity
1363 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1364 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1365 $langs->load("errors");
1366 $error++;
1367 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1368 }
1369 }
1370 } elseif ($key == 'TVA_INTRA') {
1371 // Check for unicity
1372 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1373 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1374 $langs->load("errors");
1375 $error++;
1376 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1377 }
1378 }
1379 if ($this->tva_assuj && !$vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_MANDATORY')) {
1380 $langs->load("errors");
1381 $error++;
1382 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('VATIntra')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1383 }
1384 } elseif ($key == 'EUID') {
1385 // Check for unicity
1386 if ($vallabel && getDolGlobalString('SOCIETE_EUID_UNIQUE')) {
1387 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1388 $langs->load("errors");
1389 $error++;
1390 $this->errors[] = $langs->trans('EUIDShort')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1391 }
1392 }
1393
1394 // Check for mandatory
1395 if (getDolGlobalString('SOCIETE_EUID_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1396 $langs->load("errors");
1397 $error++;
1398 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('EUIDShort')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1399 }
1400 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1401 // Check for unicity
1402 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1403 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1404 $langs->loadLangs(array("errors", 'compta'));
1405 $error++;
1406 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1407 }
1408 }
1409
1410 // Check for mandatory
1411 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1412 $langs->loadLangs(array("errors", 'compta'));
1413 $error++;
1414 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1415 }
1416 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1417 // Check for unicity
1418 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1419 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1420 $langs->loadLangs(array("errors", 'compta'));
1421 $error++;
1422 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1423 }
1424 }
1425
1426 // Check for mandatory
1427 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1428 $langs->loadLangs(array("errors", 'compta'));
1429 $error++;
1430 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1431 }
1432 }
1433 }
1434 }
1435
1436 if ($error) {
1437 $result = -4;
1438 }
1439
1440 return $result;
1441 }
1442
1455 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1456 {
1457 global $langs, $conf, $hookmanager;
1458
1459 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1460
1461 if (empty($id)) {
1462 $id = $this->id;
1463 }
1464 if (empty($this->country_id) && !empty($this->country_code)) {
1465 $this->country_id = dol_getIdFromCode($this->db, $this->country_code, 'c_country', 'code', 'rowid');
1466 }
1467
1468 if (empty($this->country_id) && !empty($this->country_code)) {
1469 $country_id = getCountry($this->country_code, '3');
1470 $this->country_id = is_int($country_id) ? $country_id : 0;
1471 }
1472
1473 $error = 0;
1474
1475 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1476
1477 $now = dol_now();
1478
1479 // Clean parameters
1480 $this->id = $id;
1481 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1482 $this->name = $this->name ? trim((string) $this->name) : trim((string) $this->nom);
1483 $this->nom = $this->name; // For backward compatibility
1484 $this->name_alias = trim((string) $this->name_alias);
1485 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1486 $this->address = trim((string) $this->address);
1487 $this->zip = trim((string) $this->zip);
1488 $this->town = trim((string) $this->town);
1489 $this->state_id = (is_numeric($this->state_id)) ? (int) $this->state_id : 0;
1490 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1491 $this->phone = trim((string) $this->phone);
1492 $this->phone = preg_replace("/\s/", "", $this->phone);
1493 $this->phone = preg_replace("/\./", "", $this->phone);
1494 $this->phone_mobile = trim((string) $this->phone_mobile);
1495 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1496 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1497 $this->fax = trim((string) $this->fax);
1498 $this->fax = preg_replace("/\s/", "", $this->fax);
1499 $this->fax = preg_replace("/\./", "", $this->fax);
1500 $this->email = trim((string) $this->email);
1501 $this->url = $this->url ? clean_url($this->url, 0) : '';
1502 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1503 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1504 $this->idprof1 = trim((string) $this->idprof1);
1505 $this->idprof2 = trim((string) $this->idprof2);
1506 $this->idprof3 = trim((string) $this->idprof3);
1507 $this->idprof4 = trim((string) $this->idprof4);
1508 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1509 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1510 $this->prefix_comm = trim((string) $this->prefix_comm);
1511 $this->outstanding_limit = price2num($this->outstanding_limit);
1512 $this->order_min_amount = price2num($this->order_min_amount);
1513 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1514 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1515 $this->tva_intra = trim((string) $this->tva_intra);
1516 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1517 $this->euid = trim((string) $this->euid);
1518
1519 if (empty($this->status)) {
1520 $this->status = 0;
1521 }
1522
1523 if (!empty($this->multicurrency_code)) {
1524 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1525 }
1526 if (empty($this->fk_multicurrency)) {
1527 $this->multicurrency_code = '';
1528 $this->fk_multicurrency = 0;
1529 }
1530
1531 // Local taxes
1532 $this->localtax1_assuj = (int) trim((string) $this->localtax1_assuj);
1533 $this->localtax2_assuj = (int) trim((string) $this->localtax2_assuj);
1534
1535 $this->localtax1_value = trim((string) $this->localtax1_value);
1536 $this->localtax2_value = trim((string) $this->localtax2_value);
1537
1538 $this->capital = (!is_null($this->capital) && (string) $this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1539
1540 $this->effectif_id = (int) $this->effectif_id;
1541 $this->forme_juridique_code = (int) $this->forme_juridique_code;
1542
1543 //Gencod
1544 $this->barcode = trim((string) $this->barcode);
1545
1546 // For automatic creation
1547 if ($this->code_client == -1 || $this->code_client === 'auto') {
1548 $this->get_codeclient($this, 0);
1549 }
1550 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1551 $this->get_codefournisseur($this, 1);
1552 }
1553
1554 $this->accountancy_code_customer_general = trim((string) $this->accountancy_code_customer_general);
1555 if ($this->accountancy_code_customer_general === '-1') {
1556 $this->accountancy_code_customer_general = '';
1557 }
1558 $this->code_compta_client = trim((string) $this->code_compta_client);
1559 $this->accountancy_code_supplier_general = trim((string) $this->accountancy_code_supplier_general);
1560 if ($this->accountancy_code_supplier_general === '-1') {
1561 $this->accountancy_code_supplier_general = '';
1562 }
1563 $this->code_compta_fournisseur = trim((string) $this->code_compta_fournisseur);
1564
1565 // Check parameters. More tests are done later in the ->verify()
1566 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1567 $langs->load("errors");
1568 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1569 return -1;
1570 }
1571
1572 $customer = false;
1573 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1574 // If $allowmodcodeclient is set and value is not set, we generate it
1575 if (empty($this->code_compta_client)) {
1576 $ret = $this->get_codecompta('customer');
1577 if ($ret < 0) {
1578 return -1;
1579 }
1580 }
1581
1582 $customer = true;
1583 }
1584
1585 $supplier = false;
1586 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1587 // If $allowmodcodefournisseur is set and value is not set, we generate it
1588 if (empty($this->code_compta_fournisseur)) {
1589 $ret = $this->get_codecompta('supplier');
1590 if ($ret < 0) {
1591 return -1;
1592 }
1593 }
1594
1595 $supplier = true;
1596 }
1597
1598 //Web services
1599 $this->webservices_url = empty($this->webservices_url) ? '' : clean_url($this->webservices_url, 0);
1600 $this->webservices_key = trim((string) $this->webservices_key);
1601
1602 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1603 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1604
1605 //Incoterms
1606 $this->fk_incoterms = (int) $this->fk_incoterms;
1607 $this->location_incoterms = trim((string) $this->location_incoterms);
1608
1609 $this->db->begin();
1610
1611 // Check name is required and codes are ok or unique.
1612 // If error, this->errors[] is filled
1613 $result = 0;
1614 if ($action != 'add' && $action != 'merge') {
1615 // We don't check when update called during a create because verify was already done.
1616 // 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
1617 $result = $this->verify();
1618
1619 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1620 // So we can update record that were using and old numbering rule.
1621 if (is_array($this->errors)) {
1622 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1623 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1624 unset($this->errors[$key]); // Remove error message
1625 }
1626 }
1627 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1628 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1629 unset($this->errors[$key]); // Remove error message
1630 }
1631 }
1632 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1633 $result = 0;
1634 }
1635 }
1636 }
1637 $this->setUpperOrLowerCase();
1638 if ($result >= 0) {
1639 dol_syslog(get_class($this)."::update verify ok or not done");
1640
1641 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1642 $sql .= "entity = ".((int) $this->entity);
1643 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1644 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1645 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1646 $sql .= ",address = '".$this->db->escape($this->address)."'";
1647
1648 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1649 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1650
1651 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1652 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1653
1654 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1655 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1656 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1657 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1658 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1659 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1660
1661 $sql .= ",parent = ".($this->parent > 0 ? ((int) $this->parent) : "null");
1662
1663 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1664 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1665
1666 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1667 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1668 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1669 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1670 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1671 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1672
1673 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape((string) $this->tva_assuj)."'" : "null");
1674 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1675 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1676 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape((string) $this->vat_reverse_charge) . "'" : 0);
1677 }
1678 $sql .= ",euid = '".$this->db->escape($this->euid)."'";
1679 $sql .= ",status = ".((int) $this->status);
1680
1681 // Local taxes
1682 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape((string) $this->localtax1_assuj)."'" : "null");
1683 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape((string) $this->localtax2_assuj)."'" : "null");
1684 if ($this->localtax1_assuj == 1) {
1685 if ($this->localtax1_value != '') {
1686 $sql .= ", localtax1_value = ".((float) $this->localtax1_value);
1687 } else {
1688 $sql .= ", localtax1_value = 0.000";
1689 }
1690 } else {
1691 $sql .= ",localtax1_value =0.000";
1692 }
1693
1694 if ($this->localtax2_assuj == 1) {
1695 if ($this->localtax2_value != '') {
1696 $sql .= ",localtax2_value = ".((float) $this->localtax2_value);
1697 } else {
1698 $sql .= ",localtax2_value = 0.000";
1699 }
1700 } else {
1701 $sql .= ",localtax2_value = 0.000";
1702 }
1703
1704 $sql .= ",capital = ".($this->capital === null ? "null" : (float) $this->capital);
1705
1706 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1707
1708 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1709 if (isset($this->stcomm_id)) {
1710 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1711 }
1712 if (isset($this->typent_id)) {
1713 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1714 }
1715
1716 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape((string) $this->forme_juridique_code)."'" : "null");
1717 $sql .= ",birth = ".(!empty($this->birth) ? "'".$this->db->idate($this->birth)."'" : "null");
1718
1719 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape((string) $this->deposit_percent)."'" : "null");
1720 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape((string) $this->transport_mode_id)."'" : "null");
1721 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape((string) $this->transport_mode_supplier_id)."'" : "null");
1722 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape((string) $this->shipping_method_id)."'" : "null");
1723
1724 $sql .= ",client = ".(!empty($this->client) ? ((int) $this->client) : 0);
1725 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? ((int) $this->fournisseur) : 0);
1726 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1727 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1728 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1729 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1730 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? ((float) $this->outstanding_limit) : 'null');
1731 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? ((float) $this->order_min_amount) : 'null');
1732 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? ((float) $this->supplier_order_min_amount) : 'null');
1733 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1734 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1735 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1736 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1737 $sql .= ", mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape((string) $this->mode_reglement_id)."'" : "null");
1738 $sql .= ", cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape((string) $this->cond_reglement_id)."'" : "null");
1739 $sql .= ", mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape((string) $this->mode_reglement_supplier_id)."'" : "null");
1740 $sql .= ", cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape((string) $this->cond_reglement_supplier_id)."'" : "null");
1741 $sql .= ", fk_account = ".($this->fk_account > 0 ? (int) $this->fk_account : "null");
1742 if ($customer) {
1743 $sql .= ", accountancy_code_customer_general = ".(!empty($this->accountancy_code_customer_general) ? "'".$this->db->escape($this->accountancy_code_customer_general)."'" : "null");
1744 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1745 }
1746
1747 if ($supplier) {
1748 $sql .= ", accountancy_code_supplier_general = ".(!empty($this->accountancy_code_supplier_general) ? "'".$this->db->escape($this->accountancy_code_supplier_general)."'" : "null");
1749 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1750 }
1751 }
1752 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1753 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1754
1755 //Incoterms
1756 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1757 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1758
1759 if ($customer) {
1760 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1761 }
1762
1763 if ($supplier) {
1764 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1765 }
1766
1767 // The payment reference applies to customers and suppliers alike
1768 $sql .= ", tp_payment_reference = ".(!empty($this->tp_payment_reference) ? "'".$this->db->escape($this->tp_payment_reference)."'" : "null");
1769 $sql .= ", fk_user_modif = ".($user->id > 0 ? ((int) $user->id) : "null");
1770 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1771 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1772 $sql .= ", model_pdf = '".$this->db->escape((string) $this->model_pdf)."'";
1773 // Default warehouse of the thirdparty. Updated only when it can be edited from the GUI (stock module and
1774 // SOCIETE_ASK_FOR_WAREHOUSE on, see comm/card.php) and when the property is set, so a caller that did not
1775 // load it does not erase it. A value <= 0 removes the link.
1776 if (isModEnabled('stock') && getDolGlobalString('SOCIETE_ASK_FOR_WAREHOUSE') && isset($this->fk_warehouse) && $this->fk_warehouse !== '') {
1777 $sql .= ", fk_warehouse = ".((int) $this->fk_warehouse > 0 ? (int) $this->fk_warehouse : "null");
1778 }
1779 $sql .= " WHERE rowid = ".(int) $id;
1780
1781 $resql = $this->db->query($sql);
1782 if ($resql) {
1783 if (is_object($this->oldcopy)) { // If we have information on old values
1784 if ($this->oldcopy->country_id != $this->country_id) {
1785 unset($this->country_code);
1786 unset($this->country);
1787 }
1788 if ($this->oldcopy->state_id != $this->state_id) {
1789 unset($this->state_code);
1790 unset($this->state);
1791 }
1792 } else {
1793 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1794 unset($this->country);
1795 unset($this->state_code);
1796 unset($this->state);
1797 }
1798
1799 $nbrowsaffected = $this->db->affected_rows($resql);
1800
1801 if ($nbrowsaffected) {
1802 // Update information on linked member if it is an update
1803 if (!$nosyncmember && isModEnabled('member')) {
1804 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1805
1806 dol_syslog(get_class($this)."::update update linked member");
1807
1808 $lmember = new Adherent($this->db);
1809 $result = $lmember->fetch(0, '0', $this->id);
1810
1811 if ($result > 0) {
1812 $lmember->company = $this->name;
1813 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1814 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1815 $lmember->address = $this->address;
1816 $lmember->zip = $this->zip;
1817 $lmember->town = $this->town;
1818 $lmember->email = $this->email;
1819 $lmember->socialnetworks = $this->socialnetworks;
1820 $lmember->phone = $this->phone;
1821 $lmember->state_id = $this->state_id;
1822 $lmember->country_id = $this->country_id;
1823 $lmember->default_lang = $this->default_lang;
1824
1825 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1826 if ($result < 0) {
1827 $this->setErrorsFromObject($lmember);
1828 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1829 $error++;
1830 }
1831 } elseif ($result < 0) {
1832 $this->error = $lmember->error;
1833 $error++;
1834 }
1835 }
1836 }
1837
1838 $action = 'update';
1839
1840 // update accountancy for this entity
1841 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1842 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1843
1844 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1845 $sql .= " fk_soc";
1846 $sql .= ", entity";
1847 $sql .= ", vat_reverse_charge";
1848 $sql .= ", accountancy_code_customer_general";
1849 $sql .= ", accountancy_code_customer";
1850 $sql .= ", accountancy_code_supplier_general";
1851 $sql .= ", accountancy_code_supplier";
1852 $sql .= ", accountancy_code_buy";
1853 $sql .= ", accountancy_code_sell";
1854 $sql .= ", fk_account";
1855 $sql .= ", mode_reglement";
1856 $sql .= ", cond_reglement";
1857 $sql .= ", mode_reglement_supplier";
1858 $sql .= ", cond_reglement_supplier";
1859 $sql .= ") VALUES (";
1860 $sql .= ((int) $this->id);
1861 $sql .= ", ".((int) $conf->entity);
1862 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1863 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1864 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1865 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1866 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1867 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1868 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1869 $sql .= ", ".($this->fk_account > 0 ? (int) $this->fk_account : "null");
1870 $sql .= ", ".(!empty($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null");
1871 $sql .= ", ".(!empty($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null");
1872 $sql .= ", ".(!empty($this->mode_reglement_supplier_id) ? (int) $this->mode_reglement_supplier_id : "null");
1873 $sql .= ", ".(!empty($this->cond_reglement_supplier_id) ? (int) $this->cond_reglement_supplier_id : "null");
1874 $sql .= ")";
1875 $result = $this->db->query($sql);
1876 if (!$result) {
1877 $error++;
1878 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1879 }
1880 }
1881
1882 // Actions on extra fields
1883 if (!$error) {
1884 $result = $this->insertExtraFields();
1885 if ($result < 0) {
1886 $error++;
1887 }
1888 }
1889 // Actions on extra languages
1890 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1891 $result = $this->insertExtraLanguages();
1892 if ($result < 0) {
1893 $error++;
1894 }
1895 }
1896
1897 if (!$error && $call_trigger) {
1898 // Call trigger
1899 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1900 if ($result < 0) {
1901 $error++;
1902 }
1903 // End call triggers
1904 }
1905
1906 if (!$error) {
1907 dol_syslog(get_class($this)."::Update success");
1908 $this->db->commit();
1909 return 1;
1910 } else {
1911 $this->db->rollback();
1912 return -1;
1913 }
1914 } else {
1915 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1916 // Duplicate
1917 $this->error = $langs->trans("ErrorDuplicateField");
1918 $result = -1;
1919 } else {
1920 $this->error = $this->db->lasterror();
1921 $result = -2;
1922 }
1923 $this->db->rollback();
1924 return $result;
1925 }
1926 } else {
1927 $this->db->rollback();
1928 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1929 return -3;
1930 }
1931 }
1932
1952 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1953 {
1954 global $langs;
1955 global $conf;
1956
1957 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)) {
1958 return -1;
1959 }
1960
1961 $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';
1962 $sql .= ', s.status, s.fk_warehouse';
1963 $sql .= ', s.price_level';
1964 $sql .= ', GREATEST(s.tms, COALESCE(sef.tms, s.tms)) as date_modification, s.fk_user_creat, s.fk_user_modif';
1965 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1966 $sql .= ', s.socialnetworks';
1967 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1968 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1969 $sql .= ', s.capital, s.tva_intra, s.euid';
1970 $sql .= ', s.fk_typent as typent_id';
1971 $sql .= ', s.fk_effectif as effectif_id';
1972 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1973 $sql .= ', s.birth';
1974 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1975 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1976 $sql .= ', s.accountancy_code_customer_general, s.code_compta';
1977 $sql .= ', s.accountancy_code_supplier_general, s.code_compta_fournisseur';
1978 $sql .= ', s.accountancy_code_buy, s.accountancy_code_sell';
1979 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1980 $sql .= ', s.mode_reglement, s.cond_reglement, s.fk_account';
1981 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier';
1982 } else {
1983 $sql .= ', spe.accountancy_code_customer_general, spe.accountancy_code_customer as code_compta';
1984 $sql .= ', spe.accountancy_code_supplier_general, spe.accountancy_code_supplier as code_compta_fournisseur';
1985 $sql .= ', spe.accountancy_code_buy, spe.accountancy_code_sell';
1986 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1987 $sql .= ', spe.mode_reglement, spe.cond_reglement, spe.fk_account';
1988 $sql .= ', spe.mode_reglement_supplier, spe.cond_reglement_supplier';
1989 }
1990 $sql .= ', s.code_client, s.code_fournisseur, s.tp_payment_reference, s.parent, s.barcode';
1991 $sql .= ', s.fk_departement as state_id, s.fk_pays as country_id, s.fk_stcomm, s.deposit_percent, s.transport_mode';
1992 $sql .= ', s.tva_assuj';
1993 $sql .= ', s.transport_mode_supplier';
1994 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1995 $sql .= ', s.fk_shipping_method';
1996 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1997 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1998 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1999 $sql .= ', fj.libelle as forme_juridique';
2000 $sql .= ', e.libelle as effectif';
2001 $sql .= ', c.code as country_code, c.label as country';
2002 $sql .= ', d.code_departement as state_code, d.nom as state';
2003 $sql .= ', r.rowid as region_id, r.code_region as region_code';
2004 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
2005 $sql .= ', te.code as typent_code';
2006 $sql .= ', i.libelle as label_incoterms';
2007 if (!isModEnabled('multicompany')) {
2008 $sql .= ', s.remise_client, s.remise_supplier';
2009 } else {
2010 $sql .= ', sr.remise_client, sr2.remise_supplier';
2011 }
2012 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
2013 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_extrafields as sef ON sef.fk_object=s.rowid';
2014 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2015 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
2016 }
2017 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
2018 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
2019 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
2020 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
2021 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
2022 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
2023 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
2024 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
2025 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
2026 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
2027 if (isModEnabled('multicompany')) {
2028 $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').'))';
2029 $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').'))';
2030 }
2031 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
2032
2033 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
2034 if ($is_client) {
2035 $sql .= ' AND s.client > 0';
2036 }
2037 if ($is_supplier) {
2038 $sql .= ' AND s.fournisseur > 0';
2039 } // if both false, no test (the thirdparty can be client and/or supplier)
2040
2041 if ($rowid) {
2042 $sql .= ' AND s.rowid = '.((int) $rowid);
2043 }
2044 if ($ref) {
2045 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
2046 }
2047 if ($ref_alias) {
2048 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
2049 }
2050 if ($ref_ext) {
2051 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
2052 }
2053 if ($barcode) {
2054 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
2055 }
2056 if ($idprof1) {
2057 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
2058 }
2059 if ($idprof2) {
2060 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
2061 }
2062 if ($idprof3) {
2063 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
2064 }
2065 if ($idprof4) {
2066 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
2067 }
2068 if ($idprof5) {
2069 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
2070 }
2071 if ($idprof6) {
2072 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
2073 }
2074 if ($email) {
2075 $sql .= " AND s.email = '".$this->db->escape($email)."'";
2076 }
2077
2078 $resql = $this->db->query($sql);
2079 if ($resql) {
2080 $num = $this->db->num_rows($resql);
2081 if ($num > 1) {
2082 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2083 dol_syslog($this->error, LOG_WARNING);
2084 $result = -2;
2085 } elseif ($num) { // $num = 1
2086 $obj = $this->db->fetch_object($resql);
2087
2088 $this->id = $obj->rowid;
2089 $this->entity = $obj->entity;
2090 $this->canvas = $obj->canvas;
2091
2092 $this->ref = $obj->name;
2093 $this->name = $obj->name;
2094 $this->nom = $obj->name; // deprecated
2095 $this->name_alias = $obj->name_alias;
2096 $this->ref_ext = $obj->ref_ext;
2097
2098 $this->date_creation = $this->db->jdate($obj->date_creation);
2099 $this->date_modification = $this->db->jdate($obj->date_modification);
2100 $this->user_creation_id = $obj->fk_user_creat;
2101 $this->user_modification_id = $obj->fk_user_modif;
2102
2103 $this->address = $obj->address;
2104 $this->zip = $obj->zip;
2105 $this->town = $obj->town;
2106
2107 $this->country_id = $obj->country_id;
2108 $this->country_code = $obj->country_id ? $obj->country_code : '';
2109 // $langs may be null when called from a page with NOREQUIRETRAN (like viewimage.php)
2110 $this->country = $obj->country_id ? ((is_object($langs) && $langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
2111
2112 $this->state_id = $obj->state_id;
2113 $this->state_code = $obj->state_code;
2114 $this->region_id = $obj->region_id;
2115 $this->region_code = $obj->region_code;
2116 $this->state = ($obj->state != '-' ? $obj->state : '');
2117
2118 $transcode = (is_object($langs) ? $langs->trans('StatusProspect'.$obj->fk_stcomm) : 'StatusProspect'.$obj->fk_stcomm);
2119 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
2120 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
2121 $this->status_prospect_label = $label; // label status prospect
2122 $this->stcomm_picto = $obj->stcomm_picto; // commercial status picto
2123
2124 $this->email = $obj->email;
2125 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
2126
2127 $this->url = $obj->url;
2128 $this->phone = $obj->phone;
2129 $this->phone_mobile = $obj->phone_mobile;
2130 $this->fax = $obj->fax;
2131
2132 $this->parent = $obj->parent;
2133
2134 $this->idprof1 = $obj->idprof1;
2135 $this->idprof2 = $obj->idprof2;
2136 $this->idprof3 = $obj->idprof3;
2137 $this->idprof4 = $obj->idprof4;
2138 $this->idprof5 = $obj->idprof5;
2139 $this->idprof6 = $obj->idprof6;
2140
2141 $this->capital = $obj->capital;
2142
2143 $this->code_client = $obj->code_client;
2144 $this->code_fournisseur = $obj->code_fournisseur;
2145 $this->tp_payment_reference = $obj->tp_payment_reference;
2146
2147 $this->accountancy_code_customer_general = $obj->accountancy_code_customer_general;
2148 $this->code_compta_client = $obj->code_compta;
2149 $this->accountancy_code_supplier_general = $obj->accountancy_code_supplier_general;
2150 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
2151
2152 $this->barcode = $obj->barcode;
2153
2154 $this->tva_assuj = $obj->tva_assuj;
2155 $this->tva_intra = $obj->tva_intra;
2156
2157 if (!empty($obj->spe_vat_reverse_charge)) {
2158 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2159 } elseif (!empty($obj->soc_vat_reverse_charge)) {
2160 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2161 } else {
2162 $this->vat_reverse_charge = 0;
2163 }
2164 $this->euid = $obj->euid;
2165
2166 $this->status = $obj->status;
2167
2168 // Local Taxes
2169 $this->localtax1_assuj = $obj->localtax1_assuj;
2170 $this->localtax2_assuj = $obj->localtax2_assuj;
2171
2172 $this->localtax1_value = $obj->localtax1_value;
2173 $this->localtax2_value = $obj->localtax2_value;
2174
2175 $this->typent_id = $obj->typent_id;
2176 $this->typent_code = $obj->typent_code;
2177
2178 $this->effectif_id = $obj->effectif_id;
2179 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2180
2181 $this->forme_juridique_code = $obj->forme_juridique_code;
2182 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2183 $this->birth = $this->db->jdate($obj->birth);
2184
2185 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2186
2187 $this->prefix_comm = $obj->prefix_comm;
2188
2189 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2190 $this->remise_supplier_percent = $obj->remise_supplier;
2191
2192 $this->mode_reglement_id = $obj->mode_reglement;
2193 $this->cond_reglement_id = $obj->cond_reglement;
2194 $this->deposit_percent = $obj->deposit_percent;
2195 $this->transport_mode_id = $obj->transport_mode;
2196 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2197 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2198 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2199 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2200 $this->fk_account = $obj->fk_account;
2201
2202 $this->client = $obj->client;
2203 $this->fournisseur = $obj->fournisseur;
2204
2205 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2206 $this->note_private = $obj->note_private;
2207 $this->note_public = $obj->note_public;
2208 $this->model_pdf = $obj->model_pdf;
2209 $this->default_lang = $obj->default_lang;
2210 $this->logo = $obj->logo;
2211 $this->logo_squarred = $obj->logo_squarred;
2212
2213 $this->webservices_url = $obj->webservices_url;
2214 $this->webservices_key = $obj->webservices_key;
2215
2216 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2217 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2218
2219 $this->outstanding_limit = $obj->outstanding_limit;
2220 $this->order_min_amount = $obj->order_min_amount;
2221 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2222
2223 // multi price
2224 $this->price_level = $obj->price_level;
2225
2226 // warehouse
2227 $this->fk_warehouse = $obj->fk_warehouse;
2228
2229 $this->import_key = $obj->import_key;
2230
2231 //Incoterms
2232 $this->fk_incoterms = $obj->fk_incoterms;
2233 $this->location_incoterms = $obj->location_incoterms;
2234 $this->label_incoterms = $obj->label_incoterms;
2235
2236 // multicurrency
2237 $this->fk_multicurrency = $obj->fk_multicurrency;
2238 $this->multicurrency_code = $obj->multicurrency_code;
2239
2240 // pdf
2241 $this->model_pdf = $obj->model_pdf;
2242 $this->last_main_doc = $obj->last_main_doc;
2243
2244 $result = $this->id;
2245
2246 // fetch optionals attributes and labels
2247 $this->fetch_optionals();
2248 } else {
2249 $result = 0;
2250 }
2251
2252 $this->db->free($resql);
2253 } else {
2254 $this->error = $this->db->lasterror();
2255 $this->errors[] = $this->db->lasterror();
2256 $result = -3;
2257 }
2258
2259 // Use first price level if level not defined for third party
2260 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->price_level)) {
2261 $this->price_level = 1;
2262 }
2263
2264 return $result;
2265 }
2266
2277 public function setBankAccount($fk_account, $notrigger = 0, $userused = null)
2278 {
2279 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2280 return parent::setBankAccount($fk_account, $notrigger, $userused);
2281 }
2282
2283 global $conf, $user;
2284
2285 if (empty($userused)) {
2286 $userused = $user;
2287 }
2288
2289 if ($fk_account < 0) {
2290 $fk_account = 'NULL';
2291 }
2292 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
2293
2294 $this->db->begin();
2295
2296 $sql = "UPDATE ".MAIN_DB_PREFIX."societe_perentity SET fk_account = ".((int) $fk_account);
2297 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity);
2298 $resql = $this->db->query($sql);
2299 if ($resql && !$this->db->affected_rows($resql)) {
2300 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (fk_soc, entity, fk_account)";
2301 $sql .= " VALUES (".((int) $this->id).", ".((int) $conf->entity).", ".((int) $fk_account).")";
2302 $resql = $this->db->query($sql);
2303 }
2304
2305 if (!$resql) {
2306 dol_syslog(get_class($this).'::setBankAccount Error '.$this->db->error());
2307 $this->error = $this->db->lasterror();
2308 $this->db->rollback();
2309 return -1;
2310 }
2311
2312 if (!$notrigger) {
2313 $this->context['bankaccountupdate'] = 1;
2314 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2315 if ($result < 0) {
2316 $this->db->rollback();
2317 return -1;
2318 }
2319 }
2320
2321 $this->fk_account = ($fk_account == 'NULL') ? null : $fk_account;
2322 $this->db->commit();
2323 return 1;
2324 }
2325
2335 public function setPaymentTerms($id, $deposit_percent = null)
2336 {
2337 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2338 return parent::setPaymentTerms($id, $deposit_percent);
2339 }
2340
2341 global $conf;
2342
2343 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.formatLogObject($deposit_percent).')');
2344
2345 $fieldname = (get_class($this) == 'Fournisseur') ? 'cond_reglement_supplier' : 'cond_reglement';
2346
2347 if (empty($deposit_percent) || $deposit_percent < 0) {
2348 $deposit_percent = (float) getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2349 }
2350 if ($deposit_percent > 100) {
2351 $deposit_percent = 100;
2352 }
2353
2354 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET deposit_percent = ".(empty($deposit_percent) ? 'NULL' : "'".$this->db->escape((string) $deposit_percent)."'");
2355 $sql .= " WHERE rowid = ".((int) $this->id);
2356 $resql = $this->db->query($sql);
2357
2358 if ($resql) {
2359 $sql = "UPDATE ".MAIN_DB_PREFIX."societe_perentity SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2360 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity);
2361 $resql = $this->db->query($sql);
2362 if ($resql && !$this->db->affected_rows($resql)) {
2363 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (fk_soc, entity, ".$this->db->sanitize($fieldname).")";
2364 $sql .= " VALUES (".((int) $this->id).", ".((int) $conf->entity).", ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL').")";
2365 $resql = $this->db->query($sql);
2366 }
2367 }
2368
2369 if (!$resql) {
2370 dol_syslog(get_class($this).'::setPaymentTerms Error '.$this->db->error());
2371 $this->error = $this->db->lasterror();
2372 return -1;
2373 }
2374
2375 $this->cond_reglement_id = $id;
2376 if (get_class($this) == 'Fournisseur') {
2377 $this->cond_reglement_supplier_id = $id;
2378 }
2379 $this->deposit_percent = $deposit_percent;
2380 return 1;
2381 }
2382
2390 public function setPaymentMethods($id)
2391 {
2392 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2393 return parent::setPaymentMethods($id);
2394 }
2395
2396 global $conf;
2397
2398 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2399
2400 $fieldname = (get_class($this) == 'Fournisseur') ? 'mode_reglement_supplier' : 'mode_reglement';
2401
2402 $sql = "UPDATE ".MAIN_DB_PREFIX."societe_perentity SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2403 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity);
2404 $resql = $this->db->query($sql);
2405 if ($resql && !$this->db->affected_rows($resql)) {
2406 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (fk_soc, entity, ".$this->db->sanitize($fieldname).")";
2407 $sql .= " VALUES (".((int) $this->id).", ".((int) $conf->entity).", ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL').")";
2408 $resql = $this->db->query($sql);
2409 }
2410
2411 if (!$resql) {
2412 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2413 $this->error = $this->db->lasterror();
2414 return -1;
2415 }
2416
2417 $this->mode_reglement_id = $id;
2418 if (get_class($this) == 'Fournisseur') {
2419 $this->mode_reglement_supplier_id = $id;
2420 }
2421 return 1;
2422 }
2423
2445 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0, $vatnumber = '')
2446 {
2447 // A rowid is known, it is a unique key so we found it
2448 if ($rowid) {
2449 return $rowid;
2450 }
2451
2452 dol_syslog(get_class($this)."::findNearest", LOG_DEBUG);
2453 $tmpthirdparty = new Societe($this->db);
2454
2455 // We try to find the thirdparty with exact matching on all fields
2456 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2457 if ($result != 0) {
2458 return $result;
2459 }
2460
2461 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2462 dol_syslog("Thirdparty not found with exact match so we try barcode search", LOG_DEBUG);
2463 if ($barcode) {
2464 $result = $tmpthirdparty->fetch(0, '', '', $barcode, '', '', '', '', '', '', '', '', $is_client, $is_supplier);
2465 if ($result != 0) {
2466 return $result;
2467 }
2468 }
2469
2470 $sqlstart = "SELECT s.rowid as id FROM ".MAIN_DB_PREFIX."societe as s";
2471 $sqlstart .= ' WHERE s.entity IN ('.getEntity($this->element).')';
2472 if ($is_client) {
2473 $sqlstart .= ' AND s.client > 0';
2474 }
2475 if ($is_supplier) {
2476 $sqlstart .= ' AND s.fournisseur > 0';
2477 } // if both false, no test (the thirdparty can be client and/or supplier)
2478
2479 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2480 dol_syslog("Thirdparty not found with barcode search so we try profids search", LOG_DEBUG);
2481 $sqlprof = "";
2482 if ($idprof1) {
2483 $sqlprof .= " s.siren = '".$this->db->escape($idprof1)."'";
2484 }
2485 if ($idprof2) {
2486 if ($sqlprof) {
2487 $sqlprof .= " OR";
2488 }
2489 $sqlprof .= " s.siret = '".$this->db->escape($idprof2)."'";
2490 }
2491 if ($idprof3) {
2492 if ($sqlprof) {
2493 $sqlprof .= " OR";
2494 }
2495 $sqlprof .= " s.ape = '".$this->db->escape($idprof3)."'";
2496 }
2497 if ($idprof4) {
2498 if ($sqlprof) {
2499 $sqlprof .= " OR";
2500 }
2501 $sqlprof .= " s.idprof4 = '".$this->db->escape($idprof4)."'";
2502 }
2503 if ($idprof5) {
2504 if ($sqlprof) {
2505 $sqlprof .= " OR";
2506 }
2507 $sqlprof .= " s.idprof5 = '".$this->db->escape($idprof5)."'";
2508 }
2509 if ($idprof6) {
2510 if ($sqlprof) {
2511 $sqlprof .= " OR";
2512 }
2513 $sqlprof .= " s.idprof6 = '".$this->db->escape($idprof6)."'";
2514 }
2515 if ($vatnumber) {
2516 if ($sqlprof) {
2517 $sqlprof .= " OR";
2518 }
2519 $sqlprof .= " s.tva_intra = '".$this->db->escape($vatnumber)."'";
2520 }
2521
2522 if ($sqlprof) {
2523 $sqlprofquery = $sqlstart . " AND (".$sqlprof." )";
2524 $resql = $this->db->query($sqlprofquery);
2525 if ($resql) {
2526 $num = $this->db->num_rows($resql);
2527 if ($num > 1) {
2528 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2529 dol_syslog($this->error, LOG_WARNING);
2530 $result = -2;
2531 } elseif ($num) {
2532 $obj = $this->db->fetch_object($resql);
2533 $result = $obj->id;
2534 } else {
2535 $result = 0;
2536 }
2537 } else {
2538 $this->error = $this->db->lasterror();
2539 $this->errors[] = $this->db->lasterror();
2540 $result = -3;
2541 }
2542 if ($result != 0) {
2543 return $result;
2544 }
2545 }
2546
2547 // Then search on email (+ restriction on is_client and is_supplier)
2548 dol_syslog("Thirdparty not found with profids search so we try email search", LOG_DEBUG);
2549 if ($email) {
2550 $result = $tmpthirdparty->fetch(0, '', '', '', '', '', '', '', '', '', $email, '', $is_client, $is_supplier);
2551 if ($result != 0) {
2552 return $result;
2553 }
2554 }
2555
2556 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2557 dol_syslog("Thirdparty not found with email search so we try ref, ref_ext or ref_alias search", LOG_DEBUG);
2558 $sqlref = "";
2559 if ($ref) {
2560 $sqlref .= " s.nom = '".$this->db->escape($ref)."'";
2561 }
2562 if ($ref_alias) {
2563 if ($sqlref) {
2564 $sqlref .= " OR";
2565 }
2566 $sqlref .= " s.name_alias = '".$this->db->escape($ref_alias)."'";
2567 }
2568 if ($ref_ext) {
2569 if ($sqlref) {
2570 $sqlref .= " OR";
2571 }
2572 $sqlref .= " s.ref_ext = '".$this->db->escape($ref_ext)."'";
2573 }
2574
2575 if ($sqlref) {
2576 $sqlrefquery = $sqlstart . " AND (".$sqlref." )";
2577 $resql = $this->db->query($sqlrefquery);
2578 if ($resql) {
2579 $num = $this->db->num_rows($resql);
2580 if ($num > 1) {
2581 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2582 dol_syslog($this->error, LOG_WARNING);
2583 $result = -2;
2584 } elseif ($num) {
2585 $obj = $this->db->fetch_object($resql);
2586 $result = $obj->id;
2587 } else {
2588 $result = 0;
2589 }
2590 } else {
2591 $this->error = $this->db->lasterror();
2592 $this->errors[] = $this->db->lasterror();
2593 $result = -3;
2594 }
2595 }
2596 return $result;
2597 }
2598
2608 public function delete($id, $fuser = null, $call_trigger = 1, $nodeletefiles = 0)
2609 {
2610 global $conf, $user;
2611
2612 if (empty($fuser)) {
2613 $fuser = $user;
2614 }
2615
2616 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2617
2618 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2619
2620 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2621 $error = 0;
2622
2623 // Test if child exists
2624 $objectisused = $this->isObjectUsed($id);
2625 if (empty($objectisused)) {
2626 $this->db->begin();
2627
2628 // User is mandatory for trigger call
2629 if ($call_trigger) {
2630 // Call trigger
2631 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2632 if ($result < 0) {
2633 $error++;
2634 }
2635 // End call triggers
2636 }
2637
2638 if (!$error) {
2639 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2640 $static_cat = new Categorie($this->db);
2641 $toute_categs = array();
2642
2643 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2644 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2645 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2646
2647 // Remove each "Categorie"
2648 foreach ($toute_categs as $type => $categs_type) {
2649 foreach ($categs_type as $cat) {
2650 $cat->del_type($this, $type);
2651 }
2652 }
2653 }
2654
2655 if (!$error) {
2656 foreach ($this->childtablesoncascade as $tabletodelete) {
2657 $deleteFromObject = explode(':', $tabletodelete, 4);
2658 if (count($deleteFromObject) >= 2) {
2659 $className = str_replace('@', '', $deleteFromObject[0]);
2660 $filepath = $deleteFromObject[1];
2661 $columnName = $deleteFromObject[2];
2662 if (dol_include_once($filepath)) {
2663 $child_object = new $className($this->db);
2664 '@phan-var-force CommonObject $child_object';
2665 $result = $child_object->deleteByParentField($id, $columnName);
2666 if ($result < 0) {
2667 $error++;
2668 $this->errors[] = $child_object->error;
2669 break;
2670 }
2671 } else {
2672 $error++;
2673 $this->errors[] = 'Cannot include child class file '.$filepath;
2674 break;
2675 }
2676 } else {
2677 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2678 $sql .= " WHERE fk_soc = ".((int) $id);
2679 if (!$this->db->query($sql)) {
2680 $error++;
2681 $this->errors[] = $this->db->lasterror();
2682 break;
2683 }
2684 }
2685 }
2686 }
2687
2688 // Removed extrafields
2689 if (!$error) {
2690 $result = $this->deleteExtraFields();
2691 if ($result < 0) {
2692 $error++;
2693 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2694 }
2695 }
2696
2697 // Remove links to subsidiaries companies
2698 if (!$error) {
2699 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2700 $sql .= " SET parent = NULL";
2701 $sql .= " WHERE parent = ".((int) $id);
2702 if (!$this->db->query($sql)) {
2703 $error++;
2704 $this->errors[] = $this->db->lasterror();
2705 }
2706 }
2707
2708 // Remove third party
2709 if (!$error) {
2710 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2711 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2712 $sql .= " WHERE fk_soc = ".((int) $id);
2713 if (!$this->db->query($sql)) {
2714 $error++;
2715 $this->errors[] = $this->db->lasterror();
2716 }
2717 }
2718
2719 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2720 $sql .= " WHERE rowid = ".((int) $id);
2721 if (!$this->db->query($sql)) {
2722 $error++;
2723 $this->errors[] = $this->db->lasterror();
2724 }
2725 }
2726
2727 if (!$error) {
2728 $this->db->commit();
2729
2730 // Delete directory
2731 if (empty($nodeletefiles) && !empty($conf->societe->multidir_output[$entity])) {
2732 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2733 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2734 if (dol_is_dir($docdir)) {
2735 dol_delete_dir_recursive($docdir);
2736 }
2737 }
2738
2739 return 1;
2740 } else {
2741 dol_syslog($this->error, LOG_ERR);
2742 $this->db->rollback();
2743 return -1;
2744 }
2745 } else {
2746 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2747 }
2748 return 0;
2749 }
2750
2751 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2759 public function set_as_client()
2760 {
2761 // phpcs:enable
2762 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2763 return $this->setAsCustomer();
2764 }
2765
2772 public function setAsCustomer()
2773 {
2774 global $user;
2775
2776 if ($this->id) {
2777 $newclient = 1;
2778 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2779 $newclient = 3; // If prospected, we keep prospect tag
2780 }
2781 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2782 $sql .= " SET client = ".((int) $newclient);
2783 $sql .= " WHERE rowid = ".((int) $this->id);
2784
2785 $this->db->begin();
2786
2787 $resql = $this->db->query($sql);
2788 if ($resql) {
2789 $this->client = $newclient;
2790
2791 // Call trigger
2792 $result = $this->call_trigger('COMPANY_MODIFY', $user);
2793 if ($result < 0) {
2794 $this->db->rollback();
2795 return -1;
2796 }
2797 // End call triggers
2798
2799 $this->db->commit();
2800 return 1;
2801 } else {
2802 $this->db->rollback();
2803 return -1;
2804 }
2805 }
2806 return 0;
2807 }
2808
2809 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2818 public function set_remise_client($remise, $note, User $user)
2819 {
2820 // phpcs:enable
2821 global $conf, $langs;
2822
2823 // Parameter cleaning
2824 $note = trim((string) $note);
2825 if (!$note) {
2826 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2827 return -2;
2828 }
2829
2830 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2831
2832 if ($this->id) {
2833 $this->db->begin();
2834
2835 $now = dol_now();
2836
2837 // Position current discount
2838 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2839 $sql .= " SET remise_client = '".$this->db->escape((string) $remise)."'";
2840 $sql .= " WHERE rowid = ".((int) $this->id);
2841 $resql = $this->db->query($sql);
2842 if (!$resql) {
2843 $this->db->rollback();
2844 $this->error = $this->db->error();
2845 return -1;
2846 }
2847
2848 // Writes trace in discount history
2849 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2850 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2851 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape((string) $remise)."',";
2852 $sql .= " '".$this->db->escape($note)."',";
2853 $sql .= " ".((int) $user->id);
2854 $sql .= ")";
2855
2856 $resql = $this->db->query($sql);
2857 if (!$resql) {
2858 $this->db->rollback();
2859 $this->error = $this->db->lasterror();
2860 return -1;
2861 }
2862
2863 $this->db->commit();
2864
2865 return 1;
2866 }
2867 return -1;
2868 }
2869
2870 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2879 public function set_remise_supplier($remise, $note, User $user)
2880 {
2881 // phpcs:enable
2882 global $conf, $langs;
2883
2884 // Parameter cleaning
2885 $note = trim((string) $note);
2886 if (!$note) {
2887 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2888 return -2;
2889 }
2890
2891 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2892
2893 if ($this->id) {
2894 $this->db->begin();
2895
2896 $now = dol_now();
2897
2898 // Position current discount
2899 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2900 $sql .= " SET remise_supplier = ".((float) $remise);
2901 $sql .= " WHERE rowid = ".((int) $this->id);
2902 $resql = $this->db->query($sql);
2903 if (!$resql) {
2904 $this->db->rollback();
2905 $this->error = $this->db->error();
2906 return -1;
2907 }
2908
2909 // Writes trace in discount history
2910 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2911 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2912 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", ".((float) $remise).",";
2913 $sql .= " '".$this->db->escape($note)."',";
2914 $sql .= " ".((int) $user->id);
2915 $sql .= ")";
2916
2917 $resql = $this->db->query($sql);
2918 if (!$resql) {
2919 $this->db->rollback();
2920 $this->error = $this->db->lasterror();
2921 return -1;
2922 }
2923
2924 $this->db->commit();
2925 return 1;
2926 }
2927
2928 return -1;
2929 }
2930
2931 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2943 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2944 {
2945 // phpcs:enable
2946 global $langs, $mysoc;
2947
2948 // Clean parameters
2949 $remise = (float) price2num($remise);
2950 $desc = trim((string) $desc);
2951
2952 // Check parameters
2953 if (!($remise > 0)) {
2954 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2955 return -1;
2956 }
2957 if (!$desc) {
2958 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2959 return -2;
2960 }
2961
2962 if ($this->id > 0) {
2963 // Separate VAT code from VAT rate string
2964 // Discount type determines who is buyer and seller
2965 $taxes = getTaxesFromId($vatrate, ($discount_type == 0 ? $this : $mysoc), ($discount_type == 0 ? $mysoc : $this), 0);
2966 $reg = array();
2967 $vat_src_code = '';
2968 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2969 $vat_src_code = $reg[1];
2970 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2971 }
2972
2973 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2974
2975 $discount = new DiscountAbsolute($this->db);
2976 $discount->fk_soc = $this->id;
2977 $discount->socid = $this->id;
2978
2979 $discount->discount_type = $discount_type;
2980 $discount->multicurrency_code = $this->multicurrency_code;
2981
2982 $tmparray = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
2983 $this->fk_multicurrency = $tmparray[0];
2984 $this->multicurrency_tx = $tmparray[1];
2985
2986 $discount->multicurrency_tx = $this->multicurrency_tx;
2987
2988 $vat_tx = (float) price2num($vatrate);
2989
2990 $discount->generateFromAmount($remise, ($price_base_type == 'TTC' ? 1 : 0), $vat_tx, $taxes['localtax1'], $taxes['localtax2'], (int) $taxes['localtax1_type'], (int) $taxes['localtax2_type']);
2991
2992 $discount->vat_src_code = $vat_src_code;
2993
2994 $discount->description = $desc;
2995
2996 $result = $discount->create($user);
2997 if ($result > 0) {
2998 return $result;
2999 } else {
3000 $this->error = $discount->error;
3001 return -3;
3002 }
3003 } else {
3004 return 0;
3005 }
3006 }
3007
3017 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
3018 {
3019 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
3020
3021 $discountstatic = new DiscountAbsolute($this->db);
3022 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
3023 if ($result >= 0) {
3024 return $result;
3025 } else {
3026 $this->error = $discountstatic->error;
3027 return -1;
3028 }
3029 }
3030
3031
3038 public function getOpenCreditNotesNotYetConvertedIntoDiscount($discount_type = 0)
3039 {
3040 global $conf;
3041
3042 $sql = "SELECT COUNT(f.rowid) as nb, SUM(f.total_ttc) as amount, SUM(f.multicurrency_total_ttc) as multicurrency_amount";
3043 if (!empty($discount_type)) {
3044 $sql .= " FROM ".$this->db->prefix()."facture_fourn as f";
3045 } else {
3046 $sql .= " FROM ".$this->db->prefix()."facture as f";
3047 }
3048 $sql .= " WHERE f.entity = ".((int) $conf->entity);
3049 $sql .= " AND paye = 0 AND fk_statut = 1";
3050 $sql .= " AND f.type = ".CommonInvoice::TYPE_CREDIT_NOTE;
3051 $sql .= " AND NOT EXISTS (SELECT rowid FROM ".$this->db->prefix()."societe_remise_except as rc";
3052 $sql .= " WHERE rc.discount_type = ".((int) $discount_type);
3053 if (!empty($discount_type)) {
3054 $sql .= " AND rc.fk_invoice_supplier = f.rowid";
3055 } else {
3056 $sql .= " AND rc.fk_facture = f.rowid";
3057 }
3058 $sql .= " AND rc.fk_soc = ".((int) $this->id);
3059 $sql .= ")";
3060 $sql .= " AND f.fk_soc = ".((int) $this->id);
3061
3062 $resql = $this->db->query($sql);
3063 if ($resql) {
3064 $obj = $this->db->fetch_object($resql);
3065
3066 return $obj->nb;
3067 }
3068
3069 return -1;
3070 }
3071
3072
3082 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
3083 {
3084 global $conf;
3085
3086 $reparray = array();
3087
3088 $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";
3089 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
3090 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
3091 // Condition here should be the same than into select_dolusers()
3092 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
3093 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
3094 } else {
3095 $sql .= " WHERE entity IN (0, ".((int) $conf->entity).")";
3096 }
3097
3098 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
3099 if (empty($sortfield)) {
3100 $sortfield = 'u.lastname,u.firstname';
3101 }
3102 if (empty($sortorder)) {
3103 $sortorder = str_repeat('ASC,', count(explode(',', $sortfield)) - 1) . 'ASC';
3104 }
3105 $sql .= $this->db->order($sortfield, $sortorder);
3106
3107 $resql = $this->db->query($sql);
3108 if ($resql) {
3109 $num = $this->db->num_rows($resql);
3110 $i = 0;
3111 while ($i < $num) {
3112 $obj = $this->db->fetch_object($resql);
3113
3114 if (empty($mode)) {
3115 $reparray[$i]['id'] = (int) $obj->rowid;
3116 $reparray[$i]['lastname'] = $obj->lastname;
3117 $reparray[$i]['firstname'] = $obj->firstname;
3118 $reparray[$i]['email'] = $obj->email;
3119 $reparray[$i]['phone'] = $obj->office_phone;
3120 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
3121 $reparray[$i]['office_fax'] = $obj->office_fax;
3122 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
3123 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
3124 $reparray[$i]['job'] = $obj->job;
3125 $reparray[$i]['statut'] = $obj->status; // deprecated
3126 $reparray[$i]['status'] = $obj->status;
3127 $reparray[$i]['entity'] = $obj->entity;
3128 $reparray[$i]['login'] = $obj->login;
3129 $reparray[$i]['photo'] = $obj->photo;
3130 $reparray[$i]['gender'] = $obj->gender;
3131 } else {
3132 $reparray[] = (int) $obj->rowid;
3133 }
3134 $i++;
3135 }
3136 return $reparray;
3137 } else {
3138 dol_print_error($this->db);
3139 return -1;
3140 }
3141 }
3142
3150 public function setPriceLevel($price_level, User $user)
3151 {
3152 if ($this->id) {
3153 $now = dol_now();
3154
3155 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
3156 $sql .= " SET price_level = ".((int) $price_level);
3157 $sql .= " WHERE rowid = ".((int) $this->id);
3158
3159 if (!$this->db->query($sql)) {
3160 dol_print_error($this->db);
3161 return -1;
3162 }
3163
3164 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
3165 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
3166 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
3167
3168 if (!$this->db->query($sql)) {
3169 dol_print_error($this->db);
3170 return -1;
3171 }
3172 return 1;
3173 }
3174 return -1;
3175 }
3176
3177 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3185 public function add_commercial(User $user, $commid)
3186 {
3187 // phpcs:enable
3188 $error = 0;
3189
3190 if ($this->id > 0 && $commid > 0) {
3191 $this->db->begin();
3192
3193 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
3194 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3195
3196 $resql = $this->db->query($sql);
3197 if (!$resql) {
3198 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
3199 $error++;
3200 }
3201
3202 if (!$error) {
3203 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
3204 $sql .= " (fk_soc, fk_user)";
3205 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
3206
3207 $resql = $this->db->query($sql);
3208 if (!$resql) {
3209 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
3210 $error++;
3211 }
3212 }
3213
3214 if (!$error) {
3215 $this->context = array('commercial_modified' => $commid);
3216
3217 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
3218 if ($result < 0) {
3219 $error++;
3220 }
3221 }
3222
3223 if (!$error) {
3224 $this->db->commit();
3225 return 1;
3226 } else {
3227 $this->db->rollback();
3228 return -1;
3229 }
3230 }
3231
3232 return 0;
3233 }
3234
3235 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3243 public function del_commercial(User $user, $commid)
3244 {
3245 // phpcs:enable
3246 $error = 0;
3247 $this->context = array('commercial_modified' => $commid);
3248
3249 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
3250 if ($result < 0) {
3251 $error++;
3252 }
3253
3254 if ($this->id > 0 && $commid > 0) {
3255 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
3256 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
3257
3258 if (!$this->db->query($sql)) {
3259 $error++;
3260 dol_syslog(get_class($this)."::del_commercial Erreur");
3261 }
3262 }
3263
3264 if ($error) {
3265 return -1;
3266 } else {
3267 return 1;
3268 }
3269 }
3270
3278 public function getTooltipContentArray($params)
3279 {
3280 global $conf, $langs, $user;
3281
3282 $langs->loadLangs(['companies', 'commercial']);
3283
3284 $datas = array();
3285
3286 $option = $params['option'] ?? '';
3287 $nofetch = !empty($params['nofetch']);
3288
3289 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
3290
3291 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3292 return ['optimize' => $langs->trans("ShowCompany")];
3293 }
3294
3295 if (!empty($this->logo) && class_exists('Form')) {
3296 $photo = '<div class="photointooltip floatright">';
3297 $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.
3298 $photo .= '</div>';
3299 $datas['photo'] = $photo;
3300 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
3301 /*$label.= '<div class="photointooltip">';
3302 $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.
3303 $label.= '</div><div style="clear: both;"></div>';*/
3304 // }
3305
3306 $datas['divopen'] = '<div class="centpercent">';
3307
3308 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3309 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
3310 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3311 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
3312 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3313 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
3314 } elseif ($option == 'agenda') {
3315 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3316 } elseif ($option == 'project') {
3317 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3318 } elseif ($option == 'margin') {
3319 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3320 } elseif ($option == 'contact') {
3321 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3322 } elseif ($option == 'ban') {
3323 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3324 }
3325
3326 // By default
3327 if (empty($datas['picto'])) {
3328 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
3329 }
3330 if (isset($this->status)) {
3331 $datas['status'] = ' '.$this->getLibStatut(5);
3332 }
3333 if (isset($this->client) && isset($this->fournisseur)) {
3334 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1, '', 0, 'span');
3335 }
3336 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
3337 if (!empty($this->name_alias) && empty($noaliasinname)) {
3338 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
3339 }
3340 if (!empty($this->email)) {
3341 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
3342 }
3343 if (!empty($this->url)) {
3344 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
3345 }
3346 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
3347 $phonelist = array();
3348 if ($this->phone) {
3349 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
3350 }
3351 // deliberately not making new list because fax uses same list as phone
3352 if ($this->phone_mobile) {
3353 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'mobile');
3354 }
3355 if ($this->fax) {
3356 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
3357 }
3358 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
3359 }
3360
3361 if (!empty($this->address)) {
3362 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ', ', $langs); // Address + country
3363 } elseif (!empty($this->country_code)) {
3364 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
3365 }
3366 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
3367 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
3368 }
3369
3370 if (!empty($this->euid) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'euid') !== false)) {
3371 $datas['euid'] = '<br><b>'.$langs->trans('EUIDShort').':</b> '.dol_escape_htmltag($this->euid);
3372 }
3373
3374 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
3375 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
3376 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
3377 }
3378 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
3379 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
3380 }
3381 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
3382 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
3383 }
3384 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
3385 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
3386 }
3387 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
3388 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
3389 }
3390 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
3391 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
3392 }
3393 }
3394
3395 $datas['separator'] = '<br>';
3396
3397 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
3398 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
3399 }
3400 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
3401 $langs->load('compta');
3402 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
3403 }
3404 // show categories for this record only in ajax to not overload lists
3405 if (!$nofetch && isModEnabled('category') && $this->client) {
3406 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3407 $form = new Form($this->db);
3408 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
3409 }
3410 if (!empty($this->code_fournisseur) && $this->fournisseur) {
3411 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
3412 }
3413 if (isModEnabled('accounting') && $this->fournisseur) {
3414 $langs->load('compta');
3415 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
3416 }
3417 // show categories for this record only in ajax to not overload lists
3418 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
3419 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3420 $form = new Form($this->db);
3421 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
3422 }
3423
3424 $datas['divclose'] = '</div>';
3425
3426 return $datas;
3427 }
3428
3443 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = 'valignmiddle', $addlinktonotes = 0)
3444 {
3445 global $conf, $langs, $hookmanager, $user;
3446
3447 if (!empty($conf->dol_no_mouse_hover)) {
3448 $notooltip = 1; // Force disable tooltips
3449 }
3450
3451 $name = $this->name ? $this->name : $this->nom;
3452
3453 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3454 if (empty($option) && $this->client > 0) {
3455 $option = 'customer';
3456 }
3457 if (empty($option) && $this->fournisseur > 0) {
3458 $option = 'supplier';
3459 }
3460 }
3461
3462 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3463 $code = '';
3464 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3465 $code = $this->code_client.' - ';
3466 }
3467
3468 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3469 $code .= $this->code_fournisseur.' - ';
3470 }
3471
3472 if ($code) {
3473 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3474 $name = $code.' '.$name;
3475 } else {
3476 $name = $code;
3477 }
3478 }
3479 }
3480
3481 if (!empty($this->name_alias) && empty($noaliasinname)) {
3482 $name .= ' ('.$this->name_alias.')';
3483 }
3484
3485 $result = '';
3486 $params = [
3487 'id' => $this->id,
3488 'objecttype' => $this->element,
3489 'option' => $option,
3490 'nofetch' => 1,
3491 ];
3492 $classfortooltip = 'classfortooltip';
3493 $dataparams = '';
3494 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3495 $classfortooltip = 'classforajaxtooltip';
3496 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3497 $label = '';
3498 } else {
3499 $label = implode($this->getTooltipContentArray($params));
3500 }
3501
3502 $linkstart = '';
3503 $linkend = '';
3504
3505 $query = ['socid' => $this->id];
3506 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3507 $baseurl = DOL_URL_ROOT.'/comm/card.php';
3508 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3509 $baseurl = DOL_URL_ROOT.'/comm/card.php';
3510 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3511 $baseurl = DOL_URL_ROOT.'/fourn/card.php';
3512 } elseif ($option == 'agenda') {
3513 $baseurl = DOL_URL_ROOT.'/societe/agenda.php';
3514 } elseif ($option == 'project') {
3515 $baseurl = DOL_URL_ROOT.'/societe/project.php';
3516 } elseif ($option == 'margin') {
3517 $baseurl = DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php';
3518 $query['type'] = 1;
3519 } elseif ($option == 'contact') {
3520 $baseurl = DOL_URL_ROOT.'/societe/contact.php';
3521 } elseif ($option == 'ban') {
3522 $baseurl = DOL_URL_ROOT.'/societe/paymentmodes.php';
3523 } else {
3524 // By default
3525 $baseurl = DOL_URL_ROOT.'/societe/card.php';
3526 }
3527
3528 // Add type of canvas
3529 if (!empty($this->canvas)) {
3530 $query['canvas'] = $this->canvas;
3531 }
3532 // Add param to save lastsearch_values or not
3533 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3534 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3535 $add_save_lastsearch_values = 1;
3536 }
3537 if ($add_save_lastsearch_values) {
3538 $query['save_lastsearch_values'] = 1;
3539 }
3540 $linkstart = '<a href="'.dolBuildUrl($baseurl, $query).'"';
3541
3542 $linkclose = '';
3543 if (empty($notooltip)) {
3544 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3545 $label = $langs->trans("ShowCompany");
3546 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3547 }
3548 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3549 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl'.($withpicto ? ' valignmiddle' : '').'"';
3550 $target_value = array('_self', '_blank', '_parent', '_top');
3551 if (in_array($target, $target_value)) {
3552 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3553 }
3554 } else {
3555 $linkclose .= ' class="'.($morecss ? ' '.$morecss : '').'"';
3556 }
3557 $linkstart .= $linkclose.'>';
3558 $linkend = '</a>';
3559
3560 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3561 $linkstart = '';
3562 $linkend = '';
3563 }
3564
3565 $result .= $linkstart;
3566 if ($withpicto) {
3567 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3568 }
3569 if ($withpicto != 2) {
3570 $result .= dol_escape_htmltag($maxlen ? dol_trunc((string) $name, $maxlen) : $name);
3571 }
3572 $result .= $linkend;
3573
3574 if ($addlinktonotes) {
3575 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
3576 if ($txttoshow) {
3577 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
3578 $result .= ' <span class="note inline-block">';
3579 $result .= '<a href="'.DOL_URL_ROOT.'/societe/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
3580 $result .= img_picto('', 'note');
3581 $result .= '</a>';
3582 $result .= '</span>';
3583 }
3584 }
3585
3586 global $action;
3587 $hookmanager->initHooks(array('thirdpartydao'));
3588 $parameters = array(
3589 'id' => $this->id,
3590 'getnomurl' => &$result,
3591 'withpicto ' => $withpicto,
3592 'option' => $option,
3593 'maxlen' => $maxlen,
3594 'notooltip' => $notooltip,
3595 'save_lastsearch_value' => $save_lastsearch_value
3596 );
3597 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3598 if ($reshook > 0) {
3599 $result = $hookmanager->resPrint;
3600 } else {
3601 $result .= $hookmanager->resPrint;
3602 }
3603
3604 return $result;
3605 }
3606
3616 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3617 {
3618 global $langs;
3619
3620 $s = '';
3621 if (empty($option) || preg_match('/prospect/', $option)) {
3622 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3623 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.dolPrintHTMLForAttribute($langs->trans("Prospect")).'"';
3624 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'" tabindex="-1"' : '';
3625 $s .= '>'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3626 }
3627 }
3628 if (empty($option) || preg_match('/customer/', $option)) {
3629 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3630 $s .= '<'.$tag.' class="customer-back" title="'.dolPrintHTMLForAttribute($langs->trans("Customer")).'"';
3631 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'" tabindex="-1"' : '';
3632 $s .= '>'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3633 }
3634 }
3635 if (empty($option) || preg_match('/supplier/', $option)) {
3636 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3637 $s .= '<'.$tag.' class="vendor-back" title="'.dolPrintHTMLForAttribute($langs->trans("Supplier")).'"';
3638 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'" tabindex="-1"' : '';
3639 $s .= '>'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3640 }
3641 }
3642
3643 return $s;
3644 }
3645
3646
3653 public function getLibStatut($mode = 0)
3654 {
3655 return $this->LibStatut($this->status, $mode);
3656 }
3657
3658 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3666 public function LibStatut($status, $mode = 0)
3667 {
3668 // phpcs:enable
3669 global $langs;
3670 $langs->load('companies');
3671
3672 $statusType = 'status4';
3673 if ($status == 0) {
3674 $statusType = 'status6';
3675 }
3676
3677 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3678 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3679 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3680 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3681 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3682 }
3683
3684 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3685 }
3686
3687 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3694 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3695 {
3696 // phpcs:enable
3697 global $langs;
3698
3699 $contact_emails = $this->contact_property_array('email', 1);
3700
3701 if ($this->email && $addthirdparty) {
3702 if (empty($this->name)) {
3703 $this->name = $this->nom;
3704 }
3705 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3706 }
3707
3708 //var_dump($contact_emails)
3709 return $contact_emails;
3710 }
3711
3712 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3719 {
3720 // phpcs:enable
3721 global $langs;
3722
3723 $contact_phone = $this->contact_property_array('mobile');
3724
3725 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3726 if (empty($this->name)) {
3727 $this->name = $this->nom;
3728 }
3729 // TODO: Test if phone is not already present in contact array
3730 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3731 }
3732 return $contact_phone;
3733 }
3734
3735 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3743 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3744 {
3745 // phpcs:enable
3746 global $langs;
3747
3748 $contact_property = array();
3749
3750
3751 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3752 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3753 $sql .= " WHERE fk_soc = ".((int) $this->id);
3754 $sql .= " AND entity IN (".getEntity($this->element).")";
3755 $sql .= " ORDER BY lastname, firstname";
3756
3757 $resql = $this->db->query($sql);
3758 if ($resql) {
3759 $nump = $this->db->num_rows($resql);
3760 if ($nump) {
3761 $sepa = "(";
3762 $sepb = ")";
3763 if ($mode == 'email') {
3764 //$sepa="&lt;"; $sepb="&gt;";
3765 $sepa = "<";
3766 $sepb = ">";
3767 }
3768 $i = 0;
3769 while ($i < $nump) {
3770 $obj = $this->db->fetch_object($resql);
3771 if ($mode == 'email') {
3772 $property = $obj->email;
3773 } elseif ($mode == 'mobile') {
3774 $property = $obj->phone_mobile;
3775 } else {
3776 $property = $obj->$mode;
3777 }
3778
3779 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3780 if ($obj->status == 1 || empty($hidedisabled)) {
3781 if (empty($property)) {
3782 if ($mode == 'email') {
3783 $property = $langs->transnoentitiesnoconv("NoEMail");
3784 } elseif ($mode == 'mobile') {
3785 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3786 }
3787 }
3788
3789 if (!empty($obj->poste)) {
3790 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3791 } else {
3792 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3793 }
3794 }
3795 $i++;
3796 }
3797 }
3798 } else {
3799 dol_print_error($this->db);
3800 }
3801 return $contact_property;
3802 }
3803
3804
3805 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3811 public function contact_array()
3812 {
3813 // phpcs:enable
3814 $contacts = array();
3815
3816 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3817 $resql = $this->db->query($sql);
3818 if ($resql) {
3819 $nump = $this->db->num_rows($resql);
3820 if ($nump) {
3821 $i = 0;
3822 while ($i < $nump) {
3823 $obj = $this->db->fetch_object($resql);
3824 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3825 $i++;
3826 }
3827 }
3828 } else {
3829 dol_print_error($this->db);
3830 }
3831 return $contacts;
3832 }
3833
3834 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3840 public function contact_array_objects()
3841 {
3842 // phpcs:enable
3843 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3844 $contacts = array();
3845
3846 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3847 $resql = $this->db->query($sql);
3848 if ($resql) {
3849 $nump = $this->db->num_rows($resql);
3850 if ($nump) {
3851 $i = 0;
3852 while ($i < $nump) {
3853 $obj = $this->db->fetch_object($resql);
3854 $contact = new Contact($this->db);
3855 $contact->fetch($obj->rowid);
3856 $contacts[] = $contact;
3857 $i++;
3858 }
3859 }
3860 } else {
3861 dol_print_error($this->db);
3862 }
3863 return $contacts;
3864 }
3865
3866 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3874 public function contact_get_property($rowid, $mode)
3875 {
3876 // phpcs:enable
3877 $contact_property = '';
3878
3879 if (empty($rowid)) {
3880 return '';
3881 }
3882
3883 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3884 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3885 $sql .= " WHERE rowid = ".((int) $rowid);
3886
3887 $resql = $this->db->query($sql);
3888 if ($resql) {
3889 $nump = $this->db->num_rows($resql);
3890
3891 if ($nump) {
3892 $obj = $this->db->fetch_object($resql);
3893
3894 if ($mode == 'email') {
3895 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3896 } elseif ($mode == 'mobile') {
3897 $contact_property = $obj->phone_mobile;
3898 }
3899 }
3900 return $contact_property;
3901 } else {
3902 dol_print_error($this->db);
3903 }
3904
3905 return '';
3906 }
3907
3908
3909 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3916 public function display_rib($mode = 'label')
3917 {
3918 // phpcs:enable
3919 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3920
3921 $bac = new CompanyBankAccount($this->db);
3922 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3923 $bac->fetch(0, '', $this->id);
3924
3925 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3926 if ($mode == 'label') {
3927 return $bac->getRibLabel(true);
3928 } elseif ($mode == 'rum') {
3929 if (empty($bac->rum)) {
3930 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3931 $prelevement = new BonPrelevement($this->db);
3932 $bac->fetch_thirdparty();
3933 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, (string) $bac->id);
3934 }
3935 return $bac->rum;
3936 } elseif ($mode == 'format') {
3937 return $bac->frstrecur;
3938 } else {
3939 return 'BadParameterToFunctionDisplayRib';
3940 }
3941 } else {
3942 return '';
3943 }
3944 }
3945
3946 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3952 public function get_all_rib()
3953 {
3954 // phpcs:enable
3955 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3956 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3957 $result = $this->db->query($sql);
3958 if (!$result) {
3959 $this->error = $this->db->lasterror();
3960 $this->errors[] = $this->db->lasterror();
3961 return 0;
3962 } else {
3963 $num_rows = $this->db->num_rows($result);
3964 $rib_array = array();
3965 if ($num_rows) {
3966 while ($obj = $this->db->fetch_object($result)) {
3967 $rib = new CompanyBankAccount($this->db);
3968 $rib->fetch($obj->rowid);
3969 $rib_array[] = $rib;
3970 }
3971 }
3972 return $rib_array;
3973 }
3974 }
3975
3979 public function getDefaultRib()
3980 {
3981 // phpcs:enable
3982 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3983 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND default_rib = 1 AND fk_soc = ". (int) $this->id;
3984 $resql = $this->db->query($sql);
3985 if (!$resql) {
3986 $this->error = $this->db->lasterror();
3987 $this->errors[] = $this->db->lasterror();
3988 return -1;
3989 } else {
3990 $num_rows = $this->db->num_rows($resql);
3991 $rib_array = array();
3992 if ($num_rows) {
3993 while ($obj = $this->db->fetch_object($resql)) {
3994 return $obj->rowid;
3995 }
3996 }
3997 return 0;
3998 }
3999 }
4000
4001
4002 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4011 public function get_codeclient($objsoc = null, $type = 0)
4012 {
4013 // phpcs:enable
4014 global $conf;
4015 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4016 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4017
4018 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4019 foreach ($dirsociete as $dirroot) {
4020 $res = dol_include_once($dirroot.$module.'.php');
4021 if ($res) {
4022 break;
4023 }
4024 }
4026 $mod = new $module($this->db);
4027 '@phan-var-force ModeleThirdPartyCode $mod';
4028
4029 $this->code_client = $mod->getNextValue($objsoc, $type);
4030 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
4031
4032 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
4033 }
4034 }
4035
4036 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4045 public function get_codefournisseur($objsoc = null, $type = 1)
4046 {
4047 // phpcs:enable
4048 global $conf;
4049 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4050 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4051
4052 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4053 foreach ($dirsociete as $dirroot) {
4054 $res = dol_include_once($dirroot.$module.'.php');
4055 if ($res) {
4056 break;
4057 }
4058 }
4060 $mod = new $module($this->db);
4061 '@phan-var-force ModeleThirdPartyCode $mod';
4062
4063 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
4064
4065 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
4066 }
4067 }
4068
4069 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4076 public function codeclient_modifiable()
4077 {
4078 // phpcs:enable
4079 global $conf;
4080 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4081 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4082
4083 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4084 foreach ($dirsociete as $dirroot) {
4085 $res = dol_include_once($dirroot.$module.'.php');
4086 if ($res) {
4087 break;
4088 }
4089 }
4090
4091 $mod = new $module($this->db);
4092 '@phan-var-force ModeleThirdPartyCode $mod';
4093
4094 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
4095 if ($mod->code_modifiable_null && !$this->code_client) {
4096 return 1;
4097 }
4098 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
4099 return 1;
4100 }
4101 if ($mod->code_modifiable) {
4102 return 1; // To be put last
4103 }
4104 return 0;
4105 } else {
4106 return 0;
4107 }
4108 }
4109
4110
4111 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4118 {
4119 // phpcs:enable
4120 global $conf;
4121 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4122 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4123
4124 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4125 foreach ($dirsociete as $dirroot) {
4126 $res = dol_include_once($dirroot.$module.'.php');
4127 if ($res) {
4128 break;
4129 }
4130 }
4131
4132 $mod = new $module($this->db);
4133 '@phan-var-force ModeleThirdPartyCode $mod';
4134
4135 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
4136 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
4137 return 1;
4138 }
4139 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
4140 return 1;
4141 }
4142 if ($mod->code_modifiable) {
4143 return 1; // To be put last
4144 }
4145 return 0;
4146 } else {
4147 return 0;
4148 }
4149 }
4150
4151
4152 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4164 public function check_codeclient()
4165 {
4166 // phpcs:enable
4167 global $conf;
4168 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4169 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4170
4171 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4172 foreach ($dirsociete as $dirroot) {
4173 $res = dol_include_once($dirroot.$module.'.php');
4174 if ($res) {
4175 break;
4176 }
4177 }
4178
4179 $mod = new $module($this->db);
4180 '@phan-var-force ModeleThirdPartyCode $mod';
4181
4182 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
4183 $result = $mod->verif($this->db, $this->code_client, $this, 0);
4184 if ($result) { // If error
4185 $this->error = $mod->error;
4186 $this->errors = $mod->errors;
4187 }
4188 return $result;
4189 } else {
4190 return 0;
4191 }
4192 }
4193
4194 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4206 public function check_codefournisseur()
4207 {
4208 // phpcs:enable
4209 global $conf;
4210 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
4211 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
4212
4213 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4214 foreach ($dirsociete as $dirroot) {
4215 $res = dol_include_once($dirroot.$module.'.php');
4216 if ($res) {
4217 break;
4218 }
4219 }
4220
4221 $mod = new $module($this->db);
4222 '@phan-var-force ModeleThirdPartyCode $mod';
4223
4224 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
4225 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
4226 if ($result) { // If error
4227 $this->error = $mod->error;
4228 $this->errors = $mod->errors;
4229 }
4230 return $result;
4231 } else {
4232 return 0;
4233 }
4234 }
4235
4236 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4245 public function get_codecompta($type)
4246 {
4247 // phpcs:enable
4248 global $conf;
4249
4250 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
4251 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
4252 $res = false;
4253 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
4254 foreach ($dirsociete as $dirroot) {
4255 $res = dol_include_once($dirroot.$module.'.php');
4256 if ($res) {
4257 break;
4258 }
4259 }
4260
4261 if ($res) {
4262 $mod = new $module();
4263 '@phan-var-force ModeleAccountancyCode $mod';
4264
4265 // Set code count in $mod->code
4266 $result = $mod->get_code($this->db, $this, $type);
4267 if ($result < 0) {
4268 $this->error = $mod->error;
4269 $this->errors = $mod->errors;
4270 }
4271
4272 if ($type == 'customer') {
4273 $this->code_compta_client = $mod->code;
4274 } elseif ($type == 'supplier') {
4275 $this->code_compta_fournisseur = $mod->code;
4276 }
4277
4278 return $result;
4279 } else {
4280 $this->error = 'ErrorAccountancyCodeNotDefined';
4281 return -1;
4282 }
4283 } else {
4284 if ($type == 'customer') {
4285 $this->code_compta_client = '';
4286 } elseif ($type == 'supplier') {
4287 $this->code_compta_fournisseur = '';
4288 }
4289
4290 return 0;
4291 }
4292 }
4293
4300 public function setParent($id)
4301 {
4302 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
4303
4304 if ($this->id) {
4305 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
4306 if ($id > 0) {
4307 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
4308 if ($sameparent < 0) {
4309 return -1;
4310 }
4311 if ($sameparent == 1) {
4312 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
4313 return -1;
4314 }
4315 }
4316
4317 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? ((int) $id) : 'null').' WHERE rowid = '.((int) $this->id);
4318
4319 $resql = $this->db->query($sql);
4320 if ($resql) {
4321 $this->parent = $id;
4322 return 1;
4323 } else {
4324 return -1;
4325 }
4326 }
4327
4328 return -1;
4329 }
4330
4339 public function validateFamilyTree($idparent, $idchild, $counter = 0)
4340 {
4341 if ($counter > 100) {
4342 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
4343 }
4344
4345 $sql = 'SELECT s.parent';
4346 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
4347 $sql .= ' WHERE rowid = '.((int) $idparent);
4348 $resql = $this->db->query($sql);
4349 if ($resql) {
4350 $obj = $this->db->fetch_object($resql);
4351
4352 if ($obj->parent == '') {
4353 return 0;
4354 } elseif ($obj->parent == $idchild) {
4355 return 1;
4356 } else {
4357 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
4358 }
4359 return $sameparent;
4360 } else {
4361 return -1;
4362 }
4363 }
4364
4372 public function getParentsForCompany($company_id, $parents = array())
4373 {
4374 global $langs;
4375
4376 if ($company_id > 0) {
4377 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
4378 $resql = $this->db->query($sql);
4379 if ($resql) {
4380 if ($obj = $this->db->fetch_object($resql)) {
4381 $parent = $obj->parent;
4382 if ($parent > 0 && !in_array($parent, $parents)) {
4383 $parents[] = $parent;
4384 return $this->getParentsForCompany($parent, $parents);
4385 } else {
4386 return $parents;
4387 }
4388 }
4389 $this->db->free($resql);
4390 } else {
4391 $this->error = $langs->trans('GetCompanyParentsError', $this->db->lasterror());
4392 $this->errors[] = $this->error;
4393 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
4394 }
4395 }
4396 // Return a default value when $company_id is not greater than 0
4397 return array();
4398 }
4399
4406 public function getChildrenForCompany($company_id)
4407 {
4408 global $langs;
4409
4410 $children = array();
4411 if ($company_id > 0) {
4412 $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "societe WHERE parent = ".((int) $company_id);
4413 $resql = $this->db->query($sql);
4414 if ($resql) {
4415 while ($obj = $this->db->fetch_object($resql)) {
4416 $child = $obj->rowid;
4417 if ($child > 0 && !in_array($child, $children)) {
4418 $children[] = $child;
4419 }
4420 }
4421 $this->db->free($resql);
4422 } else {
4423 $this->error = $this->db->lasterror();
4424 $this->errors[] = $this->error;
4425 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
4426 }
4427 }
4428 // Return a default value when $company_id is not greater than 0
4429 return $children;
4430 }
4431
4432 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4439 public function id_prof_verifiable($idprof)
4440 {
4441 // phpcs:enable
4442 global $conf;
4443
4444 switch ($idprof) {
4445 case 1:
4446 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
4447 break;
4448 case 2:
4449 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
4450 break;
4451 case 3:
4452 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
4453 break;
4454 case 4:
4455 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
4456 break;
4457 case 5:
4458 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
4459 break;
4460 case 6:
4461 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
4462 break;
4463 default:
4464 $ret = false;
4465 }
4466
4467 return $ret;
4468 }
4469
4470 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4479 public function id_prof_exists($idprof, $value, $socid = 0)
4480 {
4481 // phpcs:enable
4482 $field = $idprof;
4483
4484 switch ($idprof) { // For backward compatibility
4485 case '1':
4486 case 'idprof1':
4487 $field = "siren";
4488 break;
4489 case '2':
4490 case 'idprof2':
4491 $field = "siret";
4492 break;
4493 case '3':
4494 case 'idprof3':
4495 $field = "ape";
4496 break;
4497 case '4':
4498 case 'idprof4':
4499 $field = "idprof4";
4500 break;
4501 case '5':
4502 $field = "idprof5";
4503 break;
4504 case '6':
4505 $field = "idprof6";
4506 break;
4507 }
4508
4509 //Verify duplicate entries
4510 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
4511 if ($socid) {
4512 $sql .= " AND rowid <> ".((int) $socid);
4513 }
4514 $resql = $this->db->query($sql);
4515 if ($resql) {
4516 $obj = $this->db->fetch_object($resql);
4517 $count = $obj->nb;
4518 } else {
4519 $count = 0;
4520 print $this->db->error();
4521 }
4522 $this->db->free($resql);
4523
4524 if ($count > 0) {
4525 return true;
4526 } else {
4527 return false;
4528 }
4529 }
4530
4531 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4538 public function id_prof_check($idprof)
4539 {
4540 // phpcs:enable
4541
4542 // Load the library necessary to check the professional identifiers
4543 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4544
4545 return isValidProfIds($idprof, $this);
4546 }
4547
4548 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4557 public function id_prof_url($idprof, $thirdparty)
4558 {
4559 // phpcs:enable
4560 global $langs, $hookmanager;
4561
4562 $url = '';
4563 $action = '';
4564
4565 $hookmanager->initHooks(array('idprofurl'));
4566 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4567 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4568 if (empty($reshook)) {
4569 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4570 return '';
4571 }
4572
4573 // TODO Move links to validate professional ID into the dictionary table "country" + column "linkidprof1"
4574 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4575 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4576 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.urlencode($strippedIdProf1); // See also http://avis-situation-sirene.insee.fr/
4577 }
4578 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4579 $url = 'https://beta.companieshouse.gov.uk/company/'.urlencode($strippedIdProf1);
4580 }
4581 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4582 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.urlencode($strippedIdProf1);
4583 }
4584 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4585 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.urlencode($strippedIdProf1).';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4586 }
4587 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4588 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.urlencode($strippedIdProf1);
4589 }
4590 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4591 $url = 'http://www.nif.pt/'.urlencode($strippedIdProf1);
4592 }
4593
4594 if ($url) {
4595 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4596 }
4597 } else {
4598 return $hookmanager->resPrint;
4599 }
4600
4601 return '';
4602 }
4603
4604 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4610 public function has_projects()
4611 {
4612 // phpcs:enable
4613 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4614 $resql = $this->db->query($sql);
4615 if ($resql) {
4616 $obj = $this->db->fetch_object($resql);
4617 $count = $obj->numproj;
4618 } else {
4619 $count = 0;
4620 print $this->db->error();
4621 }
4622 $this->db->free($resql);
4623 return ($count > 0);
4624 }
4625
4626
4633 public function info($id)
4634 {
4635 $sql = "SELECT s.rowid, s.nom as name, s.datec, GREATEST(s.tms, COALESCE(sef.tms, s.tms)) as datem,";
4636 $sql .= " fk_user_creat, fk_user_modif";
4637 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4638 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields as sef ON sef.fk_object=s.rowid";
4639 $sql .= " WHERE s.rowid = ".((int) $id);
4640
4641 $result = $this->db->query($sql);
4642 if ($result) {
4643 if ($this->db->num_rows($result)) {
4644 $obj = $this->db->fetch_object($result);
4645
4646 $this->id = $obj->rowid;
4647
4648 $this->user_creation_id = $obj->fk_user_creat;
4649 $this->user_modification_id = $obj->fk_user_modif;
4650 $this->date_creation = $this->db->jdate($obj->datec);
4651 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4652
4653 $this->ref = $obj->name;
4654 }
4655
4656 $this->db->free($result);
4657 } else {
4658 dol_print_error($this->db);
4659 }
4660 }
4661
4667 public function isACompany()
4668 {
4669 // Define if third party is treated as company (or not) when nature is unknown
4670 //$defaultvalue = in_array($mysoc->country_code, array('FR')) ? 0 : 1; // TODO On old version, default was 1 for everybody, move this to defaultvalue = 0 for everybody
4671 $defaultvalue = 0;
4672 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES', $defaultvalue);
4673
4674 // Now try to guess using different tips
4675 if (!empty($this->tva_intra)) {
4676 $isACompany = 2;
4677 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6) || !empty($this->euid)) {
4678 $isACompany = 3;
4679 } else {
4680 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) { // never or rarely set
4681 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) { // TODO Add a field is_a_company into dictionary
4682 $isACompany = 0;
4683 }
4684 } else {
4685 $isACompany = 4;
4686 }
4687 }
4688
4689 return $isACompany;
4690 }
4691
4697 public function isInEEC()
4698 {
4699 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4700 return isInEEC($this);
4701 }
4702
4708 public function isInSEPA()
4709 {
4710 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4711 return isInSEPA($this);
4712 }
4713
4714 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4720 public function LoadSupplierCateg()
4721 {
4722 // phpcs:enable
4723 $this->supplierCategories = array();
4724 $sql = "SELECT rowid, label";
4725 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4726 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4727
4728 $resql = $this->db->query($sql);
4729 if ($resql) {
4730 while ($obj = $this->db->fetch_object($resql)) {
4731 $this->supplierCategories[$obj->rowid] = $obj->label;
4732 }
4733 return 0;
4734 } else {
4735 return -1;
4736 }
4737 }
4738
4739 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4746 public function AddFournisseurInCategory($categorie_id)
4747 {
4748 // phpcs:enable
4749 if ($categorie_id > 0 && $this->id > 0) {
4750 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4751 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4752
4753 if ($resql = $this->db->query($sql)) {
4754 return 0;
4755 }
4756 } else {
4757 return 0;
4758 }
4759 return -1;
4760 }
4761
4767 public function getNbOfEMailings()
4768 {
4769 $sql = "SELECT count(mc.email) as nb";
4770 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4771 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4772 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4773
4774 $resql = $this->db->query($sql);
4775 if ($resql) {
4776 $obj = $this->db->fetch_object($resql);
4777 $nb = (int) $obj->nb;
4778
4779 $this->db->free($resql);
4780 return $nb;
4781 } else {
4782 $this->error = $this->db->error();
4783 return -1;
4784 }
4785 }
4786
4794 public function setNoEmail($no_email, $unsubscribegroup = '')
4795 {
4796 $error = 0;
4797
4798 // Update mass emailing flag into table mailing_unsubscribe
4799 if ($this->email) {
4800 $this->db->begin();
4801
4802 if ($no_email) {
4803 // TODO Add $unsubscribegroup
4804 $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)."'";
4805 $resql = $this->db->query($sql);
4806 if ($resql) {
4807 $obj = $this->db->fetch_object($resql);
4808 $noemail = $obj->nb;
4809 if (empty($noemail)) {
4810 // TODO Add $unsubscribegroup
4811 $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())."')";
4812 $resql = $this->db->query($sql);
4813 if (!$resql) {
4814 $error++;
4815 $this->error = $this->db->lasterror();
4816 $this->errors[] = $this->error;
4817 }
4818 }
4819 } else {
4820 $error++;
4821 $this->error = $this->db->lasterror();
4822 $this->errors[] = $this->error;
4823 }
4824 } else {
4825 // TODO Add $unsubscribegroup
4826 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4827 $resql = $this->db->query($sql);
4828 if (!$resql) {
4829 $error++;
4830 $this->error = $this->db->lasterror();
4831 $this->errors[] = $this->error;
4832 }
4833 }
4834
4835 if (empty($error)) {
4836 $this->no_email = $no_email;
4837 $this->db->commit();
4838 return 1;
4839 } else {
4840 $this->db->rollback();
4841 return $error * -1;
4842 }
4843 }
4844
4845 return 0;
4846 }
4847
4854 public function getNoEmail()
4855 {
4856 if ($this->email) {
4857 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4858 $resql = $this->db->query($sql);
4859 if ($resql) {
4860 $obj = $this->db->fetch_object($resql);
4861 $this->no_email = $obj->nb;
4862 return 1;
4863 } else {
4864 $this->error = $this->db->lasterror();
4865 $this->errors[] = $this->error;
4866 return -1;
4867 }
4868 }
4869 return 0;
4870 }
4871
4872 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4882 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4883 {
4884 // phpcs:enable
4885 global $user, $langs;
4886
4887 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4888 $fullname = $member->getFullName($langs);
4889
4890 if ($member->morphy == 'mor') {
4891 if (empty($socname)) {
4892 $socname = $member->company ? $member->company : $member->societe;
4893 }
4894 if (!empty($fullname) && empty($socalias)) {
4895 $socalias = $fullname;
4896 }
4897 } elseif (empty($socname) && $member->morphy == 'phy') {
4898 if (empty($socname)) {
4899 $socname = $fullname;
4900 }
4901 if (!empty($member->company) && empty($socalias)) {
4902 $socalias = $member->company;
4903 }
4904 }
4905
4906 $name = (string) $socname;
4907 $alias = $socalias ? $socalias : '';
4908
4909 // Positionne parameters
4910 $this->nom = $name; // TODO deprecated
4911 $this->name = $name;
4912 $this->name_alias = $alias;
4913 $this->address = $member->address;
4914 $this->zip = $member->zip;
4915 $this->town = $member->town;
4916 $this->country_code = $member->country_code;
4917 $this->country_id = $member->country_id;
4918 $this->phone = $member->phone; // Prof phone
4919 $this->email = $member->email;
4920 $this->socialnetworks = $member->socialnetworks;
4921 $this->entity = $member->entity;
4922
4923 $this->client = 1; // A member is a customer by default
4924 if (getDolGlobalString('THIRDPARTY_CUSTOMERCODE_EQUALS_MEMBERREF')) {
4925 $this->code_client = $member->ref; // set Customer Code equal to existing Member Reference
4926 } else {
4927 $this->code_client = ($customercode ? $customercode : -1); // set new auto-incremented Customer Code
4928 }
4929 $this->code_fournisseur = '-1';
4930 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4931 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4932
4933 $this->db->begin();
4934
4935 // Creates and positions $this->id
4936 $result = $this->create($user);
4937
4938 if ($result >= 0) {
4939 // Auto-create contact on thirdparty creation
4940 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4941 // Fill fields needed by contact
4942 $this->name_bis = $member->lastname;
4943 $this->firstname = $member->firstname;
4944 $this->civility_id = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4945 $this->civility_code = (empty($member->civility_code) ? $member->civility_id : $member->civility_code);
4946
4947 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4948 $result = $this->create_individual($user);
4949
4950 if ($result < 0) {
4951 $this->db->rollback();
4952 return -1;
4953 }
4954 }
4955
4956 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4957 $sql .= " SET fk_soc = ".((int) $this->id);
4958 $sql .= " WHERE rowid = ".((int) $member->id);
4959
4960 $resql = $this->db->query($sql);
4961 if ($resql) {
4962 $this->db->commit();
4963 return $this->id;
4964 } else {
4965 $this->error = $this->db->error();
4966
4967 $this->db->rollback();
4968 return -1;
4969 }
4970 } else {
4971 // $this->error already positioned
4972 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4973
4974 $this->db->rollback();
4975 return $result;
4976 }
4977 }
4978
4985 public function setMysoc(Conf $conf)
4986 {
4987 global $langs;
4988
4989 $this->id = 0;
4990 $this->entity = $conf->entity;
4991 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4992 $this->nom = $this->name; // deprecated
4993 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4994 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4995 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4996 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4997
4998 $this->currency_code = getDolGlobalString('MAIN_MONNAIE');
4999
5000 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
5001
5002 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
5003
5004 // We define country_id, country_code and country
5005 $country_id = 0;
5006 $country_code = $country_label = '';
5007 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
5008 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
5009 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
5010 if (!empty($tmp[1]) && !empty($tmp[2])) { // MAIN_INFO_SOCIETE_COUNTRY is the canonical "id:code:label"
5011 $country_code = $tmp[1];
5012 $country_label = $tmp[2];
5013 } elseif ($country_id > 0) {
5014 // For backward compatibility. The value is "id" only, or a legacy "id:label" where the
5015 // second token is a country label (e.g. 'Suisse') and not an ISO code. In both cases we
5016 // must not keep a label in country_code (it would break code-based lookups like VAT rates),
5017 // so we rebuild code and label from the authoritative country id.
5018 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
5019 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
5020 $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
5021 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
5022 }
5023 }
5024 $this->country_id = $country_id;
5025 $this->country_code = $country_code;
5026 $this->country = $country_label;
5027 if (is_object($langs)) {
5028 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
5029 }
5030
5031 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
5032 // We define state_id, state_code and state
5033 $state_id = 0;
5034 $state_code = '';
5035 $state_label = '';
5036 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
5037 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
5038 $state_id = (int) $tmp[0];
5039 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
5040 $state_code = $tmp[1];
5041 $state_label = $tmp[2];
5042 } else { // For backward compatibility
5043 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);
5044 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
5045 $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
5046 $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
5047 }
5048 }
5049 $this->state_id = $state_id;
5050 $this->state_code = $state_code;
5051 $this->state = $state_label;
5052 if (is_object($langs)) {
5053 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
5054 }
5055
5056 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
5057 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
5058 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
5059 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
5060
5061 // Social networks
5062 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
5063 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
5064 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
5065 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
5066 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
5067 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
5068 $this->socialnetworks = array();
5069 if (!empty($facebook_url)) {
5070 $this->socialnetworks['facebook'] = $facebook_url;
5071 }
5072 if (!empty($twitter_url)) {
5073 $this->socialnetworks['twitter'] = $twitter_url;
5074 }
5075 if (!empty($linkedin_url)) {
5076 $this->socialnetworks['linkedin'] = $linkedin_url;
5077 }
5078 if (!empty($instagram_url)) {
5079 $this->socialnetworks['instagram'] = $instagram_url;
5080 }
5081 if (!empty($youtube_url)) {
5082 $this->socialnetworks['youtube'] = $youtube_url;
5083 }
5084 if (!empty($github_url)) {
5085 $this->socialnetworks['github'] = $github_url;
5086 }
5087
5088 // Id prof generic
5089 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
5090 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
5091 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
5092 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
5093 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
5094 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
5095 $this->idprof7 = getDolGlobalString('MAIN_INFO_PROFID7');
5096 $this->idprof8 = getDolGlobalString('MAIN_INFO_PROFID8');
5097 $this->idprof9 = getDolGlobalString('MAIN_INFO_PROFID9');
5098 $this->idprof10 = getDolGlobalString('MAIN_INFO_PROFID10');
5099 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
5100 $this->euid = getDolGlobalString('MAIN_INFO_EUID');
5101 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
5102 $this->capital = is_numeric(price2num(getDolGlobalString('MAIN_INFO_CAPITAL'))) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : null;
5103 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
5104 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
5105 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
5106 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
5107 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
5108 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
5109 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
5110 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
5111 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
5112
5113 // Define if company use vat or not
5114 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
5115
5116 // Define if company use local taxes
5117 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
5118 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
5119
5120 $this->termsofsale = getDolGlobalString('MAIN_INFO_SOCIETE_TERMSOFSALE');
5121 }
5122
5130 public function initAsSpecimen()
5131 {
5132 $now = dol_now();
5133
5134 // Initialize parameters
5135 $this->id = 0;
5136 $this->entity = 1;
5137 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
5138 $this->ref_ext = 'Ref ext';
5139 $this->specimen = 1;
5140 $this->address = '21 jump street';
5141 $this->zip = '99999';
5142 $this->town = 'MyTown';
5143 $this->state_id = 1;
5144 $this->state_code = 'AA';
5145 $this->state = 'MyState';
5146 $this->country_id = 1;
5147 $this->country_code = 'FR';
5148 $this->email = 'specimen@specimen.com';
5149 $this->socialnetworks = array(
5150 'skype' => 'skypepseudo',
5151 'twitter' => 'twitterpseudo',
5152 'facebook' => 'facebookpseudo',
5153 'linkedin' => 'linkedinpseudo',
5154 );
5155 $this->url = 'https://www.specimen.com';
5156
5157 $this->phone = '0909090901';
5158 $this->phone_mobile = '0909090901';
5159 $this->fax = '0909090909';
5160
5161 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
5162 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
5163 $this->typent_code = 'TE_OTHER';
5164 $this->capital = 10000;
5165 $this->client = 1;
5166 $this->prospect = 1;
5167 $this->fournisseur = 1;
5168 $this->tva_assuj = 1;
5169 //$this->tva_intra = 'EU1234567';
5170 $this->tva_intra = 'FR1234567';
5171 $this->note_public = 'This is a comment (public)';
5172 $this->note_private = 'This is a comment (private)';
5173
5174 $this->idprof1 = 'idprof1';
5175 $this->idprof2 = 'idprof2';
5176 $this->idprof3 = 'idprof3';
5177 $this->idprof4 = 'idprof4';
5178 $this->idprof5 = 'idprof5';
5179 $this->idprof6 = 'idprof6';
5180
5181 $this->euid = 'FR-RCSXXXX-idprof1';
5182
5183 return 1;
5184 }
5185
5194 public function useLocalTax($localTaxNum = 0, $mode = 0, $thirdparty = null)
5195 {
5196 if ($mode == 1 && $thirdparty instanceof Societe) {
5197 if ($localTaxNum == -1) {
5198 return array(1 => ($thirdparty->localtax1_assuj ? true : false), 2 => ($thirdparty->localtax2_assuj ? true : false));
5199 } elseif ($localTaxNum == 1) {
5200 return $thirdparty->localtax1_assuj ? true : false;
5201 } elseif ($localTaxNum == 2) {
5202 return $thirdparty->localtax2_assuj ? true : false;
5203 }
5204 return false;
5205 } else {
5206 $sql = "SELECT t.localtax1, t.localtax2";
5207 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
5208 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5209 $sql .= " AND t.active = 1";
5210 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
5211 if (empty($localTaxNum) || $localTaxNum == -1) {
5212 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
5213 } elseif ($localTaxNum == 1) {
5214 $sql .= " AND t.localtax1_type <> '0'";
5215 } elseif ($localTaxNum == 2) {
5216 $sql .= " AND t.localtax2_type <> '0'";
5217 }
5218
5219 $resql = $this->db->query($sql);
5220 if ($resql) {
5221 if ($localTaxNum == -1) {
5222 $obj = $this->db->fetch_object($resql);
5223 if ($obj) {
5224 return array(1 => ($obj->localtax1 ? true : false), 2 => ($obj->localtax2 ? true : false));
5225 }
5226 return array(1 => false, 2 => false);
5227 } else {
5228 return ($this->db->num_rows($resql) > 0);
5229 }
5230 } else {
5231 return false;
5232 }
5233 }
5234 }
5235
5241 public function useNPR()
5242 {
5243 $sql = "SELECT t.rowid";
5244 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
5245 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5246 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
5247 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
5248
5249 dol_syslog("useNPR", LOG_DEBUG);
5250 $resql = $this->db->query($sql);
5251 if ($resql) {
5252 return ($this->db->num_rows($resql) > 0);
5253 } else {
5254 return false;
5255 }
5256 }
5257
5264 public function useRevenueStamp()
5265 {
5266 $sql = "SELECT COUNT(*) as nb";
5267 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
5268 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
5269 $sql .= " AND r.active = 1";
5270
5271 dol_syslog("useRevenueStamp", LOG_DEBUG);
5272 $resql = $this->db->query($sql);
5273 if ($resql) {
5274 $obj = $this->db->fetch_object($resql);
5275 return ($obj->nb > 0);
5276 } else {
5277 $this->error = $this->db->lasterror();
5278 return false;
5279 }
5280 }
5281
5287 public function getLibProspLevel()
5288 {
5289 return $this->LibProspLevel($this->fk_prospectlevel);
5290 }
5291
5292 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5299 public function LibProspLevel($fk_prospectlevel)
5300 {
5301 // phpcs:enable
5302 global $langs;
5303
5304 $label = '';
5305 if ($fk_prospectlevel != '') {
5306 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
5307 // If label is not found in language file, we get label from cache/database
5308 if ($label == "ProspectLevel".$fk_prospectlevel) {
5309 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
5310 }
5311 }
5312
5313 return $label;
5314 }
5315
5323 public function getLibProspCommStatut($mode = 0, $label = '')
5324 {
5325 return $this->LibProspCommStatut((int) $this->stcomm_id, $mode, $label, $this->stcomm_picto);
5326 }
5327
5328 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5342 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
5343 {
5344 // phpcs:enable
5345 global $langs;
5346
5347 $langs->load('customers');
5348
5349 if ($mode == 2) {
5350 if ($status == '-1' || $status == 'ST_NO') {
5351 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5352 } elseif ($status == '0' || $status == 'ST_NEVER') {
5353 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5354 } elseif ($status == '1' || $status == 'ST_TODO') {
5355 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5356 } elseif ($status == '2' || $status == 'ST_PEND') {
5357 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5358 } elseif ($status == '3' || $status == 'ST_DONE') {
5359 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5360 } else {
5361 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);
5362 }
5363 } elseif ($mode == 3) {
5364 if ($status == '-1' || $status == 'ST_NO') {
5365 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
5366 } elseif ($status == '0' || $status == 'ST_NEVER') {
5367 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
5368 } elseif ($status == '1' || $status == 'ST_TODO') {
5369 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
5370 } elseif ($status == '2' || $status == 'ST_PEND') {
5371 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
5372 } elseif ($status == '3' || $status == 'ST_DONE') {
5373 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
5374 } else {
5375 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
5376 }
5377 } elseif ($mode == 4) {
5378 if ($status == '-1' || $status == 'ST_NO') {
5379 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
5380 } elseif ($status == '0' || $status == 'ST_NEVER') {
5381 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
5382 } elseif ($status == '1' || $status == 'ST_TODO') {
5383 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
5384 } elseif ($status == '2' || $status == 'ST_PEND') {
5385 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
5386 } elseif ($status == '3' || $status == 'ST_DONE') {
5387 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
5388 } else {
5389 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);
5390 }
5391 }
5392
5393 return "Error, mode/status not found";
5394 }
5395
5402 public function getOutstandingProposals($mode = 'customer')
5403 {
5404 global $hookmanager;
5405 $table = 'propal';
5406 if ($mode == 'supplier') {
5407 $table = 'supplier_proposal';
5408 }
5409
5410 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5411 $sql .= " WHERE fk_soc = ".((int) $this->id);
5412 if ($mode == 'supplier') {
5413 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
5414 } else {
5415 $sql .= " AND entity IN (".getEntity('propal').")";
5416 }
5417
5418 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
5419
5420 // Add where from hooks
5421 $parameters = array('mode' => $mode, 'table' => $table);
5422 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5423 $sql .= $hookmanager->resPrint;
5424
5425 $resql = $this->db->query($sql);
5426 if ($resql) {
5427 $outstandingOpened = 0;
5428 $outstandingTotal = 0;
5429 $outstandingTotalIncTax = 0;
5430 $arrayofref = array();
5431 while ($obj = $this->db->fetch_object($resql)) {
5432 $arrayofref[$obj->rowid] = $obj->ref;
5433 $outstandingTotal += $obj->total_ht;
5434 $outstandingTotalIncTax += $obj->total_ttc;
5435 if ($obj->status != 0) {
5436 // Not a draft
5437 $outstandingOpened += $obj->total_ttc;
5438 }
5439 }
5440 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5441 } else {
5442 return array();
5443 }
5444 }
5445
5452 public function getOutstandingOrders($mode = 'customer')
5453 {
5454 global $hookmanager;
5455 $table = 'commande';
5456 if ($mode == 'supplier') {
5457 $table = 'commande_fournisseur';
5458 }
5459
5460 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
5461 $sql .= " WHERE fk_soc = ".((int) $this->id);
5462 if ($mode == 'supplier') {
5463 $sql .= " AND entity IN (".getEntity('supplier_order').")";
5464 } else {
5465 $sql .= " AND entity IN (".getEntity('commande').")";
5466 }
5467
5468 dol_syslog("getOutstandingOrders", LOG_DEBUG);
5469 // Add where from hooks
5470 $parameters = array('mode' => $mode, 'table' => $table);
5471 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5472 $sql .= $hookmanager->resPrint;
5473 $resql = $this->db->query($sql);
5474 if ($resql) {
5475 $outstandingOpened = 0;
5476 $outstandingTotal = 0;
5477 $outstandingTotalIncTax = 0;
5478 $arrayofref = array();
5479 while ($obj = $this->db->fetch_object($resql)) {
5480 $arrayofref[$obj->rowid] = $obj->ref;
5481 $outstandingTotal += $obj->total_ht;
5482 $outstandingTotalIncTax += $obj->total_ttc;
5483 if ($obj->status != 0) {
5484 // Not a draft
5485 $outstandingOpened += $obj->total_ttc;
5486 }
5487 }
5488 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
5489 } else {
5490 return array();
5491 }
5492 }
5493
5502 public function getInvoiceRemainToPayInOutstanding($invoice, $mode = 'customer', $late = 0)
5503 {
5504 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5505
5506 if ($invoice->paye != 0
5507 || $invoice->statut == $invoice::STATUS_DRAFT
5508 || $invoice->statut == $invoice::STATUS_ABANDONED
5509 || $invoice->statut == $invoice::STATUS_CLOSED) {
5510 return 0;
5511 }
5512
5513 $paiement = $invoice->getSommePaiement();
5514 $creditnotes = $invoice->getSumCreditNotesUsed();
5515 $deposits = $invoice->getSumDepositsUsed();
5516
5517 $remaintopay = (float) price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
5518
5519 if ($mode == 'supplier') {
5520 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5521 if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE && $invoice->isCreditNoteUsed()) {
5522 $remaintopay -= (float) $invoice->getSumFromThisCreditNotesNotUsed();
5523 }
5524 }
5525
5526 if ($remaintopay <= 0) {
5527 return 0;
5528 }
5529
5530 if (!empty($late)) {
5531 $today = dol_get_first_hour(dol_now('tzuser'));
5532 if (empty($invoice->date_lim_reglement) || $invoice->date_lim_reglement >= $today) {
5533 return 0;
5534 }
5535 }
5536
5537 return $remaintopay;
5538 }
5539
5547 public function getOutstandingBills($mode = 'customer', $late = 0)
5548 {
5549 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5550
5551 $table = 'facture';
5552 if ($mode == 'supplier') {
5553 $table = 'facture_fourn';
5554 }
5555
5556 /* Accurate value of remain to pay is to sum remaintopay for each invoice
5557 $paiement = $invoice->getSommePaiement();
5558 $creditnotes=$invoice->getSumCreditNotesUsed();
5559 $deposits=$invoice->getSumDepositsUsed();
5560 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
5561 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
5562 */
5563 $today = dol_get_first_hour(dol_now('tzuser')); // Returns today at 00:00 in the user's time zone
5564
5565 if ($mode == 'supplier') {
5566 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5567 $tmpobject = new FactureFournisseur($this->db);
5568 } else {
5569 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
5570 $tmpobject = new Facture($this->db);
5571 }
5572
5573 // With MAIN_PERF_CALCULATE_OUTSTANDING_BILLS_BY_DB, the amount already paid and the credit notes and deposits
5574 // used are read for each opened invoice with subqueries of this request (same requests as getSommePaiement(),
5575 // getSumCreditNotesUsed() and getSumDepositsUsed()), instead of 3 requests per opened invoice: a thirdparty
5576 // with thousands of opened invoices made the customer card run tens of thousands of requests. The option is
5577 // off by default, so that the business rules of these methods stay on the PHP side.
5578 $calculatebydb = getDolGlobalInt('MAIN_PERF_CALCULATE_OUTSTANDING_BILLS_BY_DB');
5579
5580 $sql = "SELECT f.rowid, f.ref, f.total_ht, f.total_ttc, f.paye, f.type, f.fk_statut as status, f.close_code";
5581 if ($calculatebydb) {
5582 $sqlopened = "f.paye = 0 AND f.fk_statut NOT IN (".$this->db->sanitize($tmpobject::STATUS_DRAFT.", ".$tmpobject::STATUS_ABANDONED.", ".$tmpobject::STATUS_CLOSED).")";
5583 if ($mode == 'supplier') {
5584 $sql .= ", CASE WHEN (".$sqlopened.") THEN (SELECT SUM(pf.amount) FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf WHERE pf.fk_facturefourn = f.rowid) ELSE 0 END as amount_paid";
5585 $sql .= ", CASE WHEN (".$sqlopened.") THEN (SELECT SUM(rc.amount_ttc) FROM ".MAIN_DB_PREFIX."societe_remise_except as rc, ".MAIN_DB_PREFIX."facture_fourn as fs";
5586 $sql .= " WHERE rc.fk_invoice_supplier_source = fs.rowid AND rc.fk_invoice_supplier = f.rowid AND fs.type IN (".$this->db->sanitize($tmpobject::TYPE_STANDARD.", ".$tmpobject::TYPE_CREDIT_NOTE).")) ELSE 0 END as amount_creditnotes";
5587 $sql .= ", CASE WHEN (".$sqlopened.") THEN (SELECT SUM(rc.amount_ttc) FROM ".MAIN_DB_PREFIX."societe_remise_except as rc, ".MAIN_DB_PREFIX."facture_fourn as fs";
5588 $sql .= " WHERE rc.fk_invoice_supplier_source = fs.rowid AND rc.fk_invoice_supplier = f.rowid AND fs.type = ".((int) $tmpobject::TYPE_DEPOSIT).") ELSE 0 END as amount_deposits";
5589 } else {
5590 $sql .= ", CASE WHEN (".$sqlopened.") THEN (SELECT SUM(pf.amount) FROM ".MAIN_DB_PREFIX."paiement_facture as pf WHERE pf.fk_facture = f.rowid) ELSE 0 END as amount_paid";
5591 $sql .= ", CASE WHEN (".$sqlopened.") THEN (SELECT SUM(rc.amount_ttc) FROM ".MAIN_DB_PREFIX."societe_remise_except as rc, ".MAIN_DB_PREFIX."facture as fs";
5592 $sql .= " WHERE rc.fk_facture_source = fs.rowid AND rc.fk_facture = f.rowid AND fs.type IN (".$this->db->sanitize($tmpobject::TYPE_STANDARD.", ".$tmpobject::TYPE_CREDIT_NOTE.", ".$tmpobject::TYPE_SITUATION).")) ELSE 0 END as amount_creditnotes";
5593 $sql .= ", CASE WHEN (".$sqlopened.") THEN (SELECT SUM(rc.amount_ttc) FROM ".MAIN_DB_PREFIX."societe_remise_except as rc, ".MAIN_DB_PREFIX."facture as fs";
5594 $sql .= " WHERE rc.fk_facture_source = fs.rowid AND rc.fk_facture = f.rowid AND fs.type = ".((int) $tmpobject::TYPE_DEPOSIT).") ELSE 0 END as amount_deposits";
5595 }
5596 }
5597 $sql .= " FROM ".MAIN_DB_PREFIX.$table." as f";
5598 $sql .= " WHERE f.fk_soc = ".((int) $this->id);
5599 if (!empty($late)) {
5600 $sql .= " AND date_lim_reglement < '".$this->db->idate($today)."'";
5601 }
5602 if ($mode == 'supplier') {
5603 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
5604 } else {
5605 $sql .= " AND entity IN (".getEntity('invoice').")";
5606 }
5607
5608 dol_syslog("getOutstandingBills", LOG_DEBUG);
5609 $resql = $this->db->query($sql);
5610 if ($resql) {
5611 $outstandingOpened = 0;
5612 $outstandingTotal = 0;
5613 $outstandingTotalIncTax = 0;
5614 $arrayofref = array();
5615 $arrayofrefopened = array();
5616 while ($obj = $this->db->fetch_object($resql)) {
5617 $arrayofref[$obj->rowid] = $obj->ref;
5618 $tmpobject->id = $obj->rowid;
5619
5620 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5621 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5622 ) {
5623 $outstandingTotal += $obj->total_ht;
5624 $outstandingTotalIncTax += $obj->total_ttc;
5625 }
5626
5627 $remaintopay = 0;
5628
5629 if ($obj->paye == 0
5630 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5631 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5632 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5633 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5634 if ($calculatebydb) {
5635 $paiement = (float) $obj->amount_paid;
5636 $creditnotes = $obj->amount_creditnotes;
5637 $deposits = $obj->amount_deposits;
5638 } else {
5639 $paiement = $tmpobject->getSommePaiement();
5640 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5641 $deposits = $tmpobject->getSumDepositsUsed();
5642 }
5643
5644 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5645 $outstandingOpened += $remaintopay;
5646 }
5647
5648 //if credit note is converted but not used
5649 // TODO Do this also for customer ?
5650 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5651 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5652 $remaintopay -= $remainingcreditnote;
5653 $outstandingOpened -= $remainingcreditnote;
5654 }
5655
5656 if ($remaintopay) {
5657 $arrayofrefopened[$obj->rowid] = $obj->ref;
5658 }
5659 }
5660 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'amount incl taxes' > 0
5661 } else {
5662 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5663 return array();
5664 }
5665 }
5666
5673 public function getLibCustProspStatut()
5674 {
5675 return $this->LibCustProspStatut($this->client);
5676 }
5677
5678 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5685 public function LibCustProspStatut($status)
5686 {
5687 // phpcs:enable
5688 global $langs;
5689 $langs->load('companies');
5690
5691 if ($status == 0) {
5692 return $langs->trans("NorProspectNorCustomer");
5693 } elseif ($status == 1) {
5694 return $langs->trans("Customer");
5695 } elseif ($status == 2) {
5696 return $langs->trans("Prospect");
5697 } elseif ($status == 3) {
5698 return $langs->trans("ProspectCustomer");
5699 }
5700
5701 return '';
5702 }
5703
5704
5711 public function calculateVATNumberFromProperties($thirdparty)
5712 {
5713 if ($thirdparty->country_code == 'FR' && empty($thirdparty->tva_intra) && !empty($thirdparty->tva_assuj)) {
5714 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
5715
5716 $siren = preg_replace('/\s+/', '', (string) $thirdparty->idprof1);
5717 $siret = preg_replace('/\s+/', '', (string) $thirdparty->idprof2);
5718 if (!isValidSiren($siren)) {
5719 if (!isValidSiret($siret)) {
5720 return '';
5721 }
5722
5723 $siren = substr($siret, 0, 9);
5724 }
5725 if (!empty($siren)) {
5726 // [FR + key code + SIREN number ]
5727 // Key VAT = [12 + 3 * (SIREN modulo 97)] modulo 97
5728 $cle = (12 + 3 * (((int) $siren) % 97)) % 97;
5729 $tva_intra = 'FR' . str_pad((string) $cle, 2, '0', STR_PAD_LEFT) . $siren;
5730 }
5731 }
5732
5733 return $tva_intra ?? '';
5734 }
5735
5736
5748 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5749 {
5750 global $langs;
5751
5752 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5753 $modelpath = "core/modules/bank/doc/";
5754
5755 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5756 $companybankaccount = new CompanyBankAccount($this->db);
5757 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5758 if (!$result) {
5759 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5760 }
5761 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5762 $this->last_main_doc = $companybankaccount->last_main_doc;
5763 } else {
5764 // Set the model to the name of the model to be used
5765 if (!dol_strlen($modele)) {
5766 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5767 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5768 } else {
5769 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5770 return 0;
5771 }
5772 }
5773
5774 if (!isset($this->bank_account)) {
5775 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5776 $bac = new CompanyBankAccount($this->db);
5777 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5778 $result = $bac->fetch(0, '', $this->id);
5779 if ($result > 0) {
5780 $this->bank_account = $bac;
5781 } else {
5782 $this->bank_account = '';
5783 }
5784 }
5785
5786 $modelpath = "core/modules/societe/doc/";
5787
5788 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5789 }
5790
5791 return $result;
5792 }
5793
5794
5807 public function setCategories($categories, $type_categ, $remove_existing = true)
5808 {
5809 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5810
5811 // Decode type
5812 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5813 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Nothing done.', LOG_ERR);
5814 return -1;
5815 }
5816
5817 return parent::setCategoriesCommon($categories, $type_categ, $remove_existing);
5818 }
5819
5827 public function setSalesRep($salesrep, $onlyAdd = false)
5828 {
5829 global $user;
5830
5831 // Handle single user
5832 if (!is_array($salesrep)) {
5833 $salesrep = array($salesrep);
5834 }
5835
5836 $to_del = array(); // Nothing to delete
5837 $to_add = $salesrep;
5838 if ($onlyAdd === false) {
5839 // Get current users
5840 $existing = $this->getSalesRepresentatives($user, 1);
5841
5842 // Diff
5843 if (is_array($existing)) {
5844 $to_del = array_diff($existing, $salesrep);
5845 $to_add = array_diff($salesrep, $existing);
5846 }
5847 }
5848
5849 $error = 0;
5850
5851 // Process
5852 foreach ($to_del as $del) {
5853 $this->del_commercial($user, $del);
5854 }
5855 foreach ($to_add as $add) {
5856 $result = $this->add_commercial($user, $add);
5857 if ($result < 0) {
5858 $error++;
5859 break;
5860 }
5861 }
5862
5863 return $error ? -1 : 1;
5864 }
5865
5872 public function setThirdpartyType($typent_id)
5873 {
5874 global $user;
5875
5876 dol_syslog(__METHOD__, LOG_DEBUG);
5877
5878 if ($this->id) {
5879 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5880
5881 if ($result > 0) {
5882 $this->typent_id = $typent_id;
5883 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5884 return 1;
5885 } else {
5886 return -1;
5887 }
5888 } else {
5889 return -1;
5890 }
5891 }
5892
5902 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5903 {
5904 if ($origin_id == $dest_id) {
5905 dol_syslog('Error: Try to merge a thirdparty into itself');
5906 return false;
5907 }
5908
5909 // 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.
5910 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5911 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5912 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5913 $sql .= ' SELECT fk_user ';
5914 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5915 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5916
5917 $resql = $dbs->query($sql);
5918 while ($obj = $dbs->fetch_object($resql)) {
5919 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5920 }
5921
5922 // 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.
5923 // Do not include llx_societe because it will be replaced later.
5924 $tables = array(
5925 'societe_account',
5926 'societe_commerciaux',
5927 'societe_prices',
5928 'societe_remise',
5929 'societe_remise_except',
5930 'societe_rib'
5931 );
5932
5933 // TODO When we merge societe_account, we may get 2 lines for the stripe account. Must fix this.
5934
5935 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5936 }
5937
5946 public function setAccountancyCode($type, $value)
5947 {
5948 global $user, $langs, $conf;
5949
5950 $this->db->begin();
5951
5952 if ($type == 'buy') {
5953 $field = 'accountancy_code_buy';
5954 } elseif ($type == 'sell') {
5955 $field = 'accountancy_code_sell';
5956 } else {
5957 return -1;
5958 }
5959
5960 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5961 $sql .= $field." = '".$this->db->escape($value)."'";
5962 $sql .= " WHERE rowid = ".((int) $this->id);
5963
5964 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5965 $resql = $this->db->query($sql);
5966
5967 if ($resql) {
5968 // Call triggers
5969 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5970 $interface = new Interfaces($this->db);
5971 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5972 if ($result < 0) {
5973 $this->errors = $interface->errors;
5974 $this->db->rollback();
5975 return -1;
5976 }
5977 // End call triggers
5978
5979 $this->$field = $value;
5980
5981 $this->db->commit();
5982 return 1;
5983 } else {
5984 $this->error = $this->db->lasterror();
5985 $this->db->rollback();
5986 return -1;
5987 }
5988 }
5989
5996 public function fetchPartnerships($mode)
5997 {
5998 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5999
6000 $this->partnerships[] = array();
6001
6002 return 1;
6003 }
6004
6012 public function getKanbanView($option = '', $arraydata = array())
6013 {
6014 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
6015
6016 $out = '<div class="box-flex-item box-flex-grow-zero">';
6017 $out .= '<div class="info-box info-box-sm">';
6018 $out .= '<span class="info-box-icon bg-infobox-action">';
6019 if (!empty($this->logo) && class_exists('Form')) {
6020 $out .= Form::showphoto('societe', $this, 0, 40, 0, 'photokanban', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
6021 } else {
6022 $out .= img_picto('', $this->picto);
6023 }
6024 $out .= '</span>';
6025 $out .= '<div class="info-box-content">';
6026 $out .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">' . $this->getNomUrl(1);
6027 $out .= '</div>';
6028 if (!empty($this->phone)) {
6029 $out .= '<div class="inline-block valignmiddle">';
6030 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
6031 $out .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
6032 $out .= '</div>';
6033 }
6034 if (!empty($this->email)) {
6035 $out .= '<div class="inline-block valignmiddle">';
6036 $out .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
6037 $out .= '</div>';
6038 }
6039 if ($selected >= 0) {
6040 $out .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
6041 }
6042 if (!empty($this->code_client)) {
6043 $out .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
6044 }
6045 $out .= '<br><div class="info-box-status">' . $this->getLibStatut(3) . '</div>';
6046 $out .= '</div>'; // end info-box-content
6047 $out .= '</div>';
6048 $out .= '</div>';
6049
6050 return $out;
6051 }
6052
6062 public function getContacts($list = 0, $code = '', $element = '', $status = -1)
6063 {
6064 // phpcs:enable
6065 global $langs;
6066
6067 $tab = array();
6068
6069 $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
6070 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
6071 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
6072 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
6073 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
6074 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
6075 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
6076 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
6077 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
6078
6079 // Add status filter if requested
6080 if ($status >= 0) {
6081 $sql .= " AND t.statut = " . ((int) $status);
6082 }
6083 if (!empty($element)) {
6084 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
6085 }
6086 if ($code) {
6087 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
6088 }
6089 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
6090 $sql .= " AND tc.source = 'external'";
6091 $sql .= " AND tc.active = 1";
6092
6093 $sql .= " ORDER BY t.lastname ASC";
6094
6095 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
6096 $resql = $this->db->query($sql);
6097 if ($resql) {
6098 $num = $this->db->num_rows($resql);
6099 $i = 0;
6100 while ($i < $num) {
6101 $obj = $this->db->fetch_object($resql);
6102
6103 if (!$list) {
6104 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
6105 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
6106 $tab[$obj->id] = array(
6107 'source' => $obj->source,
6108 'socid' => (int) $obj->socid,
6109 'id' => (int) $obj->id,
6110 'nom' => $obj->lastname, // For backward compatibility
6111 'civility' => $obj->civility,
6112 'lastname' => $obj->lastname,
6113 'firstname' => $obj->firstname,
6114 'email' => $obj->email,
6115 'login' => (empty($obj->login) ? '' : $obj->login),
6116 'photo' => (empty($obj->photo) ? '' : $obj->photo),
6117 'statuscontact' => $obj->statuscontact,
6118 'rowid' => (int) $obj->rowid,
6119 'code' => $obj->code,
6120 'element' => $obj->element,
6121 'libelle' => $label_type,
6122 'status' => $obj->statuslink,
6123 'fk_c_type_contact' => (int) $obj->fk_c_type_contact
6124 );
6125 } else {
6126 $tab[$obj->id] = (int) $obj->id;
6127 }
6128 $i++;
6129 }
6130
6131 return $tab;
6132 } else {
6133 $this->error = $this->db->lasterror();
6134 dol_print_error($this->db);
6135 return -1;
6136 }
6137 }
6138
6149 public function mergeCompany($soc_origin_id)
6150 {
6151 global $conf, $langs, $hookmanager, $user, $action;
6152
6153 $error = 0;
6154 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
6155
6156 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
6157
6158 if ($soc_origin->fetch($soc_origin_id) < 1) {
6159 $this->error = $langs->trans('ErrorRecordNotFound');
6160 $error++;
6161 }
6162
6163 if (!$error) {
6164 $this->db->begin();
6165
6166 // Recopy some data
6167 $this->client |= $soc_origin->client;
6168 $this->fournisseur |= $soc_origin->fournisseur;
6169 $listofproperties = array(
6170 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
6171 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
6172 'tva_intra', 'euid', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
6173 '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',
6174 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
6175 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
6176 );
6177 foreach ($listofproperties as $property) {
6178 if (empty($this->$property)) {
6179 $this->$property = $soc_origin->$property;
6180 }
6181 }
6182
6183 if ($this->typent_id == -1) {
6184 $this->typent_id = $soc_origin->typent_id;
6185 }
6186
6187 // Concat some data
6188 $listofproperties = array(
6189 'note_public', 'note_private'
6190 );
6191 foreach ($listofproperties as $property) {
6192 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
6193 }
6194
6195 // Merge extrafields
6196 if (is_array($soc_origin->array_options)) {
6197 foreach ($soc_origin->array_options as $key => $val) {
6198 if (empty($this->array_options[$key])) {
6199 $this->array_options[$key] = $val;
6200 }
6201 }
6202 }
6203
6204 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
6205 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
6206 $this->name_bis = $this->name;
6207 }
6208
6209 // Merge categories
6210 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
6211 $static_cat = new Categorie($this->db);
6212
6213 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
6214 $custcats = $static_cat->containing($this->id, 'customer', 'id');
6215 $custcats = array_merge($custcats, $custcats_ori);
6216 $this->setCategories($custcats, 'customer');
6217
6218 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
6219 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
6220 $suppcats = array_merge($suppcats, $suppcats_ori);
6221 $this->setCategories($suppcats, 'supplier');
6222
6223 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
6224 if ($soc_origin->code_client == $this->code_client
6225 || $soc_origin->code_fournisseur == $this->code_fournisseur
6226 || $soc_origin->barcode == $this->barcode) {
6227 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
6228 $soc_origin->code_client = '';
6229 $soc_origin->code_fournisseur = '';
6230 $soc_origin->barcode = '';
6231 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
6232 }
6233
6234 // Children companies
6235 if (!getDolGlobalString('SOCIETE_DISABLE_PARENTCOMPANY')) {
6236 // Children
6237 $children_ori = $this->getChildrenForCompany($soc_origin->id);
6238 if (count($children_ori)) {
6239 foreach ($children_ori as $child_id) {
6240 $child = new Societe($this->db);
6241 $child->id = $child_id;
6242 $child->setParent($this->id);
6243 }
6244 }
6245 }
6246
6247 // Update
6248 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
6249
6250 if ($result < 0) {
6251 $error++;
6252 }
6253
6254 // Move links
6255 if (!$error) {
6256 $objects = array(
6257 'Adherent' => '/adherents/class/adherent.class.php',
6258 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
6259 'ActionComm' => '/comm/action/class/actioncomm.class.php',
6260 'Propal' => '/comm/propal/class/propal.class.php',
6261 'Commande' => '/commande/class/commande.class.php',
6262 'Facture' => '/compta/facture/class/facture.class.php',
6263 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
6264 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
6265 'Contact' => '/contact/class/contact.class.php',
6266 'Contrat' => '/contrat/class/contrat.class.php',
6267 'Expedition' => '/expedition/class/expedition.class.php',
6268 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
6269 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
6270 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
6271 'Reception' => '/reception/class/reception.class.php',
6272 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
6273 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
6274 'Product' => '/product/class/product.class.php',
6275 //'ProductThirparty' => '...', // for llx_product_thirdparty
6276 'Project' => '/projet/class/project.class.php',
6277 'User' => '/user/class/user.class.php',
6278 'Account' => '/compta/bank/class/account.class.php',
6279 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
6280 'Societe' => '/societe/class/societe.class.php',
6281 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
6282 );
6283 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'delivery')) {
6284 $objects['Delivery'] = '/delivery/class/delivery.class.php';
6285 }
6286 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'mrp_mo')) {
6287 $objects['Mo'] = '/mrp/class/mo.class.php';
6288 }
6289 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'don')) {
6290 $objects['Don'] = '/don/class/don.class.php';
6291 }
6292 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'partnership')) {
6293 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
6294 }
6295 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'fichinter')) {
6296 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
6297 }
6298 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'ticket')) {
6299 $objects['Ticket'] = '/ticket/class/ticket.class.php';
6300 }
6301
6302 //First, all core objects must update their tables
6303 foreach ($objects as $object_name => $object_file) {
6304 /* $object_file is never an array -> code commented
6305 if (is_array($object_file)) {
6306 if (empty($object_file['enabled'])) {
6307 continue;
6308 }
6309 $object_file = $object_file['file'];
6310 }
6311 */
6312
6313 require_once DOL_DOCUMENT_ROOT.$object_file;
6314
6315 if (!$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
6316 $error++;
6317 $this->error = $this->db->lasterror();
6318 break;
6319 }
6320 }
6321 }
6322
6323 // External modules should update their ones too
6324 if (!$error) {
6325 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
6326 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
6327
6328 if ($reshook < 0) {
6329 $this->error = $hookmanager->error;
6330 $this->errors = $hookmanager->errors;
6331 $error++;
6332 }
6333 }
6334
6335
6336 if (!$error) {
6337 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
6338
6339 // Call trigger
6340 $result = $this->call_trigger('COMPANY_MODIFY', $user);
6341 if ($result < 0) {
6342 $error++;
6343 }
6344 // End call triggers
6345 }
6346
6347 if (!$error) {
6348 // We finally remove the old thirdparty
6349 if ($soc_origin->delete($soc_origin->id, $user, 1, 1) <= 0) {
6350 $this->error = $soc_origin->error;
6351 $this->errors = $soc_origin->errors;
6352 $error++;
6353 }
6354 }
6355
6356
6357 if (!$error) {
6358 // TODO Move this into this->mergeCompanyFiles() like done by mergeContactFiles() for contact.class.php
6359
6360 // Move files from the dir of the third party to delete into the dir of the third party to keep
6361 if (!empty($conf->societe->multidir_output[$this->entity])) {
6362 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
6363 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
6364
6365 if (dol_is_dir($srcdir)) {
6366 $failed = array();
6367 $dirlist = dol_dir_list($srcdir, 'files', 1);
6368 foreach ($dirlist as $filetomove) {
6369 $destfile = $destdir.'/'.$filetomove['relativename'];
6370 // dol_move() does not create the target directory, and the target contact usually has
6371 // none yet, so it has to be created for every level of the source tree
6372 dol_mkdir(dirname($destfile));
6373 if (!dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1)) {
6374 $failed[] = $filetomove['relativename'];
6375 }
6376 }
6377
6378 if (!empty($failed)) {
6379 dol_syslog(__METHOD__.' Failed to move '.count($failed).' file(s) from '.$srcdir, LOG_ERR);
6380 // The merge itself is committed, so this is reported as a warning and not as a failure
6381 $this->warnings[] = $langs->trans('WarningMergeFilesNotMoved', implode(', ', $failed));
6382 }
6383 }
6384 }
6385 }
6386
6387 if (!$error) {
6388 $this->db->commit();
6389 return 0;
6390 } else {
6391 $langs->load("errors");
6392 $this->error = $langs->trans('ErrorsThirdpartyMerge').' '.$this->error;
6393 $this->db->rollback();
6394 return -1;
6395 }
6396 }
6397
6398 return -1;
6399 }
6400}
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage members of a foundation.
Class to manage withdrawal receipts.
Class to manage categories.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
setErrorsFromObject($object)
setErrorsFromObject
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
deleteExtraFields()
Delete all extra fields values for the current object.
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra languages values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Class to manage bank accounts description of third parties.
Class to stock current configuration.
Class to manage contact/addresses.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage suppliers invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoices.
Class to manage generation of HTML components Only common components must be here.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0, $usesharelinkifavailable=0)
Return HTML code to output a photo.
Class to manage triggers.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage third parties objects (customers, suppliers, prospects...)
setParent($id)
Define parent company of current company.
getInvoiceRemainToPayInOutstanding($invoice, $mode='customer', $late=0)
Remain to pay for one invoice if it counts in getOutstandingBills() "opened" (same rules as tiles).
getLibProspLevel()
Return prostect level.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
setAsCustomer()
Define third party as a customer.
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
contact_get_property($rowid, $mode)
Return property of contact from its id.
check_codeclient()
Check customer code.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
isInSEPA()
Return if a company is inside the SEPA zone (Single Euro Payment Area)
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
get_all_rib()
Return Array of RIB.
get_codecompta($type)
Assigns a accounting code from the accounting code module.
__construct($db)
Constructor.
del_commercial(User $user, $commid)
Add link to sales representative.
info($id)
Load information for tab info.
has_projects()
Indicates if the company has projects.
setThirdpartyType($typent_id)
Define third-party type of current company.
isACompany()
Check if third party is a company (Business) or an end user (Consumer)
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
useLocalTax($localTaxNum=0, $mode=0, $thirdparty=null)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
add_commercial(User $user, $commid)
Add link to sales representative.
LibStatut($status, $mode=0)
Return the label of a given status.
update($id, User $user, $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.
const PROSPECT
Third party type is a prospect.
setPaymentMethods($id)
Change the payments methods.
create(User $user, $notrigger=0)
Create third party in database.
set_as_client()
Define third party as a customer.
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysoc in most ca...
id_prof_check($idprof)
Check the validity of a professional identifier according to the properties (country) of the thirdpar...
id_prof_verifiable($idprof)
Returns if a profid should be verified to be unique.
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
getParentsForCompany($company_id, $parents=array())
Get parents for company.
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0, $price_base_type='HT')
Add a discount for third party.
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
getContacts($list=0, $code='', $element='', $status=-1)
Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for a...
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
const CUSTOMER
Third party type is a customer.
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Load a third party from database into memory.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
LoadSupplierCateg()
Load the list of provider categories.
getAvailableDiscounts($user=null, $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company.
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
findNearest($rowid=0, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0, $vatnumber='')
Search the thirdparty that match the most the provided parameters.
contact_array_objects()
Return the contact list of this company.
isInEEC()
Return if a company is inside the EEC (European Economic Community)
setCategories($categories, $type_categ, $remove_existing=true)
Sets object to supplied categories.
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
fetchPartnerships($mode)
Function to get partnerships array.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
mergeCompany($soc_origin_id)
Merge a company with current one, deleting the given company $soc_origin_id.
const NO_SUPPLIER
Third party supplier flag is not supplier.
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
setNoEmail($no_email, $unsubscribegroup='')
Set "blacklist" mailing status.
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
getOpenCreditNotesNotYetConvertedIntoDiscount($discount_type=0)
Return amount (with tax) of discounts currently available for a company, user or other criteria.
getChildrenForCompany($company_id)
Get children for company.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
getLibStatut($mode=0)
Return label of status (activity, closed)
const NO_CUSTOMER
Third party type is no customer.
calculateVATNumberFromProperties($thirdparty)
Calculate VAT intracommunity number for a thirdparty if missing, from the professional ID.
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
create_individual(User $user, $no_email=0, $tags=array(), $notrigger=0)
Create a contact/address from thirdparty.
getNoEmail()
get "blacklist" mailing status set no_email attribute to 1 or 0
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='', $morecss='valignmiddle', $addlinktonotes=0)
Return a link on thirdparty (with picto)
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
LibCustProspStatut($status)
Return the label of the customer/prospect status.
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
setPriceLevel($price_level, User $user)
Set the price level.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
deprecatedProperties()
Provide list of deprecated properties and replacements.
getTooltipContentArray($params)
getTooltipContentArray
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
getKanbanView($option='', $arraydata=array())
Return clickable link of object (with optional picto)
const SUPPLIER
Third party supplier flag is a supplier.
check_codefournisseur()
Check supplier code.
contact_array()
Return the contact list of this company.
initAsSpecimen()
Initialise an instance with random values.
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
setMysoc(Conf $conf)
Set properties with value into $conf.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
trait CommonSocialNetworks
Superclass for social networks.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
global $mysoc
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:686
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=null)
Move a file into another name.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
dol_now($mode='gmt')
Return date for now.
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=2, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
isValidSiren($siren, $lengthonly=0)
Check the syntax validity of a SIREN.
isValidProfIds($idprof, $thirdparty, $lenghtonly=0)
Check the validity of a professional identifier according to the properties (country) of the company ...
isValidSiret($siret, $lengthonly=0)
Check the syntax validity of a SIRET.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
div refaddress div address