dolibarr 21.0.0-beta
societe.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5 * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2013-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
12 * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16 * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17 * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18 * Copyright (C) 2019-2024 Frédéric France <frederic.france@free.fr>
19 * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20 * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
21 * Copyright (C) 2023-2024 Alexandre Janniaux <alexandre.janniaux@gmail.com>
22 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
23 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
24 *
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 3 of the License, or
28 * (at your option) any later version.
29 *
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
34 *
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <https://www.gnu.org/licenses/>.
37 */
38
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
48require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
49
50
54class Societe extends CommonObject
55{
56 use CommonIncoterm;
58 use CommonPeople;
59
63 public $module = 'societe';
64
68 public $element = 'societe';
69
73 public $table_element = 'societe';
74
78 public $fk_element = 'fk_soc';
79
83 public $fieldsforcombobox = 'nom,name_alias';
84
88 protected $childtables = array(
89 'supplier_proposal' => array('name' => 'SupplierProposal'),
90 'propal' => array('name' => 'Proposal'),
91 'commande' => array('name' => 'Order'),
92 'facture' => array('name' => 'Invoice'),
93 'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
94 'contrat' => array('name' => 'Contract'),
95 'fichinter' => array('name' => 'Fichinter'),
96 'facture_fourn' => array('name' => 'SupplierInvoice'),
97 'commande_fournisseur' => array('name' => 'SupplierOrder'),
98 'projet' => array('name' => 'Project'),
99 'expedition' => array('name' => 'Shipment'),
100 'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
101 );
102
107 protected $childtablesoncascade = array(
108 'societe_prices',
109 'product_fournisseur_price',
110 'product_customer_price_log',
111 'product_customer_price',
112 '@Contact:/contact/class/contact.class.php:fk_soc',
113 'adherent',
114 'societe_account',
115 'societe_rib',
116 'societe_remise',
117 'societe_remise_except',
118 'societe_commerciaux',
119 'categorie',
120 'notify',
121 'notify_def',
122 'actioncomm',
123 );
124
128 public $picto = 'company';
129
134 public $restrictiononfksoc = 1;
135
140 public $SupplierCategories = array();
141
146 public $prefixCustomerIsRequired;
147
177 public $fields = array(
178 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
179 'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
180 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
181 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
182 'nom' => array('type' => 'varchar(128)', 'length' => 128, 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1, 'csslist' => 'tdoverflowmax150'),
183 'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
184 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
185 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
186 'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
187 'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
188 'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
189 'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
190 'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
191 'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
192 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
193 'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
194 'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
195 'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
196 'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
197 'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
198 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
199 'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
200 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
201 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
202 'fk_typent' => array('type' => 'integer', 'label' => 'TypeOfCompany', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
203 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
204 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
205 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
206 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
207 'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
208 'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
209 'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
210 'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
211 'tva_intra' => array('type' => 'varchar(20)', 'label' => 'Tva intra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
212 'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
213 'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
214 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225),
215 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230),
216 'prefix_comm' => array('type' => 'varchar(5)', 'label' => 'Prefix comm', 'enabled' => "getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible' => -1, 'position' => 235),
217 'client' => array('type' => 'tinyint(4)', 'label' => 'Client', 'enabled' => 1, 'visible' => -1, 'position' => 240),
218 'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Fournisseur', 'enabled' => 1, 'visible' => -1, 'position' => 245),
219 'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
220 'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
221 'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
222 'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
223 'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
224 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
225 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
226 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
227 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
228 'mode_reglement' => array('type' => 'tinyint(4)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
229 'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
230 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
231 'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
232 'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
233 'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
234 'order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Order min amount', 'enabled' => 'isModEnabled("order") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible' => -1, 'position' => 315, 'isameasure' => 1),
235 'supplier_order_min_amount' => array('type' => 'double(24,8)', 'label' => 'Supplier order min amount', 'enabled' => 'isModEnabled("order") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible' => -1, 'position' => 320, 'isameasure' => 1),
236 'fk_shipping_method' => array('type' => 'integer', 'label' => 'Fk shipping method', 'enabled' => 1, 'visible' => -1, 'position' => 330),
237 'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'Tva assuj', 'enabled' => 1, 'visible' => -1, 'position' => 335),
238 'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax1 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 340),
239 'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'Localtax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
240 'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax2 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 350),
241 'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'Localtax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
242 'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
243 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
244 'price_level' => array('type' => 'integer', 'label' => 'Price level', 'enabled' => '$conf->global->PRODUIT_MULTIPRICES || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES") || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES")', 'visible' => -1, 'position' => 365),
245 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
246 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
247 'fk_barcode_type' => array('type' => 'integer', 'label' => 'Fk barcode type', 'enabled' => 1, 'visible' => -1, 'position' => 405),
248 'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
249 'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
250 'fk_incoterms' => array('type' => 'integer', 'label' => 'Fk incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 425),
251 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
252 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
253 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
254 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
255 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
256 'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
257 'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
258 'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
259 'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
260 'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
261 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
262 );
263
267 public $entity;
268
275 public $nom;
276
280 public $name;
281
286 public $name_alias;
287
291 public $particulier;
292
297 public $status = 1;
298
302 public $region_code;
303
307 public $region;
308
312 public $country_id;
313
319 public $departement_code;
320
326 public $departement;
327
333 public $pays;
334
339 public $phone;
344 public $phone_mobile;
349 public $fax;
350
355 public $email;
356
361 public $no_email;
362
368 public $skype;
369
375 public $twitter;
376
382 public $facebook;
383
389 public $linkedin;
390
395 public $url;
396
401 public $barcode;
402
403 // 6 professional id (usage depends on country)
404
409 public $idprof1;
410
416 public $siren;
417
418
423 public $idprof2;
424
430 public $siret;
431
436 public $idprof3;
437
443 public $ape;
444
449 public $idprof4;
450
455 public $idprof5;
456
461 public $idprof6;
462
467 public $idprof7;
468
473 public $idprof8;
474
479 public $idprof9;
480
485 public $idprof10;
486
491 public $socialobject;
492
496 public $prefix_comm;
497
501 public $tva_assuj = 1;
502
506 public $tva_intra;
507
511 public $vat_reverse_charge = 0;
512
513 // Local taxes
517 public $localtax1_assuj;
521 public $localtax1_value;
525 public $localtax2_assuj;
529 public $localtax2_value;
530
534 public $managers;
535
539 public $capital;
540
544 public $typent_id = 0;
548 public $typent_code;
552 public $effectif;
556 public $effectif_id = 0;
560 public $forme_juridique_code = 0;
565 public $forme_juridique;
566
570 public $remise_percent;
574 public $remise_supplier_percent;
575
579 public $mode_reglement_id;
583 public $cond_reglement_id;
587 public $deposit_percent;
591 public $mode_reglement_supplier_id;
595 public $cond_reglement_supplier_id;
599 public $transport_mode_supplier_id;
600
604 public $fk_prospectlevel;
605
609 public $name_bis;
610
616 public $user_modification;
617
623 public $user_creation;
624
629 public $client = 0;
630
635 public $prospect = 0;
636
641 public $fournisseur;
642
647 public $code_client;
648
653 public $code_fournisseur;
654
659 public $code_compta_client;
660
665 public $accountancy_code_customer_general;
666
671 public $accountancy_code_customer;
672
677 public $code_compta_fournisseur;
678
683 public $accountancy_code_supplier_general;
684
689 public $accountancy_code_supplier;
690
695 public $code_compta_product;
696
702 public $note;
703
708 public $note_private;
709
714 public $note_public;
715
720 public $stcomm_id;
721
726 public $stcomm_picto;
727
732 public $status_prospect_label;
733
738 public $price_level;
739
743 public $outstanding_limit;
744
748 public $order_min_amount;
749
753 public $supplier_order_min_amount;
754
759 public $commercial_id;
760
765 public $parent;
766
771 public $default_lang;
772
776 public $ref;
777
783 public $ref_ext;
784
788 public $ip;
789
796 public $import_key;
797
802 public $webservices_url;
803
808 public $webservices_key;
809
813 public $logo;
814
818 public $logo_small;
819
823 public $logo_mini;
824
828 public $logo_squarred;
829
833 public $logo_squarred_small;
834
838 public $logo_squarred_mini;
839
843 public $accountancy_code_sell;
844
848 public $accountancy_code_buy;
849
850 // Multicurrency
854 public $fk_multicurrency;
855
859 public $multicurrency_code;
860
861 // Warehouse
865 public $fk_warehouse;
866
870 public $termsofsale;
871
872
873 // Fields loaded by fetchPartnerships()
874
878 public $partnerships = array();
879
880
884 public $bank_account;
885
886
887 const STATUS_CEASED = 0;
888 const STATUS_INACTIVITY = 1;
889
893 const NO_CUSTOMER = 0;
894
898 const CUSTOMER = 1;
899
903 const PROSPECT = 2;
904
909
913 const NO_SUPPLIER = 0;
914
918 const SUPPLIER = 1;
919
925 protected function deprecatedProperties()
926 {
927 return
928 array(
929 'code_compta' => 'code_compta_client',
930 )
931 + parent::deprecatedProperties();
932 }
933
934
935
941 public function __construct($db)
942 {
943 $this->db = $db;
944
945 $this->ismultientitymanaged = 1;
946 $this->isextrafieldmanaged = 1;
947 $this->client = 0;
948 $this->prospect = 0;
949 $this->fournisseur = 0;
950 $this->typent_id = 0;
951 $this->effectif_id = 0;
952 $this->forme_juridique_code = 0;
953 $this->tva_assuj = 1;
954 $this->vat_reverse_charge = 0;
955 $this->status = 1;
956
957 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
958 $this->fields['address']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
959 $this->fields['zip']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
960 $this->fields['town']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
961 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
962 }
963 }
964
965
974 public function create(User $user, $notrigger = 0)
975 {
976 global $langs, $conf;
977
978 $error = 0;
979
980 // Clean parameters
981 if (empty($this->status)) {
982 $this->status = 0;
983 }
984 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
985 $this->setUpperOrLowerCase();
986 $this->nom = $this->name; // For backward compatibility
987
988 if (empty($this->client)) {
989 $this->client = 0;
990 }
991 if (empty($this->fournisseur)) {
992 $this->fournisseur = 0;
993 }
994 $this->import_key = trim((string) $this->import_key);
995
996 $this->code_compta_client = trim($this->code_compta_client);
997
998 $this->accountancy_code_customer_general = trim($this->accountancy_code_customer_general);
999 $this->accountancy_code_customer = trim((string) $this->code_compta_client);
1000 $this->accountancy_code_supplier_general = trim($this->accountancy_code_supplier_general);
1001 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
1002 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1003 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1004
1005 if (!empty($this->multicurrency_code)) {
1006 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1007 }
1008 if (empty($this->fk_multicurrency)) {
1009 $this->multicurrency_code = '';
1010 $this->fk_multicurrency = 0;
1011 }
1012
1013 dol_syslog(get_class($this)."::create ".$this->name);
1014
1015 $now = dol_now();
1016
1017 if (empty($this->date_creation)) {
1018 $this->date_creation = $now;
1019 }
1020
1021 $this->db->begin();
1022
1023 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1024 if ($this->code_client == -1 || $this->code_client === 'auto') {
1025 $this->get_codeclient($this, 0);
1026 }
1027 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1028 $this->get_codefournisseur($this, 1);
1029 }
1030
1031 // Check more parameters (including mandatory setup
1032 // If error, this->errors[] is filled
1033 $result = $this->verify();
1034
1035 if ($result >= 0) {
1036 $this->entity = setEntity($this);
1037
1038 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
1039 $sql .= "nom";
1040 $sql .= ", name_alias";
1041 $sql .= ", entity";
1042 $sql .= ", datec";
1043 $sql .= ", fk_user_creat";
1044 $sql .= ", fk_typent";
1045 $sql .= ", canvas";
1046 $sql .= ", status";
1047 $sql .= ", ref_ext";
1048 $sql .= ", fk_stcomm";
1049 $sql .= ", fk_incoterms";
1050 $sql .= ", location_incoterms";
1051 $sql .= ", import_key";
1052 $sql .= ", fk_multicurrency";
1053 $sql .= ", multicurrency_code";
1054 $sql .= ", ip";
1055 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1056 $sql .= ", vat_reverse_charge";
1057 $sql .= ", accountancy_code_buy";
1058 $sql .= ", accountancy_code_sell";
1059 }
1060 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
1061 $sql .= " '".$this->db->escape($this->name_alias)."',";
1062 $sql .= " ".((int) $this->entity).",";
1063 $sql .= " '".$this->db->idate($this->date_creation)."'";
1064 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
1065 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
1066 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
1067 $sql .= ", ".((int) $this->status);
1068 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1069 $sql .= ", 0";
1070 $sql .= ", ".(int) $this->fk_incoterms;
1071 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1072 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1073 $sql .= ", ".(int) $this->fk_multicurrency;
1074 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1075 $sql .= ", '".$this->db->escape($this->ip)."'";
1076 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1077 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1078 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1079 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1080 }
1081 $sql .= ")";
1082
1083 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1084
1085 $result = $this->db->query($sql);
1086 if ($result) {
1087 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1088
1089 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1090
1091 // update accountancy for this entity
1092 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1093 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1094
1095 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1096 $sql .= " fk_soc";
1097 $sql .= ", entity";
1098 $sql .= ", vat_reverse_charge";
1099 $sql .= ", accountancy_code_customer_general";
1100 $sql .= ", accountancy_code_customer";
1101 $sql .= ", accountancy_code_supplier_general";
1102 $sql .= ", accountancy_code_supplier";
1103 $sql .= ", accountancy_code_buy";
1104 $sql .= ", accountancy_code_sell";
1105 $sql .= ") VALUES (";
1106 $sql .= $this->id;
1107 $sql .= ", ".((int) $conf->entity);
1108 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1109 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1110 $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1111 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1112 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1113 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1114 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1115 $sql .= ")";
1116 $result = $this->db->query($sql);
1117 if (!$result) {
1118 $error++;
1119 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1120 }
1121 }
1122
1123 // Ajout du commercial affecte
1124 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1125 $this->add_commercial($user, $this->commercial_id);
1126 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1127 // si un commercial cree un client il lui est affecte automatiquement
1128 $this->add_commercial($user, $user->id);
1129 }
1130
1131 if ($ret >= 0) {
1132 if (! $notrigger) {
1133 // Call trigger
1134 $result = $this->call_trigger('COMPANY_CREATE', $user);
1135 if ($result < 0) {
1136 $error++;
1137 }
1138 // End call triggers
1139 }
1140 } else {
1141 $error++;
1142 }
1143
1144 if (!$error) {
1145 dol_syslog(get_class($this)."::Create success id=".$this->id);
1146 $this->db->commit();
1147 return $this->id;
1148 } else {
1149 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1150 $this->db->rollback();
1151 return -4;
1152 }
1153 } else {
1154 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1155 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1156 $result = -1;
1157 } else {
1158 $this->error = $this->db->lasterror();
1159 $result = -2;
1160 }
1161 $this->db->rollback();
1162 return $result;
1163 }
1164 } else {
1165 $this->db->rollback();
1166 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1167 return -3;
1168 }
1169 }
1170
1171
1172 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1182 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1183 {
1184 global $conf;
1185
1186 $error = 0;
1187
1188 $this->db->begin();
1189
1190 // phpcs:enable
1191 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1192 $contact = new Contact($this->db);
1193
1194 $contact->name = $this->name_bis;
1195 $contact->firstname = $this->firstname;
1196 $contact->civility_id = $this->civility_id;
1197 $contact->socid = $this->id; // fk_soc
1198 $contact->statut = 1; // deprecated
1199 $contact->status = 1;
1200 $contact->priv = 0;
1201 $contact->country_id = $this->country_id;
1202 $contact->state_id = $this->state_id;
1203 $contact->address = $this->address;
1204 $contact->email = $this->email;
1205 $contact->zip = $this->zip;
1206 $contact->town = $this->town;
1207 $this->setUpperOrLowerCase();
1208 $contact->phone_pro = $this->phone;
1209 if (getDolGlobalString('CONTACTS_DEFAULT_ROLES')) {
1210 $contact->roles = explode(',', getDolGlobalString('CONTACTS_DEFAULT_ROLES'));
1211 }
1212
1213 $contactId = $contact->create($user, $notrigger);
1214 if ($contactId < 0) {
1215 $error++;
1216 $this->setErrorsFromObject($contact);
1217 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1218 }
1219
1220 if (empty($error) && is_array($tags) && !empty($tags)) {
1221 $result = $contact->setCategories($tags);
1222 if ($result < 0) {
1223 $error++;
1224 $this->setErrorsFromObject($contact);
1225 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1226 $contactId = $result;
1227 }
1228 }
1229
1230 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1231 $result = $contact->setNoEmail($no_email);
1232 if ($result < 0) {
1233 $this->setErrorsFromObject($contact);
1234 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1235 $contactId = $result;
1236 }
1237 }
1238
1239 if (empty($error)) {
1240 dol_syslog(get_class($this)."::create_individual success");
1241 $this->db->commit();
1242 } else {
1243 $this->db->rollback();
1244 }
1245
1246 return $contactId;
1247 }
1248
1255 public function verify()
1256 {
1257 global $conf, $langs, $mysoc;
1258
1259 $error = 0;
1260 $this->errors = array();
1261
1262 $result = 0;
1263 $this->name = trim($this->name);
1264 $this->nom = $this->name; // For backward compatibility
1265
1266 if (!$this->name) {
1267 $this->errors[] = 'ErrorBadThirdPartyName';
1268 $result = -2;
1269 }
1270
1271 if ($this->client) {
1272 $rescode = $this->check_codeclient();
1273 if ($rescode != 0 && $rescode != -5) {
1274 if ($rescode == -1) {
1275 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1276 } elseif ($rescode == -2) {
1277 $this->errors[] = 'ErrorCustomerCodeRequired';
1278 } elseif ($rescode == -3) {
1279 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1280 } elseif ($rescode == -4) {
1281 $this->errors[] = 'ErrorPrefixRequired';
1282 } else {
1283 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1284 }
1285
1286 $result = -3;
1287 }
1288 }
1289
1290 if ($this->fournisseur) {
1291 $rescode = $this->check_codefournisseur();
1292 if ($rescode != 0 && $rescode != -5) {
1293 if ($rescode == -1) {
1294 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1295 } elseif ($rescode == -2) {
1296 $this->errors[] = 'ErrorSupplierCodeRequired';
1297 } elseif ($rescode == -3) {
1298 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1299 } elseif ($rescode == -4) {
1300 $this->errors[] = 'ErrorPrefixRequired';
1301 } else {
1302 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1303 }
1304 $result = -3;
1305 }
1306 }
1307
1308 // Check for duplicate or mandatory fields defined into setup
1309 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1310 foreach ($array_to_check as $key) {
1311 $keymin = strtolower($key);
1312 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1313 $keymin = 'code_compta_client';
1314 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1315 $keymin = 'code_compta_fournisseur';
1316 }
1317 $i = (int) preg_replace('/[^0-9]/', '', $key);
1318 $vallabel = $this->$keymin;
1319
1320 if ($i > 0) {
1321 if ($mysoc != null && $this->isACompany()) {
1322 // Check for mandatory prof id (but only if country is same than ours)
1323 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1324 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1325 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1326 $langs->load("errors");
1327 $error++;
1328 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1329 }
1330 }
1331 }
1332
1333 // Check for unicity on profid
1334 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1335 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1336 $langs->load("errors");
1337 $error++;
1338 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1339 }
1340 }
1341 } else {
1342 //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1343 //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1344 if ($key == 'EMAIL') {
1345 // Check for mandatory
1346 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1347 $langs->load("errors");
1348 $error++;
1349 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1350 }
1351
1352 // Check for unicity
1353 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1354 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1355 $langs->load("errors");
1356 $error++;
1357 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1358 }
1359 }
1360 } elseif ($key == 'TVA_INTRA') {
1361 // Check for unicity
1362 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1363 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1364 $langs->load("errors");
1365 $error++;
1366 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1367 }
1368 }
1369 if ($this->tva_assuj && !$vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_MANDATORY')) {
1370 $langs->load("errors");
1371 $error++;
1372 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('VATIntra')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1373 }
1374 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1375 // Check for unicity
1376 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1377 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1378 $langs->loadLangs(array("errors", 'compta'));
1379 $error++;
1380 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1381 }
1382 }
1383
1384 // Check for mandatory
1385 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1386 $langs->loadLangs(array("errors", 'compta'));
1387 $error++;
1388 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1389 }
1390 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1391 // Check for unicity
1392 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1393 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1394 $langs->loadLangs(array("errors", 'compta'));
1395 $error++;
1396 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1397 }
1398 }
1399
1400 // Check for mandatory
1401 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1402 $langs->loadLangs(array("errors", 'compta'));
1403 $error++;
1404 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1405 }
1406 }
1407 }
1408 }
1409
1410 if ($error) {
1411 $result = -4;
1412 }
1413
1414 return $result;
1415 }
1416
1429 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1430 {
1431 global $langs, $conf, $hookmanager;
1432
1433 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1434
1435 if (empty($id)) {
1436 $id = $this->id;
1437 }
1438
1439 $error = 0;
1440
1441 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1442
1443 $now = dol_now();
1444
1445 // Clean parameters
1446 $this->id = $id;
1447 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1448 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1449 $this->nom = $this->name; // For backward compatibility
1450 $this->name_alias = trim((string) $this->name_alias);
1451 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1452 $this->address = trim((string) $this->address);
1453 $this->zip = trim((string) $this->zip);
1454 $this->town = trim((string) $this->town);
1455 $this->state_id = (is_numeric($this->state_id)) ? (int) $this->state_id : 0;
1456 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1457 $this->phone = trim((string) $this->phone);
1458 $this->phone = preg_replace("/\s/", "", $this->phone);
1459 $this->phone = preg_replace("/\./", "", $this->phone);
1460 $this->phone_mobile = trim((string) $this->phone_mobile);
1461 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1462 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1463 $this->fax = trim((string) $this->fax);
1464 $this->fax = preg_replace("/\s/", "", $this->fax);
1465 $this->fax = preg_replace("/\./", "", $this->fax);
1466 $this->email = trim((string) $this->email);
1467 $this->url = $this->url ? clean_url($this->url, 0) : '';
1468 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1469 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1470 $this->idprof1 = trim((string) $this->idprof1);
1471 $this->idprof2 = trim((string) $this->idprof2);
1472 $this->idprof3 = trim((string) $this->idprof3);
1473 $this->idprof4 = trim((string) $this->idprof4);
1474 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1475 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1476 $this->prefix_comm = trim((string) $this->prefix_comm);
1477 $this->outstanding_limit = price2num($this->outstanding_limit);
1478 $this->order_min_amount = price2num($this->order_min_amount);
1479 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1480
1481 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1482 $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1483 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1484 if (empty($this->status)) {
1485 $this->status = 0;
1486 }
1487
1488 if (!empty($this->multicurrency_code)) {
1489 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1490 }
1491 if (empty($this->fk_multicurrency)) {
1492 $this->multicurrency_code = '';
1493 $this->fk_multicurrency = 0;
1494 }
1495
1496 // Local taxes
1497 $this->localtax1_assuj = (int) trim((string) $this->localtax1_assuj);
1498 $this->localtax2_assuj = (int) trim((string) $this->localtax2_assuj);
1499
1500 $this->localtax1_value = trim($this->localtax1_value);
1501 $this->localtax2_value = trim($this->localtax2_value);
1502
1503 $this->capital = ($this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1504
1505 $this->effectif_id = (int) trim((string) $this->effectif_id);
1506 $this->forme_juridique_code = (int) trim((string) $this->forme_juridique_code);
1507
1508 //Gencod
1509 $this->barcode = trim($this->barcode);
1510
1511 // For automatic creation
1512 if ($this->code_client == -1 || $this->code_client === 'auto') {
1513 $this->get_codeclient($this, 0);
1514 }
1515 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1516 $this->get_codefournisseur($this, 1);
1517 }
1518
1519 $this->accountancy_code_customer_general = trim($this->accountancy_code_customer_general);
1520 $this->code_compta_client = trim($this->code_compta_client);
1521 $this->accountancy_code_supplier_general = trim($this->accountancy_code_supplier_general);
1522 $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1523
1524 // Check parameters. More tests are done later in the ->verify()
1525 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1526 $langs->load("errors");
1527 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1528 return -1;
1529 }
1530
1531 $customer = false;
1532 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1533 // If $allowmodcodeclient is set and value is not set, we generate it
1534 if (empty($this->code_compta_client)) {
1535 $ret = $this->get_codecompta('customer');
1536 if ($ret < 0) {
1537 return -1;
1538 }
1539 }
1540
1541 $customer = true;
1542 }
1543
1544 $supplier = false;
1545 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1546 // If $allowmodcodefournisseur is set and value is not set, we generate it
1547 if (empty($this->code_compta_fournisseur)) {
1548 $ret = $this->get_codecompta('supplier');
1549 if ($ret < 0) {
1550 return -1;
1551 }
1552 }
1553
1554 $supplier = true;
1555 }
1556
1557 //Web services
1558 $this->webservices_url = $this->webservices_url ? clean_url($this->webservices_url, 0) : '';
1559 $this->webservices_key = trim($this->webservices_key);
1560
1561 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1562 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1563
1564 //Incoterms
1565 $this->fk_incoterms = (int) $this->fk_incoterms;
1566 $this->location_incoterms = trim($this->location_incoterms);
1567
1568 $this->db->begin();
1569
1570 // Check name is required and codes are ok or unique.
1571 // If error, this->errors[] is filled
1572 $result = 0;
1573 if ($action != 'add' && $action != 'merge') {
1574 // We don't check when update called during a create because verify was already done.
1575 // 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
1576 $result = $this->verify();
1577
1578 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1579 // So we can update record that were using and old numbering rule.
1580 if (is_array($this->errors)) {
1581 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1582 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1583 unset($this->errors[$key]); // Remove error message
1584 }
1585 }
1586 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1587 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1588 unset($this->errors[$key]); // Remove error message
1589 }
1590 }
1591 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1592 $result = 0;
1593 }
1594 }
1595 }
1596 $this->setUpperOrLowerCase();
1597 if ($result >= 0) {
1598 dol_syslog(get_class($this)."::update verify ok or not done");
1599
1600 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1601 $sql .= "entity = ".((int) $this->entity);
1602 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1603 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1604 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1605 $sql .= ",address = '".$this->db->escape($this->address)."'";
1606
1607 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1608 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1609
1610 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1611 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1612
1613 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1614 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1615 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1616 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1617 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1618 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1619
1620 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1621
1622 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1623 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1624
1625 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1626 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1627 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1628 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1629 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1630 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1631
1632 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1633 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1634 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1635 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1636 }
1637 $sql .= ",status = ".((int) $this->status);
1638
1639 // Local taxes
1640 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1641 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1642 if ($this->localtax1_assuj == 1) {
1643 if ($this->localtax1_value != '') {
1644 $sql .= ",localtax1_value =".$this->localtax1_value;
1645 } else {
1646 $sql .= ",localtax1_value =0.000";
1647 }
1648 } else {
1649 $sql .= ",localtax1_value =0.000";
1650 }
1651
1652 if ($this->localtax2_assuj == 1) {
1653 if ($this->localtax2_value != '') {
1654 $sql .= ",localtax2_value =".$this->localtax2_value;
1655 } else {
1656 $sql .= ",localtax2_value =0.000";
1657 }
1658 } else {
1659 $sql .= ",localtax2_value =0.000";
1660 }
1661
1662 $sql .= ",capital = ".($this->capital === null ? "null" : $this->capital);
1663
1664 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1665
1666 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1667 if (isset($this->stcomm_id)) {
1668 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1669 }
1670 if (isset($this->typent_id)) {
1671 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1672 }
1673
1674 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1675
1676 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1677 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1678 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1679 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1680 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1681 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1682 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1683 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1684
1685 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1686 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1687 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1688 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1689 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1690 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1691 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1692 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1693 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1694 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1695 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1696 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1697 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1698 if ($customer) {
1699 $sql .= ", accountancy_code_customer_general = ".(!empty($this->accountancy_code_customer_general) ? "'".$this->db->escape($this->accountancy_code_customer_general)."'" : "null");
1700 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1701 }
1702
1703 if ($supplier) {
1704 $sql .= ", accountancy_code_supplier_general = ".(!empty($this->accountancy_code_supplier_general) ? "'".$this->db->escape($this->accountancy_code_supplier_general)."'" : "null");
1705 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1706 }
1707 }
1708 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1709 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1710
1711 //Incoterms
1712 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1713 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1714
1715 if ($customer) {
1716 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1717 }
1718
1719 if ($supplier) {
1720 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1721 }
1722 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1723 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1724 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1725 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1726 $sql .= " WHERE rowid = ".(int) $id;
1727
1728 $resql = $this->db->query($sql);
1729 if ($resql) {
1730 if (is_object($this->oldcopy)) { // If we have information on old values
1731 if ($this->oldcopy->country_id != $this->country_id) {
1732 unset($this->country_code);
1733 unset($this->country);
1734 }
1735 if ($this->oldcopy->state_id != $this->state_id) {
1736 unset($this->state_code);
1737 unset($this->state);
1738 }
1739 } else {
1740 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1741 unset($this->country);
1742 unset($this->state_code);
1743 unset($this->state);
1744 }
1745
1746 $nbrowsaffected = $this->db->affected_rows($resql);
1747
1748 if (!$error && $nbrowsaffected) {
1749 // Update information on linked member if it is an update
1750 if (!$nosyncmember && isModEnabled('member')) {
1751 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1752
1753 dol_syslog(get_class($this)."::update update linked member");
1754
1755 $lmember = new Adherent($this->db);
1756 $result = $lmember->fetch(0, 0, $this->id);
1757
1758 if ($result > 0) {
1759 $lmember->company = $this->name;
1760 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1761 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1762 $lmember->address = $this->address;
1763 $lmember->zip = $this->zip;
1764 $lmember->town = $this->town;
1765 $lmember->email = $this->email;
1766 $lmember->socialnetworks = $this->socialnetworks;
1767 $lmember->phone = $this->phone;
1768 $lmember->state_id = $this->state_id;
1769 $lmember->country_id = $this->country_id;
1770 $lmember->default_lang = $this->default_lang;
1771
1772 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1773 if ($result < 0) {
1774 $this->error = $lmember->error;
1775 $this->errors = array_merge($this->errors, $lmember->errors);
1776 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1777 $error++;
1778 }
1779 } elseif ($result < 0) {
1780 $this->error = $lmember->error;
1781 $error++;
1782 }
1783 }
1784 }
1785
1786 $action = 'update';
1787
1788 // update accountancy for this entity
1789 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1790 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1791
1792 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1793 $sql .= " fk_soc";
1794 $sql .= ", entity";
1795 $sql .= ", vat_reverse_charge";
1796 $sql .= ", accountancy_code_customer_general";
1797 $sql .= ", accountancy_code_customer";
1798 $sql .= ", accountancy_code_supplier_general";
1799 $sql .= ", accountancy_code_supplier";
1800 $sql .= ", accountancy_code_buy";
1801 $sql .= ", accountancy_code_sell";
1802 $sql .= ") VALUES (";
1803 $sql .= $this->id;
1804 $sql .= ", ".$conf->entity;
1805 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1806 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1807 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1808 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1809 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1810 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1811 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1812 $sql .= ")";
1813 $result = $this->db->query($sql);
1814 if (!$result) {
1815 $error++;
1816 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1817 }
1818 }
1819
1820 // Actions on extra fields
1821 if (!$error) {
1822 $result = $this->insertExtraFields();
1823 if ($result < 0) {
1824 $error++;
1825 }
1826 }
1827 // Actions on extra languages
1828 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1829 $result = $this->insertExtraLanguages();
1830 if ($result < 0) {
1831 $error++;
1832 }
1833 }
1834
1835 if (!$error && $call_trigger) {
1836 // Call trigger
1837 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1838 if ($result < 0) {
1839 $error++;
1840 }
1841 // End call triggers
1842 }
1843
1844 if (!$error) {
1845 dol_syslog(get_class($this)."::Update success");
1846 $this->db->commit();
1847 return 1;
1848 } else {
1849 $this->db->rollback();
1850 return -1;
1851 }
1852 } else {
1853 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1854 // Doublon
1855 $this->error = $langs->trans("ErrorDuplicateField");
1856 $result = -1;
1857 } else {
1858 $this->error = $this->db->lasterror();
1859 $result = -2;
1860 }
1861 $this->db->rollback();
1862 return $result;
1863 }
1864 } else {
1865 $this->db->rollback();
1866 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1867 return -3;
1868 }
1869 }
1870
1890 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1891 {
1892 global $langs;
1893 global $conf;
1894
1895 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)) {
1896 return -1;
1897 }
1898
1899 $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';
1900 $sql .= ', s.status, s.fk_warehouse';
1901 $sql .= ', s.price_level';
1902 $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1903 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1904 $sql .= ', s.socialnetworks';
1905 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1906 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1907 $sql .= ', s.capital, s.tva_intra';
1908 $sql .= ', s.fk_typent as typent_id';
1909 $sql .= ', s.fk_effectif as effectif_id';
1910 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1911 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1912 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1913 $sql .= ', s.accountancy_code_customer_general, s.code_compta';
1914 $sql .= ', s.accountancy_code_supplier_general, s.code_compta_fournisseur';
1915 $sql .= ', s.accountancy_code_buy, s.accountancy_code_sell';
1916 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1917 } else {
1918 $sql .= ', spe.accountancy_code_customer_general, spe.accountancy_code_customer as code_compta';
1919 $sql .= ', spe.accountancy_code_supplier_general, spe.accountancy_code_supplier as code_compta_fournisseur';
1920 $sql .= ', spe.accountancy_code_buy, spe.accountancy_code_sell';
1921 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1922 }
1923 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1924 $sql .= ', s.fk_departement as state_id, s.fk_pays as country_id, s.fk_stcomm, s.mode_reglement, s.cond_reglement, s.deposit_percent, s.transport_mode';
1925 $sql .= ', s.fk_account, s.tva_assuj';
1926 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1927 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1928 $sql .= ', s.fk_shipping_method';
1929 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1930 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1931 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1932 $sql .= ', fj.libelle as forme_juridique';
1933 $sql .= ', e.libelle as effectif';
1934 $sql .= ', c.code as country_code, c.label as country';
1935 $sql .= ', d.code_departement as state_code, d.nom as state';
1936 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1937 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1938 $sql .= ', te.code as typent_code';
1939 $sql .= ', i.libelle as label_incoterms';
1940 if (!isModEnabled('multicompany')) {
1941 $sql .= ', s.remise_client, s.remise_supplier';
1942 } else {
1943 $sql .= ', sr.remise_client, sr2.remise_supplier';
1944 }
1945 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1946 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1947 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1948 }
1949 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1950 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1951 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1952 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1953 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1954 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1955 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1956 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1957 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1958 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1959 if (isModEnabled('multicompany')) {
1960 $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').'))';
1961 $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').'))';
1962 }
1963 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1964
1965 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
1966 if ($is_client) {
1967 $sql .= ' AND s.client > 0';
1968 }
1969 if ($is_supplier) {
1970 $sql .= ' AND s.fournisseur > 0';
1971 } // if both false, no test (the thirdparty can be client and/or supplier)
1972
1973 if ($rowid) {
1974 $sql .= ' AND s.rowid = '.((int) $rowid);
1975 }
1976 if ($ref) {
1977 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1978 }
1979 if ($ref_alias) {
1980 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1981 }
1982 if ($ref_ext) {
1983 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1984 }
1985 if ($barcode) {
1986 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1987 }
1988 if ($idprof1) {
1989 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1990 }
1991 if ($idprof2) {
1992 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1993 }
1994 if ($idprof3) {
1995 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1996 }
1997 if ($idprof4) {
1998 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1999 }
2000 if ($idprof5) {
2001 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
2002 }
2003 if ($idprof6) {
2004 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
2005 }
2006 if ($email) {
2007 $sql .= " AND s.email = '".$this->db->escape($email)."'";
2008 }
2009
2010 $resql = $this->db->query($sql);
2011 if ($resql) {
2012 $num = $this->db->num_rows($resql);
2013 if ($num > 1) {
2014 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2015 dol_syslog($this->error, LOG_ERR);
2016 $result = -2;
2017 } elseif ($num) { // $num = 1
2018 $obj = $this->db->fetch_object($resql);
2019
2020 $this->id = $obj->rowid;
2021 $this->entity = $obj->entity;
2022 $this->canvas = $obj->canvas;
2023
2024 $this->ref = $obj->rowid;
2025 $this->name = $obj->name;
2026 $this->nom = $obj->name; // deprecated
2027 $this->name_alias = $obj->name_alias;
2028 $this->ref_ext = $obj->ref_ext;
2029
2030 $this->date_creation = $this->db->jdate($obj->date_creation);
2031 $this->date_modification = $this->db->jdate($obj->date_modification);
2032 $this->user_creation_id = $obj->fk_user_creat;
2033 $this->user_modification_id = $obj->fk_user_modif;
2034
2035 $this->address = $obj->address;
2036 $this->zip = $obj->zip;
2037 $this->town = $obj->town;
2038
2039 $this->country_id = $obj->country_id;
2040 $this->country_code = $obj->country_id ? $obj->country_code : '';
2041 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
2042
2043 $this->state_id = $obj->state_id;
2044 $this->state_code = $obj->state_code;
2045 $this->region_id = $obj->region_id;
2046 $this->region_code = $obj->region_code;
2047 $this->state = ($obj->state != '-' ? $obj->state : '');
2048
2049 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
2050 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
2051 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
2052 $this->status_prospect_label = $label; // label status prospect
2053 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
2054
2055 $this->email = $obj->email;
2056 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
2057
2058 $this->url = $obj->url;
2059 $this->phone = $obj->phone;
2060 $this->phone_mobile = $obj->phone_mobile;
2061 $this->fax = $obj->fax;
2062
2063 $this->parent = $obj->parent;
2064
2065 $this->idprof1 = $obj->idprof1;
2066 $this->idprof2 = $obj->idprof2;
2067 $this->idprof3 = $obj->idprof3;
2068 $this->idprof4 = $obj->idprof4;
2069 $this->idprof5 = $obj->idprof5;
2070 $this->idprof6 = $obj->idprof6;
2071
2072 $this->capital = $obj->capital;
2073
2074 $this->code_client = $obj->code_client;
2075 $this->code_fournisseur = $obj->code_fournisseur;
2076
2077 $this->accountancy_code_customer_general = $obj->accountancy_code_customer_general;
2078 $this->code_compta_client = $obj->code_compta;
2079 $this->accountancy_code_supplier_general = $obj->accountancy_code_supplier_general;
2080 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
2081
2082 $this->barcode = $obj->barcode;
2083
2084 $this->tva_assuj = $obj->tva_assuj;
2085 $this->tva_intra = $obj->tva_intra;
2086
2087 if (!empty($obj->spe_vat_reverse_charge)) {
2088 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2089 } elseif (!empty($obj->soc_vat_reverse_charge)) {
2090 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2091 } else {
2092 $this->vat_reverse_charge = 0;
2093 }
2094
2095 $this->status = $obj->status;
2096
2097 // Local Taxes
2098 $this->localtax1_assuj = $obj->localtax1_assuj;
2099 $this->localtax2_assuj = $obj->localtax2_assuj;
2100
2101 $this->localtax1_value = $obj->localtax1_value;
2102 $this->localtax2_value = $obj->localtax2_value;
2103
2104 $this->typent_id = $obj->typent_id;
2105 $this->typent_code = $obj->typent_code;
2106
2107 $this->effectif_id = $obj->effectif_id;
2108 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2109
2110 $this->forme_juridique_code = $obj->forme_juridique_code;
2111 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2112
2113 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2114
2115 $this->prefix_comm = $obj->prefix_comm;
2116
2117 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2118 $this->remise_supplier_percent = $obj->remise_supplier;
2119
2120 $this->mode_reglement_id = $obj->mode_reglement;
2121 $this->cond_reglement_id = $obj->cond_reglement;
2122 $this->deposit_percent = $obj->deposit_percent;
2123 $this->transport_mode_id = $obj->transport_mode;
2124 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2125 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2126 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2127 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2128 $this->fk_account = $obj->fk_account;
2129
2130 $this->client = $obj->client;
2131 $this->fournisseur = $obj->fournisseur;
2132
2133 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2134 $this->note_private = $obj->note_private;
2135 $this->note_public = $obj->note_public;
2136 $this->model_pdf = $obj->model_pdf;
2137 $this->default_lang = $obj->default_lang;
2138 $this->logo = $obj->logo;
2139 $this->logo_squarred = $obj->logo_squarred;
2140
2141 $this->webservices_url = $obj->webservices_url;
2142 $this->webservices_key = $obj->webservices_key;
2143
2144 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2145 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2146
2147 $this->outstanding_limit = $obj->outstanding_limit;
2148 $this->order_min_amount = $obj->order_min_amount;
2149 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2150
2151 // multiprix
2152 $this->price_level = $obj->price_level;
2153
2154 // warehouse
2155 $this->fk_warehouse = $obj->fk_warehouse;
2156
2157 $this->import_key = $obj->import_key;
2158
2159 //Incoterms
2160 $this->fk_incoterms = $obj->fk_incoterms;
2161 $this->location_incoterms = $obj->location_incoterms;
2162 $this->label_incoterms = $obj->label_incoterms;
2163
2164 // multicurrency
2165 $this->fk_multicurrency = $obj->fk_multicurrency;
2166 $this->multicurrency_code = $obj->multicurrency_code;
2167
2168 // pdf
2169 $this->model_pdf = $obj->model_pdf;
2170 $this->last_main_doc = $obj->last_main_doc;
2171
2172 $result = $this->id;
2173
2174 // fetch optionals attributes and labels
2175 $this->fetch_optionals();
2176 } else {
2177 $result = 0;
2178 }
2179
2180 $this->db->free($resql);
2181 } else {
2182 $this->error = $this->db->lasterror();
2183 $this->errors[] = $this->db->lasterror();
2184 $result = -3;
2185 }
2186
2187 // Use first price level if level not defined for third party
2188 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->price_level)) {
2189 $this->price_level = 1;
2190 }
2191
2192 return $result;
2193 }
2194
2215 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
2216 {
2217 // A rowid is known, it is a unique key so we found it
2218 if ($rowid) {
2219 return $rowid;
2220 }
2221
2222 // We try to find the thirdparty with exact matching on all fields
2223 // TODO Replace this with step by step search
2224 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2225 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2226 // Then search on email (+ restriction on is_client and is_supplier)
2227 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2228 $tmpthirdparty = new Societe($this->db);
2229 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2230
2231 return $result;
2232 }
2233
2242 public function delete($id, $fuser = null, $call_trigger = 1)
2243 {
2244 global $conf, $user;
2245
2246 if (empty($fuser)) {
2247 $fuser = $user;
2248 }
2249
2250 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2251
2252 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2253
2254 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2255 $error = 0;
2256
2257 // Test if child exists
2258 $objectisused = $this->isObjectUsed($id);
2259 if (empty($objectisused)) {
2260 $this->db->begin();
2261
2262 // User is mandatory for trigger call
2263 if (!$error && $call_trigger) {
2264 // Call trigger
2265 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2266 if ($result < 0) {
2267 $error++;
2268 }
2269 // End call triggers
2270 }
2271
2272 if (!$error) {
2273 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2274 $static_cat = new Categorie($this->db);
2275 $toute_categs = array();
2276
2277 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2278 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2279 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2280
2281 // Remove each "Categorie"
2282 foreach ($toute_categs as $type => $categs_type) {
2283 foreach ($categs_type as $cat) {
2284 $cat->del_type($this, $type);
2285 }
2286 }
2287 }
2288
2289 if (!$error) {
2290 foreach ($this->childtablesoncascade as $tabletodelete) {
2291 $deleteFromObject = explode(':', $tabletodelete, 4);
2292 if (count($deleteFromObject) >= 2) {
2293 $className = str_replace('@', '', $deleteFromObject[0]);
2294 $filepath = $deleteFromObject[1];
2295 $columnName = $deleteFromObject[2];
2296 if (dol_include_once($filepath)) {
2297 $child_object = new $className($this->db);
2298 '@phan-var-force CommonObject $child_object';
2299 $result = $child_object->deleteByParentField($id, $columnName);
2300 if ($result < 0) {
2301 $error++;
2302 $this->errors[] = $child_object->error;
2303 break;
2304 }
2305 } else {
2306 $error++;
2307 $this->errors[] = 'Cannot include child class file '.$filepath;
2308 break;
2309 }
2310 } else {
2311 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2312 $sql .= " WHERE fk_soc = ".((int) $id);
2313 if (!$this->db->query($sql)) {
2314 $error++;
2315 $this->errors[] = $this->db->lasterror();
2316 break;
2317 }
2318 }
2319 }
2320 }
2321
2322 // Removed extrafields
2323 if (!$error) {
2324 $result = $this->deleteExtraFields();
2325 if ($result < 0) {
2326 $error++;
2327 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2328 }
2329 }
2330
2331 // Remove links to subsidiaries companies
2332 if (!$error) {
2333 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2334 $sql .= " SET parent = NULL";
2335 $sql .= " WHERE parent = ".((int) $id);
2336 if (!$this->db->query($sql)) {
2337 $error++;
2338 $this->errors[] = $this->db->lasterror();
2339 }
2340 }
2341
2342 // Remove third party
2343 if (!$error) {
2344 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2345 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2346 $sql .= " WHERE fk_soc = ".((int) $id);
2347 if (!$this->db->query($sql)) {
2348 $error++;
2349 $this->errors[] = $this->db->lasterror();
2350 }
2351 }
2352
2353 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2354 $sql .= " WHERE rowid = ".((int) $id);
2355 if (!$this->db->query($sql)) {
2356 $error++;
2357 $this->errors[] = $this->db->lasterror();
2358 }
2359 }
2360
2361 if (!$error) {
2362 $this->db->commit();
2363
2364 // Delete directory
2365 if (!empty($conf->societe->multidir_output[$entity])) {
2366 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2367 if (dol_is_dir($docdir)) {
2368 dol_delete_dir_recursive($docdir);
2369 }
2370 }
2371
2372 return 1;
2373 } else {
2374 dol_syslog($this->error, LOG_ERR);
2375 $this->db->rollback();
2376 return -1;
2377 }
2378 } else {
2379 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2380 }
2381 return 0;
2382 }
2383
2384 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2392 public function set_as_client()
2393 {
2394 // phpcs:enable
2395 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2396 return $this->setAsCustomer();
2397 }
2398
2405 public function setAsCustomer()
2406 {
2407 if ($this->id) {
2408 $newclient = 1;
2409 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2410 $newclient = 3; //If prospect, we keep prospect tag
2411 }
2412 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2413 $sql .= " SET client = ".((int) $newclient);
2414 $sql .= " WHERE rowid = ".((int) $this->id);
2415
2416 $resql = $this->db->query($sql);
2417 if ($resql) {
2418 $this->client = $newclient;
2419 return 1;
2420 } else {
2421 return -1;
2422 }
2423 }
2424 return 0;
2425 }
2426
2427 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2436 public function set_remise_client($remise, $note, User $user)
2437 {
2438 // phpcs:enable
2439 global $conf, $langs;
2440
2441 // Parameter cleaning
2442 $note = trim($note);
2443 if (!$note) {
2444 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2445 return -2;
2446 }
2447
2448 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2449
2450 if ($this->id) {
2451 $this->db->begin();
2452
2453 $now = dol_now();
2454
2455 // Position current discount
2456 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2457 $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2458 $sql .= " WHERE rowid = ".((int) $this->id);
2459 $resql = $this->db->query($sql);
2460 if (!$resql) {
2461 $this->db->rollback();
2462 $this->error = $this->db->error();
2463 return -1;
2464 }
2465
2466 // Writes trace in discount history
2467 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2468 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2469 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2470 $sql .= " '".$this->db->escape($note)."',";
2471 $sql .= " ".((int) $user->id);
2472 $sql .= ")";
2473
2474 $resql = $this->db->query($sql);
2475 if (!$resql) {
2476 $this->db->rollback();
2477 $this->error = $this->db->lasterror();
2478 return -1;
2479 }
2480
2481 $this->db->commit();
2482
2483 return 1;
2484 }
2485 return -1;
2486 }
2487
2488 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2497 public function set_remise_supplier($remise, $note, User $user)
2498 {
2499 // phpcs:enable
2500 global $conf, $langs;
2501
2502 // Parameter cleaning
2503 $note = trim($note);
2504 if (!$note) {
2505 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2506 return -2;
2507 }
2508
2509 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2510
2511 if ($this->id) {
2512 $this->db->begin();
2513
2514 $now = dol_now();
2515
2516 // Position current discount
2517 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2518 $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2519 $sql .= " WHERE rowid = ".((int) $this->id);
2520 $resql = $this->db->query($sql);
2521 if (!$resql) {
2522 $this->db->rollback();
2523 $this->error = $this->db->error();
2524 return -1;
2525 }
2526
2527 // Writes trace in discount history
2528 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2529 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2530 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2531 $sql .= " '".$this->db->escape($note)."',";
2532 $sql .= " ".((int) $user->id);
2533 $sql .= ")";
2534
2535 $resql = $this->db->query($sql);
2536 if (!$resql) {
2537 $this->db->rollback();
2538 $this->error = $this->db->lasterror();
2539 return -1;
2540 }
2541
2542 $this->db->commit();
2543 return 1;
2544 }
2545
2546 return -1;
2547 }
2548
2549 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2561 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2562 {
2563 // phpcs:enable
2564 global $langs;
2565
2566 // Clean parameters
2567 $remise = price2num($remise);
2568 $desc = trim($desc);
2569
2570 // Check parameters
2571 if (!($remise > 0)) {
2572 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2573 return -1;
2574 }
2575 if (!$desc) {
2576 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2577 return -2;
2578 }
2579
2580 if ($this->id > 0) {
2581 // Clean vat code
2582 $reg = array();
2583 $vat_src_code = '';
2584 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2585 $vat_src_code = $reg[1];
2586 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2587 }
2588
2589 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2590
2591 $discount = new DiscountAbsolute($this->db);
2592 $discount->fk_soc = $this->id;
2593 $discount->socid = $this->id;
2594
2595 $discount->discount_type = $discount_type;
2596
2597 if ($price_base_type == 'TTC') {
2598 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2599 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2600 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $discount->amount_ttc - (float) $discount->amount_ht, 'MT');
2601 } else {
2602 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2603 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $remise * (float) $vatrate / 100, 'MT');
2604 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num((float) $discount->amount_ht + (float) $discount->amount_tva, 'MT');
2605 }
2606
2607 $discount->tva_tx = (float) price2num($vatrate);
2608 $discount->vat_src_code = $vat_src_code;
2609
2610 $discount->description = $desc;
2611
2612 $result = $discount->create($user);
2613 if ($result > 0) {
2614 return $result;
2615 } else {
2616 $this->error = $discount->error;
2617 return -3;
2618 }
2619 } else {
2620 return 0;
2621 }
2622 }
2623
2633 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2634 {
2635 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2636
2637 $discountstatic = new DiscountAbsolute($this->db);
2638 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2639 if ($result >= 0) {
2640 return $result;
2641 } else {
2642 $this->error = $discountstatic->error;
2643 return -1;
2644 }
2645 }
2646
2656 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2657 {
2658 global $conf;
2659
2660 $reparray = array();
2661
2662 $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";
2663 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2664 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2665 // Condition here should be the same than into select_dolusers()
2666 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2667 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2668 } else {
2669 $sql .= " WHERE entity IN (0, ".$this->db->sanitize($conf->entity).")";
2670 }
2671
2672 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2673 if (empty($sortfield) && empty($sortorder)) {
2674 $sortfield = 'u.lastname,u.firstname';
2675 $sortorder = 'ASC,ASC';
2676 }
2677 $sql .= $this->db->order($sortfield, $sortorder);
2678
2679 $resql = $this->db->query($sql);
2680 if ($resql) {
2681 $num = $this->db->num_rows($resql);
2682 $i = 0;
2683 while ($i < $num) {
2684 $obj = $this->db->fetch_object($resql);
2685
2686 if (empty($mode)) {
2687 $reparray[$i]['id'] = $obj->rowid;
2688 $reparray[$i]['lastname'] = $obj->lastname;
2689 $reparray[$i]['firstname'] = $obj->firstname;
2690 $reparray[$i]['email'] = $obj->email;
2691 $reparray[$i]['phone'] = $obj->office_phone;
2692 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2693 $reparray[$i]['office_fax'] = $obj->office_fax;
2694 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2695 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2696 $reparray[$i]['job'] = $obj->job;
2697 $reparray[$i]['statut'] = $obj->status; // deprecated
2698 $reparray[$i]['status'] = $obj->status;
2699 $reparray[$i]['entity'] = $obj->entity;
2700 $reparray[$i]['login'] = $obj->login;
2701 $reparray[$i]['photo'] = $obj->photo;
2702 $reparray[$i]['gender'] = $obj->gender;
2703 } else {
2704 $reparray[] = $obj->rowid;
2705 }
2706 $i++;
2707 }
2708 return $reparray;
2709 } else {
2710 dol_print_error($this->db);
2711 return -1;
2712 }
2713 }
2714
2722 public function setPriceLevel($price_level, User $user)
2723 {
2724 if ($this->id) {
2725 $now = dol_now();
2726
2727 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2728 $sql .= " SET price_level = ".((int) $price_level);
2729 $sql .= " WHERE rowid = ".((int) $this->id);
2730
2731 if (!$this->db->query($sql)) {
2732 dol_print_error($this->db);
2733 return -1;
2734 }
2735
2736 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2737 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2738 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2739
2740 if (!$this->db->query($sql)) {
2741 dol_print_error($this->db);
2742 return -1;
2743 }
2744 return 1;
2745 }
2746 return -1;
2747 }
2748
2749 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2757 public function add_commercial(User $user, $commid)
2758 {
2759 // phpcs:enable
2760 $error = 0;
2761
2762 if ($this->id > 0 && $commid > 0) {
2763 $this->db->begin();
2764
2765 if (!$error) {
2766 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2767 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2768
2769 $resql = $this->db->query($sql);
2770 if (!$resql) {
2771 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2772 $error++;
2773 }
2774 }
2775
2776 if (!$error) {
2777 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2778 $sql .= " (fk_soc, fk_user)";
2779 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2780
2781 $resql = $this->db->query($sql);
2782 if (!$resql) {
2783 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2784 $error++;
2785 }
2786 }
2787
2788 if (!$error) {
2789 $this->context = array('commercial_modified' => $commid);
2790
2791 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2792 if ($result < 0) {
2793 $error++;
2794 }
2795 }
2796
2797 if (!$error) {
2798 $this->db->commit();
2799 return 1;
2800 } else {
2801 $this->db->rollback();
2802 return -1;
2803 }
2804 }
2805
2806 return 0;
2807 }
2808
2809 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2817 public function del_commercial(User $user, $commid)
2818 {
2819 // phpcs:enable
2820 $error = 0;
2821 $this->context = array('commercial_modified' => $commid);
2822
2823 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2824 if ($result < 0) {
2825 $error++;
2826 }
2827
2828 if ($this->id > 0 && $commid > 0) {
2829 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2830 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2831
2832 if (!$this->db->query($sql)) {
2833 $error++;
2834 dol_syslog(get_class($this)."::del_commercial Erreur");
2835 }
2836 }
2837
2838 if ($error) {
2839 return -1;
2840 } else {
2841 return 1;
2842 }
2843 }
2844
2852 public function getTooltipContentArray($params)
2853 {
2854 global $conf, $langs, $user;
2855
2856 $langs->loadLangs(['companies', 'commercial']);
2857
2858 $datas = array();
2859
2860 $option = $params['option'] ?? '';
2861 $nofetch = !empty($params['nofetch']);
2862
2863 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2864
2865 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2866 return ['optimize' => $langs->trans("ShowCompany")];
2867 }
2868
2869 if (!empty($this->logo) && class_exists('Form')) {
2870 $photo = '<div class="photointooltip floatright">';
2871 $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.
2872 $photo .= '</div>';
2873 $datas['photo'] = $photo;
2874 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2875 /*$label.= '<div class="photointooltip">';
2876 $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.
2877 $label.= '</div><div style="clear: both;"></div>';*/
2878 // }
2879
2880 $datas['divopen'] = '<div class="centpercent">';
2881
2882 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2883 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2884 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2885 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2886 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2887 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2888 } elseif ($option == 'agenda') {
2889 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2890 } elseif ($option == 'project') {
2891 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2892 } elseif ($option == 'margin') {
2893 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2894 } elseif ($option == 'contact') {
2895 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2896 } elseif ($option == 'ban') {
2897 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2898 }
2899
2900 // By default
2901 if (empty($datas['picto'])) {
2902 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2903 }
2904 if (isset($this->status)) {
2905 $datas['status'] = ' '.$this->getLibStatut(5);
2906 }
2907 if (isset($this->client) && isset($this->fournisseur)) {
2908 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2909 }
2910 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2911 if (!empty($this->name_alias) && empty($noaliasinname)) {
2912 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2913 }
2914 if (!empty($this->email)) {
2915 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2916 }
2917 if (!empty($this->url)) {
2918 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2919 }
2920 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
2921 $phonelist = array();
2922 if ($this->phone) {
2923 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2924 }
2925 // deliberately not making new list because fax uses same list as phone
2926 if ($this->phone_mobile) {
2927 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'phone_mobile');
2928 }
2929 if ($this->fax) {
2930 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2931 }
2932 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2933 }
2934
2935 if (!empty($this->address)) {
2936 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2937 } elseif (!empty($this->country_code)) {
2938 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2939 }
2940 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2941 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2942 }
2943
2944 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
2945 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2946 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2947 }
2948 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2949 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2950 }
2951 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2952 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2953 }
2954 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2955 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2956 }
2957 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2958 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2959 }
2960 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2961 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2962 }
2963 }
2964
2965 $datas['separator'] = '<br>';
2966
2967 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2968 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2969 }
2970 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2971 $langs->load('compta');
2972 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
2973 }
2974 // show categories for this record only in ajax to not overload lists
2975 if (!$nofetch && isModEnabled('category') && $this->client) {
2976 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2977 $form = new Form($this->db);
2978 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2979 }
2980 if (!empty($this->code_fournisseur) && $this->fournisseur) {
2981 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2982 }
2983 if (isModEnabled('accounting') && $this->fournisseur) {
2984 $langs->load('compta');
2985 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2986 }
2987 // show categories for this record only in ajax to not overload lists
2988 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
2989 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2990 $form = new Form($this->db);
2991 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2992 }
2993
2994 $datas['divclose'] = '</div>';
2995
2996 return $datas;
2997 }
2998
3012 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
3013 {
3014 global $conf, $langs, $hookmanager, $user;
3015
3016 if (!empty($conf->dol_no_mouse_hover)) {
3017 $notooltip = 1; // Force disable tooltips
3018 }
3019
3020 $name = $this->name ? $this->name : $this->nom;
3021
3022 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3023 if (empty($option) && $this->client > 0) {
3024 $option = 'customer';
3025 }
3026 if (empty($option) && $this->fournisseur > 0) {
3027 $option = 'supplier';
3028 }
3029 }
3030
3031 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3032 $code = '';
3033 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3034 $code = $this->code_client.' - ';
3035 }
3036
3037 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3038 $code .= $this->code_fournisseur.' - ';
3039 }
3040
3041 if ($code) {
3042 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3043 $name = $code.' '.$name;
3044 } else {
3045 $name = $code;
3046 }
3047 }
3048 }
3049
3050 if (!empty($this->name_alias) && empty($noaliasinname)) {
3051 $name .= ' ('.$this->name_alias.')';
3052 }
3053
3054 $result = '';
3055 $params = [
3056 'id' => $this->id,
3057 'objecttype' => $this->element,
3058 'option' => $option,
3059 'nofetch' => 1,
3060 ];
3061 $classfortooltip = 'classfortooltip';
3062 $dataparams = '';
3063 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3064 $classfortooltip = 'classforajaxtooltip';
3065 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3066 $label = '';
3067 } else {
3068 $label = implode($this->getTooltipContentArray($params));
3069 }
3070
3071 $linkstart = '';
3072 $linkend = '';
3073
3074 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3075 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3076 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3077 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3078 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3079 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3080 } elseif ($option == 'agenda') {
3081 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3082 } elseif ($option == 'project') {
3083 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3084 } elseif ($option == 'margin') {
3085 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3086 } elseif ($option == 'contact') {
3087 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3088 } elseif ($option == 'ban') {
3089 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3090 }
3091
3092 // By default
3093 if (empty($linkstart)) {
3094 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3095 }
3096
3097 // Add type of canvas
3098 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3099 // Add param to save lastsearch_values or not
3100 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3101 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3102 $add_save_lastsearch_values = 1;
3103 }
3104 if ($add_save_lastsearch_values) {
3105 $linkstart .= '&save_lastsearch_values=1';
3106 }
3107 $linkstart .= '"';
3108
3109 $linkclose = '';
3110 if (empty($notooltip)) {
3111 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3112 $label = $langs->trans("ShowCompany");
3113 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3114 }
3115 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3116 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
3117 $target_value = array('_self', '_blank', '_parent', '_top');
3118 if (in_array($target, $target_value)) {
3119 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3120 }
3121 } else {
3122 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3123 }
3124 $linkstart .= $linkclose.'>';
3125 $linkend = '</a>';
3126
3127 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3128 $linkstart = '';
3129 $linkend = '';
3130 }
3131
3132 $result .= $linkstart;
3133 if ($withpicto) {
3134 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3135 }
3136 if ($withpicto != 2) {
3137 $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
3138 }
3139 $result .= $linkend;
3140
3141 global $action;
3142 $hookmanager->initHooks(array('thirdpartydao'));
3143 $parameters = array(
3144 'id' => $this->id,
3145 'getnomurl' => &$result,
3146 'withpicto ' => $withpicto,
3147 'option' => $option,
3148 'maxlen' => $maxlen,
3149 'notooltip' => $notooltip,
3150 'save_lastsearch_value' => $save_lastsearch_value
3151 );
3152 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3153 if ($reshook > 0) {
3154 $result = $hookmanager->resPrint;
3155 } else {
3156 $result .= $hookmanager->resPrint;
3157 }
3158
3159 return $result;
3160 }
3161
3171 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3172 {
3173 global $langs;
3174
3175 $s = '';
3176 if (empty($option) || preg_match('/prospect/', $option)) {
3177 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3178 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.$langs->trans("Prospect").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3179 }
3180 }
3181 if (empty($option) || preg_match('/customer/', $option)) {
3182 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3183 $s .= '<'.$tag.' class="customer-back" title="'.$langs->trans("Customer").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3184 }
3185 }
3186 if (empty($option) || preg_match('/supplier/', $option)) {
3187 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3188 $s .= '<'.$tag.' class="vendor-back" title="'.$langs->trans("Supplier").'" href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3189 }
3190 }
3191 return $s;
3192 }
3193
3194
3201 public function getLibStatut($mode = 0)
3202 {
3203 return $this->LibStatut($this->status, $mode);
3204 }
3205
3206 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3214 public function LibStatut($status, $mode = 0)
3215 {
3216 // phpcs:enable
3217 global $langs;
3218 $langs->load('companies');
3219
3220 $statusType = 'status4';
3221 if ($status == 0) {
3222 $statusType = 'status6';
3223 }
3224
3225 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3226 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3227 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3228 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3229 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3230 }
3231
3232 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3233 }
3234
3235 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3242 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3243 {
3244 // phpcs:enable
3245 global $langs;
3246
3247 $contact_emails = $this->contact_property_array('email', 1);
3248
3249 if ($this->email && $addthirdparty) {
3250 if (empty($this->name)) {
3251 $this->name = $this->nom;
3252 }
3253 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3254 }
3255
3256 //var_dump($contact_emails)
3257 return $contact_emails;
3258 }
3259
3260 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3267 {
3268 // phpcs:enable
3269 global $langs;
3270
3271 $contact_phone = $this->contact_property_array('mobile');
3272
3273 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3274 if (empty($this->name)) {
3275 $this->name = $this->nom;
3276 }
3277 // TODO: Tester si tel non deja present dans tableau contact
3278 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3279 }
3280 return $contact_phone;
3281 }
3282
3283 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3291 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3292 {
3293 // phpcs:enable
3294 global $langs;
3295
3296 $contact_property = array();
3297
3298
3299 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3300 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3301 $sql .= " WHERE fk_soc = ".((int) $this->id);
3302 $sql .= " AND entity IN (".getEntity($this->element).")";
3303 $sql .= " ORDER BY lastname, firstname";
3304
3305 $resql = $this->db->query($sql);
3306 if ($resql) {
3307 $nump = $this->db->num_rows($resql);
3308 if ($nump) {
3309 $sepa = "(";
3310 $sepb = ")";
3311 if ($mode == 'email') {
3312 //$sepa="&lt;"; $sepb="&gt;";
3313 $sepa = "<";
3314 $sepb = ">";
3315 }
3316 $i = 0;
3317 while ($i < $nump) {
3318 $obj = $this->db->fetch_object($resql);
3319 if ($mode == 'email') {
3320 $property = $obj->email;
3321 } elseif ($mode == 'mobile') {
3322 $property = $obj->phone_mobile;
3323 } else {
3324 $property = $obj->$mode;
3325 }
3326
3327 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3328 if ($obj->status == 1 || empty($hidedisabled)) {
3329 if (empty($property)) {
3330 if ($mode == 'email') {
3331 $property = $langs->transnoentitiesnoconv("NoEMail");
3332 } elseif ($mode == 'mobile') {
3333 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3334 }
3335 }
3336
3337 if (!empty($obj->poste)) {
3338 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3339 } else {
3340 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3341 }
3342 }
3343 $i++;
3344 }
3345 }
3346 } else {
3347 dol_print_error($this->db);
3348 }
3349 return $contact_property;
3350 }
3351
3352
3353 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3359 public function contact_array()
3360 {
3361 // phpcs:enable
3362 $contacts = array();
3363
3364 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3365 $resql = $this->db->query($sql);
3366 if ($resql) {
3367 $nump = $this->db->num_rows($resql);
3368 if ($nump) {
3369 $i = 0;
3370 while ($i < $nump) {
3371 $obj = $this->db->fetch_object($resql);
3372 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3373 $i++;
3374 }
3375 }
3376 } else {
3377 dol_print_error($this->db);
3378 }
3379 return $contacts;
3380 }
3381
3382 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3388 public function contact_array_objects()
3389 {
3390 // phpcs:enable
3391 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3392 $contacts = array();
3393
3394 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3395 $resql = $this->db->query($sql);
3396 if ($resql) {
3397 $nump = $this->db->num_rows($resql);
3398 if ($nump) {
3399 $i = 0;
3400 while ($i < $nump) {
3401 $obj = $this->db->fetch_object($resql);
3402 $contact = new Contact($this->db);
3403 $contact->fetch($obj->rowid);
3404 $contacts[] = $contact;
3405 $i++;
3406 }
3407 }
3408 } else {
3409 dol_print_error($this->db);
3410 }
3411 return $contacts;
3412 }
3413
3414 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3422 public function contact_get_property($rowid, $mode)
3423 {
3424 // phpcs:enable
3425 $contact_property = '';
3426
3427 if (empty($rowid)) {
3428 return '';
3429 }
3430
3431 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3432 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3433 $sql .= " WHERE rowid = ".((int) $rowid);
3434
3435 $resql = $this->db->query($sql);
3436 if ($resql) {
3437 $nump = $this->db->num_rows($resql);
3438
3439 if ($nump) {
3440 $obj = $this->db->fetch_object($resql);
3441
3442 if ($mode == 'email') {
3443 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3444 } elseif ($mode == 'mobile') {
3445 $contact_property = $obj->phone_mobile;
3446 }
3447 }
3448 return $contact_property;
3449 } else {
3450 dol_print_error($this->db);
3451 }
3452
3453 return '';
3454 }
3455
3456
3457 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3464 public function display_rib($mode = 'label')
3465 {
3466 // phpcs:enable
3467 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3468
3469 $bac = new CompanyBankAccount($this->db);
3470 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3471 $bac->fetch(0, '', $this->id);
3472
3473 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3474 if ($mode == 'label') {
3475 return $bac->getRibLabel(true);
3476 } elseif ($mode == 'rum') {
3477 if (empty($bac->rum)) {
3478 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3479 $prelevement = new BonPrelevement($this->db);
3480 $bac->fetch_thirdparty();
3481 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3482 }
3483 return $bac->rum;
3484 } elseif ($mode == 'format') {
3485 return $bac->frstrecur;
3486 } else {
3487 return 'BadParameterToFunctionDisplayRib';
3488 }
3489 } else {
3490 return '';
3491 }
3492 }
3493
3494 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3500 public function get_all_rib()
3501 {
3502 // phpcs:enable
3503 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3504 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3505 $result = $this->db->query($sql);
3506 if (!$result) {
3507 $this->error = $this->db->lasterror();
3508 $this->errors[] = $this->db->lasterror();
3509 return 0;
3510 } else {
3511 $num_rows = $this->db->num_rows($result);
3512 $rib_array = array();
3513 if ($num_rows) {
3514 while ($obj = $this->db->fetch_object($result)) {
3515 $rib = new CompanyBankAccount($this->db);
3516 $rib->fetch($obj->rowid);
3517 $rib_array[] = $rib;
3518 }
3519 }
3520 return $rib_array;
3521 }
3522 }
3523
3527 public function getDefaultRib()
3528 {
3529 // phpcs:enable
3530 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3531 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND default_rib = 1 AND fk_soc = ". (int) $this->id;
3532 $resql = $this->db->query($sql);
3533 if (!$resql) {
3534 $this->error = $this->db->lasterror();
3535 $this->errors[] = $this->db->lasterror();
3536 return -1;
3537 } else {
3538 $num_rows = $this->db->num_rows($resql);
3539 $rib_array = array();
3540 if ($num_rows) {
3541 while ($obj = $this->db->fetch_object($resql)) {
3542 return $obj->rowid;
3543 }
3544 }
3545 return 0;
3546 }
3547 }
3548
3549
3550 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3559 public function get_codeclient($objsoc = null, $type = 0)
3560 {
3561 // phpcs:enable
3562 global $conf;
3563 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3564 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3565
3566 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3567 foreach ($dirsociete as $dirroot) {
3568 $res = dol_include_once($dirroot.$module.'.php');
3569 if ($res) {
3570 break;
3571 }
3572 }
3574 $mod = new $module($this->db);
3575 '@phan-var-force ModeleThirdPartyCode $mod';
3576
3577 $this->code_client = $mod->getNextValue($objsoc, $type);
3578 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3579
3580 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3581 }
3582 }
3583
3584 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3593 public function get_codefournisseur($objsoc = null, $type = 1)
3594 {
3595 // phpcs:enable
3596 global $conf;
3597 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3598 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3599
3600 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3601 foreach ($dirsociete as $dirroot) {
3602 $res = dol_include_once($dirroot.$module.'.php');
3603 if ($res) {
3604 break;
3605 }
3606 }
3608 $mod = new $module($this->db);
3609 '@phan-var-force ModeleThirdPartyCode $mod';
3610
3611 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3612
3613 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3614 }
3615 }
3616
3617 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3624 public function codeclient_modifiable()
3625 {
3626 // phpcs:enable
3627 global $conf;
3628 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3629 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3630
3631 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3632 foreach ($dirsociete as $dirroot) {
3633 $res = dol_include_once($dirroot.$module.'.php');
3634 if ($res) {
3635 break;
3636 }
3637 }
3638
3639 $mod = new $module($this->db);
3640 '@phan-var-force ModeleThirdPartyCode $mod';
3641
3642 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3643 if ($mod->code_modifiable_null && !$this->code_client) {
3644 return 1;
3645 }
3646 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3647 return 1;
3648 }
3649 if ($mod->code_modifiable) {
3650 return 1; // A mettre en dernier
3651 }
3652 return 0;
3653 } else {
3654 return 0;
3655 }
3656 }
3657
3658
3659 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3666 {
3667 // phpcs:enable
3668 global $conf;
3669 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3670 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3671
3672 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3673 foreach ($dirsociete as $dirroot) {
3674 $res = dol_include_once($dirroot.$module.'.php');
3675 if ($res) {
3676 break;
3677 }
3678 }
3679
3680 $mod = new $module($this->db);
3681 '@phan-var-force ModeleThirdPartyCode $mod';
3682
3683 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3684 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3685 return 1;
3686 }
3687 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3688 return 1;
3689 }
3690 if ($mod->code_modifiable) {
3691 return 1; // A mettre en dernier
3692 }
3693 return 0;
3694 } else {
3695 return 0;
3696 }
3697 }
3698
3699
3700 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3712 public function check_codeclient()
3713 {
3714 // phpcs:enable
3715 global $conf;
3716 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3717 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3718
3719 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3720 foreach ($dirsociete as $dirroot) {
3721 $res = dol_include_once($dirroot.$module.'.php');
3722 if ($res) {
3723 break;
3724 }
3725 }
3726
3727 $mod = new $module($this->db);
3728 '@phan-var-force ModeleThirdPartyCode $mod';
3729
3730 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3731 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3732 if ($result) { // If error
3733 $this->error = $mod->error;
3734 $this->errors = $mod->errors;
3735 }
3736 return $result;
3737 } else {
3738 return 0;
3739 }
3740 }
3741
3742 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3754 public function check_codefournisseur()
3755 {
3756 // phpcs:enable
3757 global $conf;
3758 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3759 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3760
3761 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3762 foreach ($dirsociete as $dirroot) {
3763 $res = dol_include_once($dirroot.$module.'.php');
3764 if ($res) {
3765 break;
3766 }
3767 }
3768
3769 $mod = new $module($this->db);
3770 '@phan-var-force ModeleThirdPartyCode $mod';
3771
3772 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3773 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3774 if ($result) { // If error
3775 $this->error = $mod->error;
3776 $this->errors = $mod->errors;
3777 }
3778 return $result;
3779 } else {
3780 return 0;
3781 }
3782 }
3783
3784 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3793 public function get_codecompta($type)
3794 {
3795 // phpcs:enable
3796 global $conf;
3797
3798 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3799 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
3800 $res = false;
3801 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3802 foreach ($dirsociete as $dirroot) {
3803 $res = dol_include_once($dirroot.$module.'.php');
3804 if ($res) {
3805 break;
3806 }
3807 }
3808
3809 if ($res) {
3810 $mod = new $module();
3811 '@phan-var-force ModeleAccountancyCode $mod';
3812
3813 // Set code count in $mod->code
3814 $result = $mod->get_code($this->db, $this, $type);
3815
3816 if ($type == 'customer') {
3817 $this->code_compta_client = $mod->code;
3818 } elseif ($type == 'supplier') {
3819 $this->code_compta_fournisseur = $mod->code;
3820 }
3821
3822 return $result;
3823 } else {
3824 $this->error = 'ErrorAccountancyCodeNotDefined';
3825 return -1;
3826 }
3827 } else {
3828 if ($type == 'customer') {
3829 $this->code_compta_client = '';
3830 } elseif ($type == 'supplier') {
3831 $this->code_compta_fournisseur = '';
3832 }
3833
3834 return 0;
3835 }
3836 }
3837
3844 public function setParent($id)
3845 {
3846 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3847
3848 if ($this->id) {
3849 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3850 if ($id > 0) {
3851 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3852 if ($sameparent < 0) {
3853 return -1;
3854 }
3855 if ($sameparent == 1) {
3856 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3857 return -1;
3858 }
3859 }
3860
3861 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3862
3863 $resql = $this->db->query($sql);
3864 if ($resql) {
3865 $this->parent = $id;
3866 return 1;
3867 } else {
3868 return -1;
3869 }
3870 }
3871
3872 return -1;
3873 }
3874
3883 public function validateFamilyTree($idparent, $idchild, $counter = 0)
3884 {
3885 if ($counter > 100) {
3886 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3887 }
3888
3889 $sql = 'SELECT s.parent';
3890 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3891 $sql .= ' WHERE rowid = '.((int) $idparent);
3892 $resql = $this->db->query($sql);
3893 if ($resql) {
3894 $obj = $this->db->fetch_object($resql);
3895
3896 if ($obj->parent == '') {
3897 return 0;
3898 } elseif ($obj->parent == $idchild) {
3899 return 1;
3900 } else {
3901 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3902 }
3903 return $sameparent;
3904 } else {
3905 return -1;
3906 }
3907 }
3908
3916 public function getParentsForCompany($company_id, $parents = array())
3917 {
3918 global $langs;
3919
3920 if ($company_id > 0) {
3921 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3922 $resql = $this->db->query($sql);
3923 if ($resql) {
3924 if ($obj = $this->db->fetch_object($resql)) {
3925 $parent = $obj->parent;
3926 if ($parent > 0 && !in_array($parent, $parents)) {
3927 $parents[] = $parent;
3928 return $this->getParentsForCompany($parent, $parents);
3929 } else {
3930 return $parents;
3931 }
3932 }
3933 $this->db->free($resql);
3934 } else {
3935 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3936 }
3937 }
3938 // Return a default value when $company_id is not greater than 0
3939 return array();
3940 }
3941
3942 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3949 public function id_prof_verifiable($idprof)
3950 {
3951 // phpcs:enable
3952 global $conf;
3953
3954 switch ($idprof) {
3955 case 1:
3956 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
3957 break;
3958 case 2:
3959 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
3960 break;
3961 case 3:
3962 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
3963 break;
3964 case 4:
3965 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
3966 break;
3967 case 5:
3968 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
3969 break;
3970 case 6:
3971 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
3972 break;
3973 default:
3974 $ret = false;
3975 }
3976
3977 return $ret;
3978 }
3979
3980 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3989 public function id_prof_exists($idprof, $value, $socid = 0)
3990 {
3991 // phpcs:enable
3992 $field = $idprof;
3993
3994 switch ($idprof) { // For backward compatibility
3995 case '1':
3996 case 'idprof1':
3997 $field = "siren";
3998 break;
3999 case '2':
4000 case 'idprof2':
4001 $field = "siret";
4002 break;
4003 case '3':
4004 case 'idprof3':
4005 $field = "ape";
4006 break;
4007 case '4':
4008 case 'idprof4':
4009 $field = "idprof4";
4010 break;
4011 case '5':
4012 $field = "idprof5";
4013 break;
4014 case '6':
4015 $field = "idprof6";
4016 break;
4017 }
4018
4019 //Verify duplicate entries
4020 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
4021 if ($socid) {
4022 $sql .= " AND rowid <> ".$socid;
4023 }
4024 $resql = $this->db->query($sql);
4025 if ($resql) {
4026 $obj = $this->db->fetch_object($resql);
4027 $count = $obj->nb;
4028 } else {
4029 $count = 0;
4030 print $this->db->error();
4031 }
4032 $this->db->free($resql);
4033
4034 if ($count > 0) {
4035 return true;
4036 } else {
4037 return false;
4038 }
4039 }
4040
4041 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4050 public function id_prof_check($idprof, $soc)
4051 {
4052 // phpcs:enable
4053 global $conf;
4054
4055 // load the library necessary to check the professional identifiers
4056 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4057
4058 $ok = 1;
4059
4060 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4061 return 1;
4062 }
4063
4064 // Check SIREN
4065 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
4066 return -1;
4067 }
4068
4069 // Check SIRET
4070 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
4071 return -1;
4072 }
4073
4074 //Verify CIF/NIF/NIE if pays ES
4075 if ($idprof == 1 && $soc->country_code == 'ES') {
4076 return isValidTinForES($this->idprof1);
4077 }
4078
4079 //Verify NIF if country is PT
4080 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
4081 return -1;
4082 }
4083
4084 //Verify NIF if country is DZ
4085 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
4086 return -1;
4087 }
4088
4089 //Verify ID Prof 1 if country is BE
4090 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
4091 return -1;
4092 }
4093
4094 return $ok;
4095 }
4096
4097 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4106 public function id_prof_url($idprof, $thirdparty)
4107 {
4108 // phpcs:enable
4109 global $conf, $langs, $hookmanager;
4110
4111 $url = '';
4112 $action = '';
4113
4114 $hookmanager->initHooks(array('idprofurl'));
4115 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4116 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4117 if (empty($reshook)) {
4118 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4119 return '';
4120 }
4121
4122 // TODO Move links to validate professional ID into a dictionary table "country" + "link"
4123 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4124 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4125 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
4126 }
4127 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4128 $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
4129 }
4130 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4131 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
4132 }
4133 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4134 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4135 }
4136 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4137 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
4138 }
4139 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4140 $url = 'http://www.nif.pt/'.$strippedIdProf1;
4141 }
4142
4143 if ($url) {
4144 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4145 }
4146 } else {
4147 return $hookmanager->resPrint;
4148 }
4149
4150 return '';
4151 }
4152
4153 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4159 public function has_projects()
4160 {
4161 // phpcs:enable
4162 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4163 $resql = $this->db->query($sql);
4164 if ($resql) {
4165 $obj = $this->db->fetch_object($resql);
4166 $count = $obj->numproj;
4167 } else {
4168 $count = 0;
4169 print $this->db->error();
4170 }
4171 $this->db->free($resql);
4172 return ($count > 0);
4173 }
4174
4175
4182 public function info($id)
4183 {
4184 $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4185 $sql .= " fk_user_creat, fk_user_modif";
4186 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4187 $sql .= " WHERE s.rowid = ".((int) $id);
4188
4189 $result = $this->db->query($sql);
4190 if ($result) {
4191 if ($this->db->num_rows($result)) {
4192 $obj = $this->db->fetch_object($result);
4193
4194 $this->id = $obj->rowid;
4195
4196 $this->user_creation_id = $obj->fk_user_creat;
4197 $this->user_modification_id = $obj->fk_user_modif;
4198 $this->date_creation = $this->db->jdate($obj->datec);
4199 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4200
4201 $this->ref = $obj->name;
4202 }
4203
4204 $this->db->free($result);
4205 } else {
4206 dol_print_error($this->db);
4207 }
4208 }
4209
4215 public function isACompany()
4216 {
4217 // Define if third party is treated as company (or not) when nature is unknown
4218 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES');
4219
4220 // Now try to guess using different tips
4221 if (!empty($this->tva_intra)) {
4222 $isACompany = 1;
4223 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4224 $isACompany = 1;
4225 } else {
4226 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) {
4227 // TODO Add a field is_a_company into dictionary
4228 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4229 $isACompany = 0;
4230 } else {
4231 $isACompany = 1;
4232 }
4233 } else {
4234 $isACompany = 1;
4235 }
4236 }
4237
4238 return (bool) $isACompany;
4239 }
4240
4246 public function isInEEC()
4247 {
4248 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4249 return isInEEC($this);
4250 }
4251
4252 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4258 public function LoadSupplierCateg()
4259 {
4260 // phpcs:enable
4261 $this->SupplierCategories = array();
4262 $sql = "SELECT rowid, label";
4263 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4264 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4265
4266 $resql = $this->db->query($sql);
4267 if ($resql) {
4268 while ($obj = $this->db->fetch_object($resql)) {
4269 $this->SupplierCategories[$obj->rowid] = $obj->label;
4270 }
4271 return 0;
4272 } else {
4273 return -1;
4274 }
4275 }
4276
4277 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4284 public function AddFournisseurInCategory($categorie_id)
4285 {
4286 // phpcs:enable
4287 if ($categorie_id > 0 && $this->id > 0) {
4288 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4289 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4290
4291 if ($resql = $this->db->query($sql)) {
4292 return 0;
4293 }
4294 } else {
4295 return 0;
4296 }
4297 return -1;
4298 }
4299
4305 public function getNbOfEMailings()
4306 {
4307 $sql = "SELECT count(mc.email) as nb";
4308 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4309 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4310 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4311
4312 $resql = $this->db->query($sql);
4313 if ($resql) {
4314 $obj = $this->db->fetch_object($resql);
4315 $nb = $obj->nb;
4316
4317 $this->db->free($resql);
4318 return $nb;
4319 } else {
4320 $this->error = $this->db->error();
4321 return -1;
4322 }
4323 }
4324
4331 public function setNoEmail($no_email)
4332 {
4333 $error = 0;
4334
4335 // Update mass emailing flag into table mailing_unsubscribe
4336 if ($this->email) {
4337 $this->db->begin();
4338
4339 if ($no_email) {
4340 $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)."'";
4341 $resql = $this->db->query($sql);
4342 if ($resql) {
4343 $obj = $this->db->fetch_object($resql);
4344 $noemail = $obj->nb;
4345 if (empty($noemail)) {
4346 $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())."')";
4347 $resql = $this->db->query($sql);
4348 if (!$resql) {
4349 $error++;
4350 $this->error = $this->db->lasterror();
4351 $this->errors[] = $this->error;
4352 }
4353 }
4354 } else {
4355 $error++;
4356 $this->error = $this->db->lasterror();
4357 $this->errors[] = $this->error;
4358 }
4359 } else {
4360 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4361 $resql = $this->db->query($sql);
4362 if (!$resql) {
4363 $error++;
4364 $this->error = $this->db->lasterror();
4365 $this->errors[] = $this->error;
4366 }
4367 }
4368
4369 if (empty($error)) {
4370 $this->no_email = $no_email;
4371 $this->db->commit();
4372 return 1;
4373 } else {
4374 $this->db->rollback();
4375 return $error * -1;
4376 }
4377 }
4378
4379 return 0;
4380 }
4381
4388 public function getNoEmail()
4389 {
4390 if ($this->email) {
4391 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4392 $resql = $this->db->query($sql);
4393 if ($resql) {
4394 $obj = $this->db->fetch_object($resql);
4395 $this->no_email = $obj->nb;
4396 return 1;
4397 } else {
4398 $this->error = $this->db->lasterror();
4399 $this->errors[] = $this->error;
4400 return -1;
4401 }
4402 }
4403 return 0;
4404 }
4405
4406 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4416 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4417 {
4418 // phpcs:enable
4419 global $conf, $user, $langs;
4420
4421 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4422 $fullname = $member->getFullName($langs);
4423
4424 if ($member->morphy == 'mor') {
4425 if (empty($socname)) {
4426 $socname = $member->company ? $member->company : $member->societe;
4427 }
4428 if (!empty($fullname) && empty($socalias)) {
4429 $socalias = $fullname;
4430 }
4431 } elseif (empty($socname) && $member->morphy == 'phy') {
4432 if (empty($socname)) {
4433 $socname = $fullname;
4434 }
4435 if (!empty($member->company) && empty($socalias)) {
4436 $socalias = $member->company;
4437 }
4438 }
4439
4440 $name = $socname;
4441 $alias = $socalias ? $socalias : '';
4442
4443 // Positionne parameters
4444 $this->nom = $name; // TODO deprecated
4445 $this->name = $name;
4446 $this->name_alias = $alias;
4447 $this->address = $member->address;
4448 $this->zip = $member->zip;
4449 $this->town = $member->town;
4450 $this->country_code = $member->country_code;
4451 $this->country_id = $member->country_id;
4452 $this->phone = $member->phone; // Prof phone
4453 $this->email = $member->email;
4454 $this->socialnetworks = $member->socialnetworks;
4455 $this->entity = $member->entity;
4456
4457 $this->client = 1; // A member is a customer by default
4458 $this->code_client = ($customercode ? $customercode : -1);
4459 $this->code_fournisseur = '-1';
4460 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4461 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4462
4463 $this->db->begin();
4464
4465 // Cree et positionne $this->id
4466 $result = $this->create($user);
4467
4468 if ($result >= 0) {
4469 // Auto-create contact on thirdparty creation
4470 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4471 // Fill fields needed by contact
4472 $this->name_bis = $member->lastname;
4473 $this->firstname = $member->firstname;
4474 $this->civility_id = $member->civility_id;
4475
4476 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4477 $result = $this->create_individual($user);
4478
4479 if ($result < 0) {
4480 setEventMessages($this->error, $this->errors, 'errors');
4481 $this->db->rollback();
4482 return -1;
4483 }
4484 }
4485
4486 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4487 $sql .= " SET fk_soc = ".((int) $this->id);
4488 $sql .= " WHERE rowid = ".((int) $member->id);
4489
4490 $resql = $this->db->query($sql);
4491 if ($resql) {
4492 $this->db->commit();
4493 return $this->id;
4494 } else {
4495 $this->error = $this->db->error();
4496
4497 $this->db->rollback();
4498 return -1;
4499 }
4500 } else {
4501 // $this->error deja positionne
4502 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4503
4504 $this->db->rollback();
4505 return $result;
4506 }
4507 }
4508
4515 public function setMysoc(Conf $conf)
4516 {
4517 global $langs;
4518
4519 $this->id = 0;
4520 $this->entity = $conf->entity;
4521 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4522 $this->nom = $this->name; // deprecated
4523 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4524 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4525 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4526 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4527
4528 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4529
4530 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4531
4532 // We define country_id, country_code and country
4533 $country_id = 0;
4534 $country_code = $country_label = '';
4535 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4536 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4537 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4538 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4539 $country_code = $tmp[1];
4540 $country_label = $tmp[2];
4541 } else {
4542 // For backward compatibility
4543 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4544 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4545 $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
4546 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4547 }
4548 }
4549 $this->country_id = $country_id;
4550 $this->country_code = $country_code;
4551 $this->country = $country_label;
4552 if (is_object($langs)) {
4553 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4554 }
4555
4556 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4557 // We define state_id, state_code and state
4558 $state_id = 0;
4559 $state_code = '';
4560 $state_label = '';
4561 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4562 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4563 $state_id = (int) $tmp[0];
4564 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4565 $state_code = $tmp[1];
4566 $state_label = $tmp[2];
4567 } else { // For backward compatibility
4568 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);
4569 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4570 $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
4571 $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
4572 }
4573 }
4574 $this->state_id = $state_id;
4575 $this->state_code = $state_code;
4576 $this->state = $state_label;
4577 if (is_object($langs)) {
4578 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4579 }
4580
4581 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4582 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4583 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4584 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4585
4586 // Social networks
4587 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4588 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4589 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4590 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4591 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4592 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4593 $this->socialnetworks = array();
4594 if (!empty($facebook_url)) {
4595 $this->socialnetworks['facebook'] = $facebook_url;
4596 }
4597 if (!empty($twitter_url)) {
4598 $this->socialnetworks['twitter'] = $twitter_url;
4599 }
4600 if (!empty($linkedin_url)) {
4601 $this->socialnetworks['linkedin'] = $linkedin_url;
4602 }
4603 if (!empty($instagram_url)) {
4604 $this->socialnetworks['instagram'] = $instagram_url;
4605 }
4606 if (!empty($youtube_url)) {
4607 $this->socialnetworks['youtube'] = $youtube_url;
4608 }
4609 if (!empty($github_url)) {
4610 $this->socialnetworks['github'] = $github_url;
4611 }
4612
4613 // Id prof generiques
4614 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4615 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4616 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4617 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4618 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4619 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4620 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4621 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4622 $this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;
4623 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4624 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4625 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4626 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4627 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4628 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4629 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4630 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4631 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4632
4633 // Define if company use vat or not
4634 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4635
4636 // Define if company use local taxes
4637 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4638 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4639 }
4640
4648 public function initAsSpecimen()
4649 {
4650 $now = dol_now();
4651
4652 // Initialize parameters
4653 $this->id = 0;
4654 $this->entity = 1;
4655 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4656 $this->nom = $this->name; // For backward compatibility
4657 $this->ref_ext = 'Ref ext';
4658 $this->specimen = 1;
4659 $this->address = '21 jump street';
4660 $this->zip = '99999';
4661 $this->town = 'MyTown';
4662 $this->state_id = 1;
4663 $this->state_code = 'AA';
4664 $this->state = 'MyState';
4665 $this->country_id = 1;
4666 $this->country_code = 'FR';
4667 $this->email = 'specimen@specimen.com';
4668 $this->socialnetworks = array(
4669 'skype' => 'skypepseudo',
4670 'twitter' => 'twitterpseudo',
4671 'facebook' => 'facebookpseudo',
4672 'linkedin' => 'linkedinpseudo',
4673 );
4674 $this->url = 'http://www.specimen.com';
4675
4676 $this->phone = '0909090901';
4677 $this->phone_mobile = '0909090901';
4678 $this->fax = '0909090909';
4679
4680 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4681 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4682 $this->typent_code = 'TE_OTHER';
4683 $this->capital = 10000;
4684 $this->client = 1;
4685 $this->prospect = 1;
4686 $this->fournisseur = 1;
4687 $this->tva_assuj = 1;
4688 $this->tva_intra = 'EU1234567';
4689 $this->note_public = 'This is a comment (public)';
4690 $this->note_private = 'This is a comment (private)';
4691
4692 $this->idprof1 = 'idprof1';
4693 $this->idprof2 = 'idprof2';
4694 $this->idprof3 = 'idprof3';
4695 $this->idprof4 = 'idprof4';
4696 $this->idprof5 = 'idprof5';
4697 $this->idprof6 = 'idprof6';
4698
4699 return 1;
4700 }
4701
4708 public function useLocalTax($localTaxNum = 0)
4709 {
4710 $sql = "SELECT t.localtax1, t.localtax2";
4711 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4712 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4713 $sql .= " AND t.active = 1";
4714 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4715 if (empty($localTaxNum)) {
4716 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4717 } elseif ($localTaxNum == 1) {
4718 $sql .= " AND t.localtax1_type <> '0'";
4719 } elseif ($localTaxNum == 2) {
4720 $sql .= " AND t.localtax2_type <> '0'";
4721 }
4722
4723 $resql = $this->db->query($sql);
4724 if ($resql) {
4725 return ($this->db->num_rows($resql) > 0);
4726 } else {
4727 return false;
4728 }
4729 }
4730
4736 public function useNPR()
4737 {
4738 $sql = "SELECT t.rowid";
4739 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4740 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4741 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4742 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4743
4744 dol_syslog("useNPR", LOG_DEBUG);
4745 $resql = $this->db->query($sql);
4746 if ($resql) {
4747 return ($this->db->num_rows($resql) > 0);
4748 } else {
4749 return false;
4750 }
4751 }
4752
4759 public function useRevenueStamp()
4760 {
4761 $sql = "SELECT COUNT(*) as nb";
4762 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4763 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4764 $sql .= " AND r.active = 1";
4765
4766 dol_syslog("useRevenueStamp", LOG_DEBUG);
4767 $resql = $this->db->query($sql);
4768 if ($resql) {
4769 $obj = $this->db->fetch_object($resql);
4770 return ($obj->nb > 0);
4771 } else {
4772 $this->error = $this->db->lasterror();
4773 return false;
4774 }
4775 }
4776
4782 public function getLibProspLevel()
4783 {
4784 return $this->LibProspLevel($this->fk_prospectlevel);
4785 }
4786
4787 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4794 public function LibProspLevel($fk_prospectlevel)
4795 {
4796 // phpcs:enable
4797 global $langs;
4798
4799 $label = '';
4800 if ($fk_prospectlevel != '') {
4801 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
4802 // If label is not found in language file, we get label from cache/database
4803 if ($label == "ProspectLevel".$fk_prospectlevel) {
4804 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4805 }
4806 }
4807
4808 return $label;
4809 }
4810
4818 public function getLibProspCommStatut($mode = 0, $label = '')
4819 {
4820 return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4821 }
4822
4823 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4837 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4838 {
4839 // phpcs:enable
4840 global $langs;
4841
4842 $langs->load('customers');
4843
4844 if ($mode == 2) {
4845 if ($status == '-1' || $status == 'ST_NO') {
4846 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4847 } elseif ($status == '0' || $status == 'ST_NEVER') {
4848 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4849 } elseif ($status == '1' || $status == 'ST_TODO') {
4850 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4851 } elseif ($status == '2' || $status == 'ST_PEND') {
4852 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4853 } elseif ($status == '3' || $status == 'ST_DONE') {
4854 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4855 } else {
4856 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);
4857 }
4858 } elseif ($mode == 3) {
4859 if ($status == '-1' || $status == 'ST_NO') {
4860 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
4861 } elseif ($status == '0' || $status == 'ST_NEVER') {
4862 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
4863 } elseif ($status == '1' || $status == 'ST_TODO') {
4864 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
4865 } elseif ($status == '2' || $status == 'ST_PEND') {
4866 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
4867 } elseif ($status == '3' || $status == 'ST_DONE') {
4868 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
4869 } else {
4870 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
4871 }
4872 } elseif ($mode == 4) {
4873 if ($status == '-1' || $status == 'ST_NO') {
4874 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4875 } elseif ($status == '0' || $status == 'ST_NEVER') {
4876 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4877 } elseif ($status == '1' || $status == 'ST_TODO') {
4878 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4879 } elseif ($status == '2' || $status == 'ST_PEND') {
4880 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4881 } elseif ($status == '3' || $status == 'ST_DONE') {
4882 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4883 } else {
4884 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);
4885 }
4886 }
4887
4888 return "Error, mode/status not found";
4889 }
4890
4897 public function getOutstandingProposals($mode = 'customer')
4898 {
4899 $table = 'propal';
4900 if ($mode == 'supplier') {
4901 $table = 'supplier_proposal';
4902 }
4903
4904 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4905 $sql .= " WHERE fk_soc = ".((int) $this->id);
4906 if ($mode == 'supplier') {
4907 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4908 } else {
4909 $sql .= " AND entity IN (".getEntity('propal').")";
4910 }
4911
4912 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4913
4914 $resql = $this->db->query($sql);
4915 if ($resql) {
4916 $outstandingOpened = 0;
4917 $outstandingTotal = 0;
4918 $outstandingTotalIncTax = 0;
4919 $arrayofref = array();
4920 while ($obj = $this->db->fetch_object($resql)) {
4921 $arrayofref[$obj->rowid] = $obj->ref;
4922 $outstandingTotal += $obj->total_ht;
4923 $outstandingTotalIncTax += $obj->total_ttc;
4924 if ($obj->status != 0) {
4925 // Not a draft
4926 $outstandingOpened += $obj->total_ttc;
4927 }
4928 }
4929 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4930 } else {
4931 return array();
4932 }
4933 }
4934
4941 public function getOutstandingOrders($mode = 'customer')
4942 {
4943 $table = 'commande';
4944 if ($mode == 'supplier') {
4945 $table = 'commande_fournisseur';
4946 }
4947
4948 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4949 $sql .= " WHERE fk_soc = ".((int) $this->id);
4950 if ($mode == 'supplier') {
4951 $sql .= " AND entity IN (".getEntity('supplier_order').")";
4952 } else {
4953 $sql .= " AND entity IN (".getEntity('commande').")";
4954 }
4955
4956 dol_syslog("getOutstandingOrders", LOG_DEBUG);
4957 $resql = $this->db->query($sql);
4958 if ($resql) {
4959 $outstandingOpened = 0;
4960 $outstandingTotal = 0;
4961 $outstandingTotalIncTax = 0;
4962 $arrayofref = array();
4963 while ($obj = $this->db->fetch_object($resql)) {
4964 $arrayofref[$obj->rowid] = $obj->ref;
4965 $outstandingTotal += $obj->total_ht;
4966 $outstandingTotalIncTax += $obj->total_ttc;
4967 if ($obj->status != 0) {
4968 // Not a draft
4969 $outstandingOpened += $obj->total_ttc;
4970 }
4971 }
4972 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4973 } else {
4974 return array();
4975 }
4976 }
4977
4985 public function getOutstandingBills($mode = 'customer', $late = 0)
4986 {
4987 $table = 'facture';
4988 if ($mode == 'supplier') {
4989 $table = 'facture_fourn';
4990 }
4991
4992 /* Accurate value of remain to pay is to sum remaintopay for each invoice
4993 $paiement = $invoice->getSommePaiement();
4994 $creditnotes=$invoice->getSumCreditNotesUsed();
4995 $deposits=$invoice->getSumDepositsUsed();
4996 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4997 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4998 */
4999 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
5000 $sql .= " WHERE fk_soc = ".((int) $this->id);
5001 if (!empty($late)) {
5002 $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
5003 }
5004 if ($mode == 'supplier') {
5005 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
5006 } else {
5007 $sql .= " AND entity IN (".getEntity('invoice').")";
5008 }
5009
5010 dol_syslog("getOutstandingBills", LOG_DEBUG);
5011 $resql = $this->db->query($sql);
5012 if ($resql) {
5013 $outstandingOpened = 0;
5014 $outstandingTotal = 0;
5015 $outstandingTotalIncTax = 0;
5016 $arrayofref = array();
5017 $arrayofrefopened = array();
5018 if ($mode == 'supplier') {
5019 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5020 $tmpobject = new FactureFournisseur($this->db);
5021 } else {
5022 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
5023 $tmpobject = new Facture($this->db);
5024 }
5025 while ($obj = $this->db->fetch_object($resql)) {
5026 $arrayofref[$obj->rowid] = $obj->ref;
5027 $tmpobject->id = $obj->rowid;
5028
5029 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5030 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5031 ) {
5032 $outstandingTotal += $obj->total_ht;
5033 $outstandingTotalIncTax += $obj->total_ttc;
5034 }
5035
5036 $remaintopay = 0;
5037
5038 if ($obj->paye == 0
5039 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5040 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5041 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5042 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5043 $paiement = $tmpobject->getSommePaiement();
5044 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5045 $deposits = $tmpobject->getSumDepositsUsed();
5046
5047 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5048 $outstandingOpened += $remaintopay;
5049 }
5050
5051 //if credit note is converted but not used
5052 // TODO Do this also for customer ?
5053 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5054 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5055 $remaintopay -= $remainingcreditnote;
5056 $outstandingOpened -= $remainingcreditnote;
5057 }
5058
5059 if ($remaintopay) {
5060 $arrayofrefopened[$obj->rowid] = $obj->ref;
5061 }
5062 }
5063 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'incl taxes'
5064 } else {
5065 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5066 return array();
5067 }
5068 }
5069
5076 public function getLibCustProspStatut()
5077 {
5078 return $this->LibCustProspStatut($this->client);
5079 }
5080
5081 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5088 public function LibCustProspStatut($status)
5089 {
5090 // phpcs:enable
5091 global $langs;
5092 $langs->load('companies');
5093
5094 if ($status == 0) {
5095 return $langs->trans("NorProspectNorCustomer");
5096 } elseif ($status == 1) {
5097 return $langs->trans("Customer");
5098 } elseif ($status == 2) {
5099 return $langs->trans("Prospect");
5100 } elseif ($status == 3) {
5101 return $langs->trans("ProspectCustomer");
5102 }
5103
5104 return '';
5105 }
5106
5107
5119 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5120 {
5121 global $langs;
5122
5123 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5124 $modelpath = "core/modules/bank/doc/";
5125
5126 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5127 $companybankaccount = new CompanyBankAccount($this->db);
5128 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5129 if (!$result) {
5130 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5131 }
5132 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5133 $this->last_main_doc = $companybankaccount->last_main_doc;
5134 } else {
5135 // Positionne le modele sur le nom du modele a utiliser
5136 if (!dol_strlen($modele)) {
5137 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5138 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5139 } else {
5140 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5141 return 0;
5142 }
5143 }
5144
5145 if (!isset($this->bank_account)) {
5146 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5147 $bac = new CompanyBankAccount($this->db);
5148 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5149 $result = $bac->fetch(0, '', $this->id);
5150 if ($result > 0) {
5151 $this->bank_account = $bac;
5152 } else {
5153 $this->bank_account = '';
5154 }
5155 }
5156
5157 $modelpath = "core/modules/societe/doc/";
5158
5159 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5160 }
5161
5162 return $result;
5163 }
5164
5165
5177 public function setCategories($categories, $type_categ)
5178 {
5179 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5180
5181 // Decode type
5182 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5183 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5184 return -1;
5185 }
5186
5187 return parent::setCategoriesCommon($categories, $type_categ);
5188 }
5189
5197 public function setSalesRep($salesrep, $onlyAdd = false)
5198 {
5199 global $user;
5200
5201 // Handle single user
5202 if (!is_array($salesrep)) {
5203 $salesrep = array($salesrep);
5204 }
5205
5206 $to_del = array(); // Nothing to delete
5207 $to_add = $salesrep;
5208 if ($onlyAdd === false) {
5209 // Get current users
5210 $existing = $this->getSalesRepresentatives($user, 1);
5211
5212 // Diff
5213 if (is_array($existing)) {
5214 $to_del = array_diff($existing, $salesrep);
5215 $to_add = array_diff($salesrep, $existing);
5216 }
5217 }
5218
5219 $error = 0;
5220
5221 // Process
5222 foreach ($to_del as $del) {
5223 $this->del_commercial($user, $del);
5224 }
5225 foreach ($to_add as $add) {
5226 $result = $this->add_commercial($user, $add);
5227 if ($result < 0) {
5228 $error++;
5229 break;
5230 }
5231 }
5232
5233 return $error ? -1 : 1;
5234 }
5235
5242 public function setThirdpartyType($typent_id)
5243 {
5244 global $user;
5245
5246 dol_syslog(__METHOD__, LOG_DEBUG);
5247
5248 if ($this->id) {
5249 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5250
5251 if ($result > 0) {
5252 $this->typent_id = $typent_id;
5253 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5254 return 1;
5255 } else {
5256 return -1;
5257 }
5258 } else {
5259 return -1;
5260 }
5261 }
5262
5272 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5273 {
5274 if ($origin_id == $dest_id) {
5275 dol_syslog('Error: Try to merge a thirdparty into itself');
5276 return false;
5277 }
5278
5279 // 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.
5280 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5281 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5282 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5283 $sql .= ' SELECT fk_user ';
5284 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5285 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5286
5287 $resql = $dbs->query($sql);
5288 while ($obj = $dbs->fetch_object($resql)) {
5289 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5290 }
5291
5292 // 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.
5293 // Do not include llx_societe because it will be replaced later.
5294 $tables = array(
5295 'societe_account',
5296 'societe_commerciaux',
5297 'societe_prices',
5298 'societe_remise',
5299 'societe_remise_except',
5300 'societe_rib'
5301 );
5302
5303 // TODO When we merge societe_account, we may get 2 lines for the stripe account. Must fix this.
5304
5305 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5306 }
5307
5316 public function setAccountancyCode($type, $value)
5317 {
5318 global $user, $langs, $conf;
5319
5320 $this->db->begin();
5321
5322 if ($type == 'buy') {
5323 $field = 'accountancy_code_buy';
5324 } elseif ($type == 'sell') {
5325 $field = 'accountancy_code_sell';
5326 } else {
5327 return -1;
5328 }
5329
5330 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5331 $sql .= $field." = '".$this->db->escape($value)."'";
5332 $sql .= " WHERE rowid = ".((int) $this->id);
5333
5334 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5335 $resql = $this->db->query($sql);
5336
5337 if ($resql) {
5338 // Call triggers
5339 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5340 $interface = new Interfaces($this->db);
5341 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5342 if ($result < 0) {
5343 $this->errors = $interface->errors;
5344 $this->db->rollback();
5345 return -1;
5346 }
5347 // End call triggers
5348
5349 $this->$field = $value;
5350
5351 $this->db->commit();
5352 return 1;
5353 } else {
5354 $this->error = $this->db->lasterror();
5355 $this->db->rollback();
5356 return -1;
5357 }
5358 }
5359
5366 public function fetchPartnerships($mode)
5367 {
5368 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5369
5370 $this->partnerships[] = array();
5371
5372 return 1;
5373 }
5374
5382 public function getKanbanView($option = '', $arraydata = array())
5383 {
5384 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5385
5386 $return = '<div class="box-flex-item box-flex-grow-zero">';
5387 $return .= '<div class="info-box info-box-sm">';
5388 $return .= '<span class="info-box-icon bg-infobox-action">';
5389 $return .= img_picto('', $this->picto);
5390 $return .= '</span>';
5391 $return .= '<div class="info-box-content">';
5392 $return .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref);
5393 $return .= '</div>';
5394 if (!empty($this->phone)) {
5395 $return .= '<div class="inline-block valignmiddle">';
5396 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5397 $return .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
5398 $return .= '</div>';
5399 }
5400 if (!empty($this->email)) {
5401 $return .= '<div class="inline-block valignmiddle">';
5402 $return .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
5403 $return .= '</div>';
5404 }
5405 if ($selected >= 0) {
5406 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5407 }
5408 if (property_exists($this, 'code_client')) {
5409 $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5410 }
5411 if (method_exists($this, 'getLibStatut')) {
5412 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5413 }
5414 $return .= '</div>'; // end info-box-content
5415 $return .= '</div>';
5416 $return .= '</div>';
5417
5418 return $return;
5419 }
5420
5430 public function getContacts($list = 0, $code = '', $element = '')
5431 {
5432 // phpcs:enable
5433 global $langs;
5434
5435 $tab = array();
5436
5437 $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
5438 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5439 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5440 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5441 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5442 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5443 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5444 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5445 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5446 if (!empty($element)) {
5447 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5448 }
5449 if ($code) {
5450 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5451 }
5452 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5453 $sql .= " AND tc.source = 'external'";
5454 $sql .= " AND tc.active = 1";
5455
5456 $sql .= " ORDER BY t.lastname ASC";
5457
5458 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5459 $resql = $this->db->query($sql);
5460 if ($resql) {
5461 $num = $this->db->num_rows($resql);
5462 $i = 0;
5463 while ($i < $num) {
5464 $obj = $this->db->fetch_object($resql);
5465
5466 if (!$list) {
5467 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5468 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5469 $tab[$i] = array(
5470 'source' => $obj->source,
5471 'socid' => $obj->socid,
5472 'id' => $obj->id,
5473 'nom' => $obj->lastname, // For backward compatibility
5474 'civility' => $obj->civility,
5475 'lastname' => $obj->lastname,
5476 'firstname' => $obj->firstname,
5477 'email' => $obj->email,
5478 'login' => (empty($obj->login) ? '' : $obj->login),
5479 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5480 'statuscontact' => $obj->statuscontact,
5481 'rowid' => $obj->rowid,
5482 'code' => $obj->code,
5483 'element' => $obj->element,
5484 'libelle' => $libelle_type,
5485 'status' => $obj->statuslink,
5486 'fk_c_type_contact' => $obj->fk_c_type_contact
5487 );
5488 } else {
5489 $tab[$i] = $obj->id;
5490 }
5491
5492 $i++;
5493 }
5494
5495 return $tab;
5496 } else {
5497 $this->error = $this->db->lasterror();
5498 dol_print_error($this->db);
5499 return -1;
5500 }
5501 }
5502
5513 public function mergeCompany($soc_origin_id)
5514 {
5515 global $conf, $langs, $hookmanager, $user, $action;
5516
5517 $error = 0;
5518 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5519
5520 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5521
5522 if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5523 $this->error = $langs->trans('ErrorRecordNotFound');
5524 $error++;
5525 }
5526
5527 if (!$error) {
5528 $this->db->begin();
5529
5530 // Recopy some data
5531 $this->client |= $soc_origin->client;
5532 $this->fournisseur |= $soc_origin->fournisseur;
5533 $listofproperties = array(
5534 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5535 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5536 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5537 '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',
5538 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5539 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5540 );
5541 foreach ($listofproperties as $property) {
5542 if (empty($this->$property)) {
5543 $this->$property = $soc_origin->$property;
5544 }
5545 }
5546
5547 if ($this->typent_id == -1) {
5548 $this->typent_id = $soc_origin->typent_id;
5549 }
5550
5551 // Concat some data
5552 $listofproperties = array(
5553 'note_public', 'note_private'
5554 );
5555 foreach ($listofproperties as $property) {
5556 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5557 }
5558
5559 // Merge extrafields
5560 if (is_array($soc_origin->array_options)) {
5561 foreach ($soc_origin->array_options as $key => $val) {
5562 if (empty($this->array_options[$key])) {
5563 $this->array_options[$key] = $val;
5564 }
5565 }
5566 }
5567
5568 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5569 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5570 $this->name_bis = $this->name;
5571 }
5572
5573 // Merge categories
5574 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5575 $static_cat = new Categorie($this->db);
5576
5577 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5578 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5579 $custcats = array_merge($custcats, $custcats_ori);
5580 $this->setCategories($custcats, 'customer');
5581
5582 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5583 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5584 $suppcats = array_merge($suppcats, $suppcats_ori);
5585 $this->setCategories($suppcats, 'supplier');
5586
5587 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5588 if ($soc_origin->code_client == $this->code_client
5589 || $soc_origin->code_fournisseur == $this->code_fournisseur
5590 || $soc_origin->barcode == $this->barcode) {
5591 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5592 $soc_origin->code_client = '';
5593 $soc_origin->code_fournisseur = '';
5594 $soc_origin->barcode = '';
5595 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5596 }
5597
5598 // Update
5599 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5600
5601 if ($result < 0) {
5602 $error++;
5603 }
5604
5605 // Move links
5606 if (!$error) {
5607 $objects = array(
5608 'Adherent' => '/adherents/class/adherent.class.php',
5609 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5610 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5611 'Propal' => '/comm/propal/class/propal.class.php',
5612 'Commande' => '/commande/class/commande.class.php',
5613 'Facture' => '/compta/facture/class/facture.class.php',
5614 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5615 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5616 'Contact' => '/contact/class/contact.class.php',
5617 'Contrat' => '/contrat/class/contrat.class.php',
5618 'Expedition' => '/expedition/class/expedition.class.php',
5619 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5620 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5621 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5622 'Reception' => '/reception/class/reception.class.php',
5623 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5624 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5625 'Product' => '/product/class/product.class.php',
5626 //'ProductThirparty' => '...', // for llx_product_thirdparty
5627 'Project' => '/projet/class/project.class.php',
5628 'User' => '/user/class/user.class.php',
5629 'Account' => '/compta/bank/class/account.class.php',
5630 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5631 'Societe' => '/societe/class/societe.class.php',
5632 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
5633 );
5634 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5635 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5636 }
5637 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5638 $objects['Mo'] = '/mrp/class/mo.class.php';
5639 }
5640 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5641 $objects['Don'] = '/don/class/don.class.php';
5642 }
5643 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5644 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5645 }
5646 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5647 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5648 }
5649 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5650 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5651 }
5652
5653 //First, all core objects must update their tables
5654 foreach ($objects as $object_name => $object_file) {
5655 /* $object_file is never an array -> code commented
5656 if (is_array($object_file)) {
5657 if (empty($object_file['enabled'])) {
5658 continue;
5659 }
5660 $object_file = $object_file['file'];
5661 }
5662 */
5663
5664 require_once DOL_DOCUMENT_ROOT.$object_file;
5665
5666 if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5667 $error++;
5668 $this->error = $this->db->lasterror();
5669 break;
5670 }
5671 }
5672 }
5673
5674 // External modules should update their ones too
5675 if (!$error) {
5676 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5677 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5678
5679 if ($reshook < 0) {
5680 $this->error = $hookmanager->error;
5681 $this->errors = $hookmanager->errors;
5682 $error++;
5683 }
5684 }
5685
5686
5687 if (!$error) {
5688 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5689
5690 // Call trigger
5691 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5692 if ($result < 0) {
5693 $error++;
5694 }
5695 // End call triggers
5696 }
5697
5698 if (!$error) {
5699 // Move files from the dir of the third party to delete into the dir of the third party to keep
5700 if (!empty($conf->societe->multidir_output[$this->entity])) {
5701 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5702 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5703
5704 if (dol_is_dir($srcdir)) {
5705 $dirlist = dol_dir_list($srcdir, 'files', 1);
5706 foreach ($dirlist as $filetomove) {
5707 $destfile = $destdir.'/'.$filetomove['relativename'];
5708 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5709 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5710 }
5711 //exit;
5712 }
5713 }
5714 }
5715
5716
5717 if (!$error) {
5718 // We finally remove the old thirdparty
5719 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5720 $this->error = $soc_origin->error;
5721 $this->errors = $soc_origin->errors;
5722 $error++;
5723 }
5724 }
5725
5726 if (!$error) {
5727 $this->db->commit();
5728 return 0;
5729 } else {
5730 $langs->load("errors");
5731 $this->error = $langs->trans('ErrorsThirdpartyMerge');
5732 $this->db->rollback();
5733 return -1;
5734 }
5735 }
5736
5737 return -1;
5738 }
5739}
$object ref
Definition info.php:89
Class to manage members of a foundation.
Class to manage withdrawal receipts.
Class to manage categories.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
setErrorsFromObject($object)
setErrorsFromObject
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
deleteExtraFields()
Delete all extra fields values for the current object.
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage bank accounts description of third parties.
Class to stock current configuration.
Class to manage contact/addresses.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage suppliers invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoices.
Class to manage generation of HTML components Only common components must be here.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Class to manage triggers.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage third parties objects (customers, suppliers, prospects...)
setParent($id)
Define parent company of current company.
getLibProspLevel()
Return prostect level.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
setAsCustomer()
Define third party as a customer.
findNearest($rowid=0, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Search the thirdparty that match the most the provided parameters.
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
contact_get_property($rowid, $mode)
Return property of contact from its id.
check_codeclient()
Check customer code.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
getContacts($list=0, $code='', $element='')
Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for a...
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
get_all_rib()
Return Array of RIB.
get_codecompta($type)
Assigns a accounting code from the accounting code module.
__construct($db)
Constructor.
del_commercial(User $user, $commid)
Add link to sales representative.
info($id)
Load information for tab info.
has_projects()
Indicates if the company has projects.
setThirdpartyType($typent_id)
Define third-party type of current company.
isACompany()
Check if third party is a company (Business) or an end user (Consumer)
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
add_commercial(User $user, $commid)
Add link to sales representative.
LibStatut($status, $mode=0)
Return the label of a given status.
update($id, User $user, $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.
const PROSPECT
Third party type is a prospect.
create(User $user, $notrigger=0)
Create third party in database.
set_as_client()
Define third party as a customer.
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
setCategories($categories, $type_categ)
Sets object to supplied categories.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysocin most cas...
setNoEmail($no_email)
Set "blacklist" mailing status.
id_prof_verifiable($idprof)
Returns if a profid should be verified to be unique.
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
getParentsForCompany($company_id, $parents=array())
Get parents for company.
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0, $price_base_type='HT')
Add a discount for third party.
const CUSTOMER_AND_PROSPECT
Third party type is a customer and a prospect.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
const CUSTOMER
Third party type is a customer.
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='', $is_client=0, $is_supplier=0)
Load a third party from database into memory.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
LoadSupplierCateg()
Load the list of provider categories.
getAvailableDiscounts($user=null, $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company.
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
contact_array_objects()
Return the contact list of this company.
isInEEC()
Return if a company is inside the EEC (European Economic Community)
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
fetchPartnerships($mode)
Function to get partnerships array.
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
mergeCompany($soc_origin_id)
Merge a company with current one, deleting the given company $soc_origin_id.
const NO_SUPPLIER
Third party supplier flag is not supplier.
getNbOfEMailings()
Return number of mass Emailing received by this contacts with its email.
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='', $morecss='')
Return a link on thirdparty (with picto)
getLibStatut($mode=0)
Return label of status (activity, closed)
const NO_CUSTOMER
Third party type is no customer.
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
useLocalTax($localTaxNum=0)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
create_individual(User $user, $no_email=0, $tags=array(), $notrigger=0)
Create a contact/address from thirdparty.
getNoEmail()
get "blacklist" mailing status set no_email attribute to 1 or 0
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
LibCustProspStatut($status)
Return the label of the customer/prospect status.
id_prof_check($idprof, $soc)
Check the validity of a professional identifier according to the country of the company (siren,...
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
setPriceLevel($price_level, User $user)
Set the price level.
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
deprecatedProperties()
Provide list of deprecated properties and replacements.
getTooltipContentArray($params)
getTooltipContentArray
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
getKanbanView($option='', $arraydata=array())
Return clickable link of object (with optional picto)
const SUPPLIER
Third party supplier flag is a supplier.
check_codefournisseur()
Check supplier code.
contact_array()
Return the contact list of this company.
initAsSpecimen()
Initialise an instance with random values.
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
setMysoc(Conf $conf)
Set properties with value into $conf.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
trait CommonSocialNetworks
Superclass for social networks.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
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_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
div refaddress div address
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
isValidSiren($siren)
Check the syntax validity of a SIREN.
isValidTinForPT($str)
Check the syntax validity of a Portuguese (PT) Tax Identification Number (TIN).
isValidSiret($siret)
Check the syntax validity of a SIRET.
isValidTinForES($str)
Check the syntax validity of a Spanish (ES) Tax Identification Number (TIN), where:
isValidTinForBE($str)
Check the syntax validity of a Belgium (BE) Tax Identification Number (TIN).
isValidTinForDZ($str)
Check the syntax validity of an Algerian (DZ) Tax Identification Number (TIN).
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:152