dolibarr 21.0.4
societe.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5 * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2013-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
12 * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16 * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17 * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18 * Copyright (C) 2019-2025 Frédéric France <frederic.france@free.fr>
19 * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20 * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
21 * Copyright (C) 2023-2024 Alexandre Janniaux <alexandre.janniaux@gmail.com>
22 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
23 * Copyright (C) 2024 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'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
959 $this->fields['zip']['showoncombobox'] = getDolGlobalInt('COMPANY_SHOW_ADDRESS_SELECTLIST');
960 $this->fields['town']['showoncombobox'] = getDolGlobalInt('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 if (empty($this->country_id) && !empty($this->country_code)) {
1014 $country_id = getCountry($this->country_code, '3');
1015 $this->country_id = is_int($country_id) ? $country_id : 0;
1016 }
1017
1018 dol_syslog(get_class($this)."::create ".$this->name);
1019
1020 $now = dol_now();
1021
1022 if (empty($this->date_creation)) {
1023 $this->date_creation = $now;
1024 }
1025
1026 $this->db->begin();
1027
1028 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1029 if ($this->code_client == -1 || $this->code_client === 'auto') {
1030 $this->get_codeclient($this, 0);
1031 }
1032 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1033 $this->get_codefournisseur($this, 1);
1034 }
1035
1036 // Check more parameters (including mandatory setup
1037 // If error, this->errors[] is filled
1038 $result = $this->verify();
1039
1040 if ($result >= 0) {
1041 $this->entity = setEntity($this);
1042
1043 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
1044 $sql .= "nom";
1045 $sql .= ", name_alias";
1046 $sql .= ", entity";
1047 $sql .= ", datec";
1048 $sql .= ", fk_user_creat";
1049 $sql .= ", fk_typent";
1050 $sql .= ", canvas";
1051 $sql .= ", status";
1052 $sql .= ", ref_ext";
1053 $sql .= ", fk_stcomm";
1054 $sql .= ", fk_incoterms";
1055 $sql .= ", location_incoterms";
1056 $sql .= ", import_key";
1057 $sql .= ", fk_multicurrency";
1058 $sql .= ", multicurrency_code";
1059 $sql .= ", ip";
1060 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1061 $sql .= ", vat_reverse_charge";
1062 $sql .= ", accountancy_code_buy";
1063 $sql .= ", accountancy_code_sell";
1064 }
1065 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
1066 $sql .= " '".$this->db->escape($this->name_alias)."',";
1067 $sql .= " ".((int) $this->entity).",";
1068 $sql .= " '".$this->db->idate($this->date_creation)."'";
1069 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
1070 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
1071 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
1072 $sql .= ", ".((int) $this->status);
1073 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1074 $sql .= ", 0";
1075 $sql .= ", ".(int) $this->fk_incoterms;
1076 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1077 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1078 $sql .= ", ".(int) $this->fk_multicurrency;
1079 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1080 $sql .= ", '".$this->db->escape($this->ip)."'";
1081 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1082 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1083 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1084 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1085 }
1086 $sql .= ")";
1087
1088 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1089
1090 $result = $this->db->query($sql);
1091 if ($result) {
1092 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1093
1094 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1095
1096 // update accountancy for this entity
1097 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1098 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1099
1100 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1101 $sql .= " fk_soc";
1102 $sql .= ", entity";
1103 $sql .= ", vat_reverse_charge";
1104 $sql .= ", accountancy_code_customer_general";
1105 $sql .= ", accountancy_code_customer";
1106 $sql .= ", accountancy_code_supplier_general";
1107 $sql .= ", accountancy_code_supplier";
1108 $sql .= ", accountancy_code_buy";
1109 $sql .= ", accountancy_code_sell";
1110 $sql .= ") VALUES (";
1111 $sql .= $this->id;
1112 $sql .= ", ".((int) $conf->entity);
1113 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1114 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1115 $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1116 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1117 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1118 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1119 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1120 $sql .= ")";
1121 $result = $this->db->query($sql);
1122 if (!$result) {
1123 $error++;
1124 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1125 }
1126 }
1127
1128 // Ajout du commercial affecte
1129 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1130 $this->add_commercial($user, $this->commercial_id);
1131 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1132 // si un commercial cree un client il lui est affecte automatiquement
1133 $this->add_commercial($user, $user->id);
1134 }
1135
1136 if ($ret >= 0) {
1137 if (! $notrigger) {
1138 // Call trigger
1139 $result = $this->call_trigger('COMPANY_CREATE', $user);
1140 if ($result < 0) {
1141 $error++;
1142 }
1143 // End call triggers
1144 }
1145 } else {
1146 $error++;
1147 }
1148
1149 if (!$error) {
1150 dol_syslog(get_class($this)."::Create success id=".$this->id);
1151 $this->db->commit();
1152 return $this->id;
1153 } else {
1154 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1155 $this->db->rollback();
1156 return -4;
1157 }
1158 } else {
1159 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1160 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1161 $result = -1;
1162 } else {
1163 $this->error = $this->db->lasterror();
1164 $result = -2;
1165 }
1166 $this->db->rollback();
1167 return $result;
1168 }
1169 } else {
1170 $this->db->rollback();
1171 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1172 return -3;
1173 }
1174 }
1175
1176
1177 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1187 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1188 {
1189 global $conf;
1190
1191 $error = 0;
1192
1193 $this->db->begin();
1194
1195 // phpcs:enable
1196 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1197 $contact = new Contact($this->db);
1198
1199 $contact->name = $this->name_bis;
1200 $contact->firstname = $this->firstname;
1201 $contact->civility_id = $this->civility_id;
1202 $contact->socid = $this->id; // fk_soc
1203 $contact->statut = 1; // deprecated
1204 $contact->status = 1;
1205 $contact->priv = 0;
1206 $contact->country_id = $this->country_id;
1207 $contact->state_id = $this->state_id;
1208 $contact->address = $this->address;
1209 $contact->email = $this->email;
1210 $contact->zip = $this->zip;
1211 $contact->town = $this->town;
1212 $this->setUpperOrLowerCase();
1213 $contact->phone_pro = $this->phone;
1214 if (getDolGlobalString('CONTACTS_DEFAULT_ROLES')) {
1215 $contact->roles = explode(',', getDolGlobalString('CONTACTS_DEFAULT_ROLES'));
1216 }
1217
1218 $contactId = $contact->create($user, $notrigger);
1219 if ($contactId < 0) {
1220 $error++;
1221 $this->setErrorsFromObject($contact);
1222 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1223 }
1224
1225 if (empty($error) && is_array($tags) && !empty($tags)) {
1226 $result = $contact->setCategories($tags);
1227 if ($result < 0) {
1228 $error++;
1229 $this->setErrorsFromObject($contact);
1230 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1231 $contactId = $result;
1232 }
1233 }
1234
1235 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1236 $result = $contact->setNoEmail($no_email);
1237 if ($result < 0) {
1238 $this->setErrorsFromObject($contact);
1239 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1240 $contactId = $result;
1241 }
1242 }
1243
1244 if (empty($error)) {
1245 dol_syslog(get_class($this)."::create_individual success");
1246 $this->db->commit();
1247 } else {
1248 $this->db->rollback();
1249 }
1250
1251 return $contactId;
1252 }
1253
1260 public function verify()
1261 {
1262 global $conf, $langs, $mysoc;
1263
1264 $error = 0;
1265 $this->errors = array();
1266
1267 $result = 0;
1268 $this->name = trim($this->name);
1269 $this->nom = $this->name; // For backward compatibility
1270
1271 if (!$this->name) {
1272 $this->errors[] = 'ErrorBadThirdPartyName';
1273 $result = -2;
1274 }
1275
1276 if ($this->client) {
1277 $rescode = $this->check_codeclient();
1278 if ($rescode != 0 && $rescode != -5) {
1279 if ($rescode == -1) {
1280 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1281 } elseif ($rescode == -2) {
1282 $this->errors[] = 'ErrorCustomerCodeRequired';
1283 } elseif ($rescode == -3) {
1284 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1285 } elseif ($rescode == -4) {
1286 $this->errors[] = 'ErrorPrefixRequired';
1287 } else {
1288 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1289 }
1290
1291 $result = -3;
1292 }
1293 }
1294
1295 if ($this->fournisseur) {
1296 $rescode = $this->check_codefournisseur();
1297 if ($rescode != 0 && $rescode != -5) {
1298 if ($rescode == -1) {
1299 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1300 } elseif ($rescode == -2) {
1301 $this->errors[] = 'ErrorSupplierCodeRequired';
1302 } elseif ($rescode == -3) {
1303 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1304 } elseif ($rescode == -4) {
1305 $this->errors[] = 'ErrorPrefixRequired';
1306 } else {
1307 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1308 }
1309 $result = -3;
1310 }
1311 }
1312
1313 // Check for duplicate or mandatory fields defined into setup
1314 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1315 foreach ($array_to_check as $key) {
1316 $keymin = strtolower($key);
1317 $keyfield_db = $keymin;
1318 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1319 $keymin = 'code_compta_client';
1320 $keyfield_db = 'code_compta';
1321 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1322 $keymin = 'code_compta_fournisseur';
1323 $keyfield_db = 'code_compta_fournisseur';
1324 }
1325 $i = (int) preg_replace('/[^0-9]/', '', $key);
1326 $vallabel = $this->$keymin;
1327
1328 if ($i > 0) {
1329 if ($mysoc != null && $this->isACompany()) {
1330 // Check for mandatory prof id (but only if country is same than ours)
1331 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1332 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1333 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1334 $langs->load("errors");
1335 $error++;
1336 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1337 }
1338 }
1339 }
1340
1341 // Check for unicity on profid
1342 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1343 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1344 $langs->load("errors");
1345 $error++;
1346 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1347 }
1348 }
1349 } else {
1350 //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1351 //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1352 if ($key == 'EMAIL') {
1353 // Check for mandatory
1354 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1355 $langs->load("errors");
1356 $error++;
1357 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1358 }
1359
1360 // Check for unicity
1361 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1362 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1363 $langs->load("errors");
1364 $error++;
1365 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1366 }
1367 }
1368 } elseif ($key == 'TVA_INTRA') {
1369 // Check for unicity
1370 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1371 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1372 $langs->load("errors");
1373 $error++;
1374 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1375 }
1376 }
1377 if ($this->tva_assuj && !$vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_MANDATORY')) {
1378 $langs->load("errors");
1379 $error++;
1380 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->trans('VATIntra')).' ('.$langs->trans("ForbiddenBySetupRules").')';
1381 }
1382 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1383 // Check for unicity
1384 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1385 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1386 $langs->loadLangs(array("errors", 'compta'));
1387 $error++;
1388 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1389 }
1390 }
1391
1392 // Check for mandatory
1393 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1394 $langs->loadLangs(array("errors", 'compta'));
1395 $error++;
1396 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1397 }
1398 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1399 // Check for unicity
1400 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1401 if ($this->id_prof_exists($keyfield_db, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1402 $langs->loadLangs(array("errors", 'compta'));
1403 $error++;
1404 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1405 }
1406 }
1407
1408 // Check for mandatory
1409 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1410 $langs->loadLangs(array("errors", 'compta'));
1411 $error++;
1412 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1413 }
1414 }
1415 }
1416 }
1417
1418 if ($error) {
1419 $result = -4;
1420 }
1421
1422 return $result;
1423 }
1424
1437 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1438 {
1439 global $langs, $conf, $hookmanager;
1440
1441 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1442
1443 if (empty($id)) {
1444 $id = $this->id;
1445 }
1446 if (empty($this->country_id) && !empty($this->country_code)) {
1447 $this->country_id = dol_getIdFromCode($this->db, $this->country_code, 'c_country', 'code', 'rowid');
1448 }
1449
1450 $error = 0;
1451
1452 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1453
1454 $now = dol_now();
1455
1456 // Clean parameters
1457 $this->id = $id;
1458 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1459 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1460 $this->nom = $this->name; // For backward compatibility
1461 $this->name_alias = trim((string) $this->name_alias);
1462 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1463 $this->address = trim((string) $this->address);
1464 $this->zip = trim((string) $this->zip);
1465 $this->town = trim((string) $this->town);
1466 $this->state_id = (is_numeric($this->state_id)) ? (int) $this->state_id : 0;
1467 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1468 $this->phone = trim((string) $this->phone);
1469 $this->phone = preg_replace("/\s/", "", $this->phone);
1470 $this->phone = preg_replace("/\./", "", $this->phone);
1471 $this->phone_mobile = trim((string) $this->phone_mobile);
1472 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1473 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1474 $this->fax = trim((string) $this->fax);
1475 $this->fax = preg_replace("/\s/", "", $this->fax);
1476 $this->fax = preg_replace("/\./", "", $this->fax);
1477 $this->email = trim((string) $this->email);
1478 $this->url = $this->url ? clean_url($this->url, 0) : '';
1479 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1480 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1481 $this->idprof1 = trim((string) $this->idprof1);
1482 $this->idprof2 = trim((string) $this->idprof2);
1483 $this->idprof3 = trim((string) $this->idprof3);
1484 $this->idprof4 = trim((string) $this->idprof4);
1485 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1486 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1487 $this->prefix_comm = trim((string) $this->prefix_comm);
1488 $this->outstanding_limit = price2num($this->outstanding_limit);
1489 $this->order_min_amount = price2num($this->order_min_amount);
1490 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1491
1492 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1493 $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1494 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1495 if (empty($this->status)) {
1496 $this->status = 0;
1497 }
1498
1499 if (!empty($this->multicurrency_code)) {
1500 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1501 }
1502 if (empty($this->fk_multicurrency)) {
1503 $this->multicurrency_code = '';
1504 $this->fk_multicurrency = 0;
1505 }
1506
1507 // Local taxes
1508 $this->localtax1_assuj = (int) trim((string) $this->localtax1_assuj);
1509 $this->localtax2_assuj = (int) trim((string) $this->localtax2_assuj);
1510
1511 $this->localtax1_value = trim($this->localtax1_value);
1512 $this->localtax2_value = trim($this->localtax2_value);
1513
1514 $this->capital = ($this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1515
1516 $this->effectif_id = (int) $this->effectif_id;
1517 $this->forme_juridique_code = (int) $this->forme_juridique_code;
1518
1519 //Gencod
1520 $this->barcode = trim((string) $this->barcode);
1521
1522 // For automatic creation
1523 if ($this->code_client == -1 || $this->code_client === 'auto') {
1524 $this->get_codeclient($this, 0);
1525 }
1526 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1527 $this->get_codefournisseur($this, 1);
1528 }
1529
1530 $this->accountancy_code_customer_general = trim((string) $this->accountancy_code_customer_general);
1531 $this->code_compta_client = trim((string) $this->code_compta_client);
1532 $this->accountancy_code_supplier_general = trim((string) $this->accountancy_code_supplier_general);
1533 $this->code_compta_fournisseur = trim((string) $this->code_compta_fournisseur);
1534
1535 // Check parameters. More tests are done later in the ->verify()
1536 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1537 $langs->load("errors");
1538 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1539 return -1;
1540 }
1541
1542 $customer = false;
1543 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1544 // If $allowmodcodeclient is set and value is not set, we generate it
1545 if (empty($this->code_compta_client)) {
1546 $ret = $this->get_codecompta('customer');
1547 if ($ret < 0) {
1548 return -1;
1549 }
1550 }
1551
1552 $customer = true;
1553 }
1554
1555 $supplier = false;
1556 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1557 // If $allowmodcodefournisseur is set and value is not set, we generate it
1558 if (empty($this->code_compta_fournisseur)) {
1559 $ret = $this->get_codecompta('supplier');
1560 if ($ret < 0) {
1561 return -1;
1562 }
1563 }
1564
1565 $supplier = true;
1566 }
1567
1568 //Web services
1569 $this->webservices_url = empty($this->webservices_url) ? '' : clean_url($this->webservices_url, 0);
1570 $this->webservices_key = trim((string) $this->webservices_key);
1571
1572 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1573 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1574
1575 //Incoterms
1576 $this->fk_incoterms = (int) $this->fk_incoterms;
1577 $this->location_incoterms = trim((string) $this->location_incoterms);
1578
1579 $this->db->begin();
1580
1581 // Check name is required and codes are ok or unique.
1582 // If error, this->errors[] is filled
1583 $result = 0;
1584 if ($action != 'add' && $action != 'merge') {
1585 // We don't check when update called during a create because verify was already done.
1586 // 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
1587 $result = $this->verify();
1588
1589 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1590 // So we can update record that were using and old numbering rule.
1591 if (is_array($this->errors)) {
1592 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1593 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1594 unset($this->errors[$key]); // Remove error message
1595 }
1596 }
1597 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1598 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1599 unset($this->errors[$key]); // Remove error message
1600 }
1601 }
1602 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1603 $result = 0;
1604 }
1605 }
1606 }
1607 $this->setUpperOrLowerCase();
1608 if ($result >= 0) {
1609 dol_syslog(get_class($this)."::update verify ok or not done");
1610
1611 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1612 $sql .= "entity = ".((int) $this->entity);
1613 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1614 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1615 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1616 $sql .= ",address = '".$this->db->escape($this->address)."'";
1617
1618 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1619 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1620
1621 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1622 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1623
1624 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1625 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1626 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1627 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1628 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1629 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1630
1631 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1632
1633 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1634 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1635
1636 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1637 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1638 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1639 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1640 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1641 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1642
1643 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1644 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1645 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1646 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1647 }
1648 $sql .= ",status = ".((int) $this->status);
1649
1650 // Local taxes
1651 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1652 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1653 if ($this->localtax1_assuj == 1) {
1654 if ($this->localtax1_value != '') {
1655 $sql .= ",localtax1_value =".$this->localtax1_value;
1656 } else {
1657 $sql .= ",localtax1_value =0.000";
1658 }
1659 } else {
1660 $sql .= ",localtax1_value =0.000";
1661 }
1662
1663 if ($this->localtax2_assuj == 1) {
1664 if ($this->localtax2_value != '') {
1665 $sql .= ",localtax2_value =".$this->localtax2_value;
1666 } else {
1667 $sql .= ",localtax2_value =0.000";
1668 }
1669 } else {
1670 $sql .= ",localtax2_value =0.000";
1671 }
1672
1673 $sql .= ",capital = ".($this->capital === null ? "null" : $this->capital);
1674
1675 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1676
1677 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1678 if (isset($this->stcomm_id)) {
1679 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1680 }
1681 if (isset($this->typent_id)) {
1682 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1683 }
1684
1685 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1686
1687 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1688 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1689 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1690 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1691 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1692 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1693 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1694 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1695
1696 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1697 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1698 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1699 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1700 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1701 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1702 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1703 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1704 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1705 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1706 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1707 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1708 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1709 if ($customer) {
1710 $sql .= ", accountancy_code_customer_general = ".(!empty($this->accountancy_code_customer_general) ? "'".$this->db->escape($this->accountancy_code_customer_general)."'" : "null");
1711 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1712 }
1713
1714 if ($supplier) {
1715 $sql .= ", accountancy_code_supplier_general = ".(!empty($this->accountancy_code_supplier_general) ? "'".$this->db->escape($this->accountancy_code_supplier_general)."'" : "null");
1716 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1717 }
1718 }
1719 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1720 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1721
1722 //Incoterms
1723 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1724 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1725
1726 if ($customer) {
1727 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1728 }
1729
1730 if ($supplier) {
1731 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1732 }
1733 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1734 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1735 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1736 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1737 $sql .= " WHERE rowid = ".(int) $id;
1738
1739 $resql = $this->db->query($sql);
1740 if ($resql) {
1741 if (is_object($this->oldcopy)) { // If we have information on old values
1742 if ($this->oldcopy->country_id != $this->country_id) {
1743 unset($this->country_code);
1744 unset($this->country);
1745 }
1746 if ($this->oldcopy->state_id != $this->state_id) {
1747 unset($this->state_code);
1748 unset($this->state);
1749 }
1750 } else {
1751 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1752 unset($this->country);
1753 unset($this->state_code);
1754 unset($this->state);
1755 }
1756
1757 $nbrowsaffected = $this->db->affected_rows($resql);
1758
1759 if (!$error && $nbrowsaffected) {
1760 // Update information on linked member if it is an update
1761 if (!$nosyncmember && isModEnabled('member')) {
1762 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1763
1764 dol_syslog(get_class($this)."::update update linked member");
1765
1766 $lmember = new Adherent($this->db);
1767 $result = $lmember->fetch(0, 0, $this->id);
1768
1769 if ($result > 0) {
1770 $lmember->company = $this->name;
1771 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1772 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1773 $lmember->address = $this->address;
1774 $lmember->zip = $this->zip;
1775 $lmember->town = $this->town;
1776 $lmember->email = $this->email;
1777 $lmember->socialnetworks = $this->socialnetworks;
1778 $lmember->phone = $this->phone;
1779 $lmember->state_id = $this->state_id;
1780 $lmember->country_id = $this->country_id;
1781 $lmember->default_lang = $this->default_lang;
1782
1783 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1784 if ($result < 0) {
1785 $this->error = $lmember->error;
1786 $this->errors = array_merge($this->errors, $lmember->errors);
1787 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1788 $error++;
1789 }
1790 } elseif ($result < 0) {
1791 $this->error = $lmember->error;
1792 $error++;
1793 }
1794 }
1795 }
1796
1797 $action = 'update';
1798
1799 // update accountancy for this entity
1800 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1801 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1802
1803 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1804 $sql .= " fk_soc";
1805 $sql .= ", entity";
1806 $sql .= ", vat_reverse_charge";
1807 $sql .= ", accountancy_code_customer_general";
1808 $sql .= ", accountancy_code_customer";
1809 $sql .= ", accountancy_code_supplier_general";
1810 $sql .= ", accountancy_code_supplier";
1811 $sql .= ", accountancy_code_buy";
1812 $sql .= ", accountancy_code_sell";
1813 $sql .= ") VALUES (";
1814 $sql .= $this->id;
1815 $sql .= ", ".$conf->entity;
1816 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1817 $sql .= ", '".$this->db->escape($this->accountancy_code_customer_general)."'";
1818 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1819 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier_general)."'";
1820 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1821 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1822 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1823 $sql .= ")";
1824 $result = $this->db->query($sql);
1825 if (!$result) {
1826 $error++;
1827 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1828 }
1829 }
1830
1831 // Actions on extra fields
1832 if (!$error) {
1833 $result = $this->insertExtraFields();
1834 if ($result < 0) {
1835 $error++;
1836 }
1837 }
1838 // Actions on extra languages
1839 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1840 $result = $this->insertExtraLanguages();
1841 if ($result < 0) {
1842 $error++;
1843 }
1844 }
1845
1846 if (!$error && $call_trigger) {
1847 // Call trigger
1848 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1849 if ($result < 0) {
1850 $error++;
1851 }
1852 // End call triggers
1853 }
1854
1855 if (!$error) {
1856 dol_syslog(get_class($this)."::Update success");
1857 $this->db->commit();
1858 return 1;
1859 } else {
1860 $this->db->rollback();
1861 return -1;
1862 }
1863 } else {
1864 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1865 // Doublon
1866 $this->error = $langs->trans("ErrorDuplicateField");
1867 $result = -1;
1868 } else {
1869 $this->error = $this->db->lasterror();
1870 $result = -2;
1871 }
1872 $this->db->rollback();
1873 return $result;
1874 }
1875 } else {
1876 $this->db->rollback();
1877 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1878 return -3;
1879 }
1880 }
1881
1901 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1902 {
1903 global $langs;
1904 global $conf;
1905
1906 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)) {
1907 return -1;
1908 }
1909
1910 $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';
1911 $sql .= ', s.status, s.fk_warehouse';
1912 $sql .= ', s.price_level';
1913 $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1914 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1915 $sql .= ', s.socialnetworks';
1916 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1917 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1918 $sql .= ', s.capital, s.tva_intra';
1919 $sql .= ', s.fk_typent as typent_id';
1920 $sql .= ', s.fk_effectif as effectif_id';
1921 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1922 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1923 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1924 $sql .= ', s.accountancy_code_customer_general, s.code_compta';
1925 $sql .= ', s.accountancy_code_supplier_general, s.code_compta_fournisseur';
1926 $sql .= ', s.accountancy_code_buy, s.accountancy_code_sell';
1927 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1928 } else {
1929 $sql .= ', spe.accountancy_code_customer_general, spe.accountancy_code_customer as code_compta';
1930 $sql .= ', spe.accountancy_code_supplier_general, spe.accountancy_code_supplier as code_compta_fournisseur';
1931 $sql .= ', spe.accountancy_code_buy, spe.accountancy_code_sell';
1932 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1933 }
1934 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1935 $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';
1936 $sql .= ', s.fk_account, s.tva_assuj';
1937 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1938 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1939 $sql .= ', s.fk_shipping_method';
1940 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1941 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1942 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1943 $sql .= ', fj.libelle as forme_juridique';
1944 $sql .= ', e.libelle as effectif';
1945 $sql .= ', c.code as country_code, c.label as country';
1946 $sql .= ', d.code_departement as state_code, d.nom as state';
1947 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1948 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1949 $sql .= ', te.code as typent_code';
1950 $sql .= ', i.libelle as label_incoterms';
1951 if (!isModEnabled('multicompany')) {
1952 $sql .= ', s.remise_client, s.remise_supplier';
1953 } else {
1954 $sql .= ', sr.remise_client, sr2.remise_supplier';
1955 }
1956 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1957 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1958 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1959 }
1960 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1961 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1962 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1963 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1964 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1965 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1966 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1967 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1968 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1969 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1970 if (isModEnabled('multicompany')) {
1971 $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').'))';
1972 $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').'))';
1973 }
1974 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1975
1976 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
1977 if ($is_client) {
1978 $sql .= ' AND s.client > 0';
1979 }
1980 if ($is_supplier) {
1981 $sql .= ' AND s.fournisseur > 0';
1982 } // if both false, no test (the thirdparty can be client and/or supplier)
1983
1984 if ($rowid) {
1985 $sql .= ' AND s.rowid = '.((int) $rowid);
1986 }
1987 if ($ref) {
1988 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1989 }
1990 if ($ref_alias) {
1991 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1992 }
1993 if ($ref_ext) {
1994 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1995 }
1996 if ($barcode) {
1997 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1998 }
1999 if ($idprof1) {
2000 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
2001 }
2002 if ($idprof2) {
2003 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
2004 }
2005 if ($idprof3) {
2006 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
2007 }
2008 if ($idprof4) {
2009 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
2010 }
2011 if ($idprof5) {
2012 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
2013 }
2014 if ($idprof6) {
2015 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
2016 }
2017 if ($email) {
2018 $sql .= " AND s.email = '".$this->db->escape($email)."'";
2019 }
2020
2021 $resql = $this->db->query($sql);
2022 if ($resql) {
2023 $num = $this->db->num_rows($resql);
2024 if ($num > 1) {
2025 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
2026 dol_syslog($this->error, LOG_ERR);
2027 $result = -2;
2028 } elseif ($num) { // $num = 1
2029 $obj = $this->db->fetch_object($resql);
2030
2031 $this->id = $obj->rowid;
2032 $this->entity = $obj->entity;
2033 $this->canvas = $obj->canvas;
2034
2035 $this->ref = $obj->name;
2036 $this->name = $obj->name;
2037 $this->nom = $obj->name; // deprecated
2038 $this->name_alias = $obj->name_alias;
2039 $this->ref_ext = $obj->ref_ext;
2040
2041 $this->date_creation = $this->db->jdate($obj->date_creation);
2042 $this->date_modification = $this->db->jdate($obj->date_modification);
2043 $this->user_creation_id = $obj->fk_user_creat;
2044 $this->user_modification_id = $obj->fk_user_modif;
2045
2046 $this->address = $obj->address;
2047 $this->zip = $obj->zip;
2048 $this->town = $obj->town;
2049
2050 $this->country_id = $obj->country_id;
2051 $this->country_code = $obj->country_id ? $obj->country_code : '';
2052 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
2053
2054 $this->state_id = $obj->state_id;
2055 $this->state_code = $obj->state_code;
2056 $this->region_id = $obj->region_id;
2057 $this->region_code = $obj->region_code;
2058 $this->state = ($obj->state != '-' ? $obj->state : '');
2059
2060 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
2061 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
2062 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
2063 $this->status_prospect_label = $label; // label status prospect
2064 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
2065
2066 $this->email = $obj->email;
2067 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
2068
2069 $this->url = $obj->url;
2070 $this->phone = $obj->phone;
2071 $this->phone_mobile = $obj->phone_mobile;
2072 $this->fax = $obj->fax;
2073
2074 $this->parent = $obj->parent;
2075
2076 $this->idprof1 = $obj->idprof1;
2077 $this->idprof2 = $obj->idprof2;
2078 $this->idprof3 = $obj->idprof3;
2079 $this->idprof4 = $obj->idprof4;
2080 $this->idprof5 = $obj->idprof5;
2081 $this->idprof6 = $obj->idprof6;
2082
2083 $this->capital = $obj->capital;
2084
2085 $this->code_client = $obj->code_client;
2086 $this->code_fournisseur = $obj->code_fournisseur;
2087
2088 $this->accountancy_code_customer_general = $obj->accountancy_code_customer_general;
2089 $this->code_compta_client = $obj->code_compta;
2090 $this->accountancy_code_supplier_general = $obj->accountancy_code_supplier_general;
2091 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
2092
2093 $this->barcode = $obj->barcode;
2094
2095 $this->tva_assuj = $obj->tva_assuj;
2096 $this->tva_intra = $obj->tva_intra;
2097
2098 if (!empty($obj->spe_vat_reverse_charge)) {
2099 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2100 } elseif (!empty($obj->soc_vat_reverse_charge)) {
2101 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2102 } else {
2103 $this->vat_reverse_charge = 0;
2104 }
2105
2106 $this->status = $obj->status;
2107
2108 // Local Taxes
2109 $this->localtax1_assuj = $obj->localtax1_assuj;
2110 $this->localtax2_assuj = $obj->localtax2_assuj;
2111
2112 $this->localtax1_value = $obj->localtax1_value;
2113 $this->localtax2_value = $obj->localtax2_value;
2114
2115 $this->typent_id = $obj->typent_id;
2116 $this->typent_code = $obj->typent_code;
2117
2118 $this->effectif_id = $obj->effectif_id;
2119 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2120
2121 $this->forme_juridique_code = $obj->forme_juridique_code;
2122 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2123
2124 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2125
2126 $this->prefix_comm = $obj->prefix_comm;
2127
2128 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2129 $this->remise_supplier_percent = $obj->remise_supplier;
2130
2131 $this->mode_reglement_id = $obj->mode_reglement;
2132 $this->cond_reglement_id = $obj->cond_reglement;
2133 $this->deposit_percent = $obj->deposit_percent;
2134 $this->transport_mode_id = $obj->transport_mode;
2135 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2136 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2137 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2138 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2139 $this->fk_account = $obj->fk_account;
2140
2141 $this->client = $obj->client;
2142 $this->fournisseur = $obj->fournisseur;
2143
2144 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2145 $this->note_private = $obj->note_private;
2146 $this->note_public = $obj->note_public;
2147 $this->model_pdf = $obj->model_pdf;
2148 $this->default_lang = $obj->default_lang;
2149 $this->logo = $obj->logo;
2150 $this->logo_squarred = $obj->logo_squarred;
2151
2152 $this->webservices_url = $obj->webservices_url;
2153 $this->webservices_key = $obj->webservices_key;
2154
2155 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2156 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2157
2158 $this->outstanding_limit = $obj->outstanding_limit;
2159 $this->order_min_amount = $obj->order_min_amount;
2160 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2161
2162 // multiprix
2163 $this->price_level = $obj->price_level;
2164
2165 // warehouse
2166 $this->fk_warehouse = $obj->fk_warehouse;
2167
2168 $this->import_key = $obj->import_key;
2169
2170 //Incoterms
2171 $this->fk_incoterms = $obj->fk_incoterms;
2172 $this->location_incoterms = $obj->location_incoterms;
2173 $this->label_incoterms = $obj->label_incoterms;
2174
2175 // multicurrency
2176 $this->fk_multicurrency = $obj->fk_multicurrency;
2177 $this->multicurrency_code = $obj->multicurrency_code;
2178
2179 // pdf
2180 $this->model_pdf = $obj->model_pdf;
2181 $this->last_main_doc = $obj->last_main_doc;
2182
2183 $result = $this->id;
2184
2185 // fetch optionals attributes and labels
2186 $this->fetch_optionals();
2187 } else {
2188 $result = 0;
2189 }
2190
2191 $this->db->free($resql);
2192 } else {
2193 $this->error = $this->db->lasterror();
2194 $this->errors[] = $this->db->lasterror();
2195 $result = -3;
2196 }
2197
2198 // Use first price level if level not defined for third party
2199 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->price_level)) {
2200 $this->price_level = 1;
2201 }
2202
2203 return $result;
2204 }
2205
2226 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
2227 {
2228 // A rowid is known, it is a unique key so we found it
2229 if ($rowid) {
2230 return $rowid;
2231 }
2232
2233 // We try to find the thirdparty with exact matching on all fields
2234 // TODO Replace this with step by step search
2235 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2236 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2237 // Then search on email (+ restriction on is_client and is_supplier)
2238 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2239 $tmpthirdparty = new Societe($this->db);
2240 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2241
2242 return $result;
2243 }
2244
2253 public function delete($id, $fuser = null, $call_trigger = 1)
2254 {
2255 global $conf, $user;
2256
2257 if (empty($fuser)) {
2258 $fuser = $user;
2259 }
2260
2261 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2262
2263 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2264
2265 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2266 $error = 0;
2267
2268 // Test if child exists
2269 $objectisused = $this->isObjectUsed($id);
2270 if (empty($objectisused)) {
2271 $this->db->begin();
2272
2273 // User is mandatory for trigger call
2274 if (!$error && $call_trigger) {
2275 // Call trigger
2276 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2277 if ($result < 0) {
2278 $error++;
2279 }
2280 // End call triggers
2281 }
2282
2283 if (!$error) {
2284 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2285 $static_cat = new Categorie($this->db);
2286 $toute_categs = array();
2287
2288 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2289 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2290 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2291
2292 // Remove each "Categorie"
2293 foreach ($toute_categs as $type => $categs_type) {
2294 foreach ($categs_type as $cat) {
2295 $cat->del_type($this, $type);
2296 }
2297 }
2298 }
2299
2300 if (!$error) {
2301 foreach ($this->childtablesoncascade as $tabletodelete) {
2302 $deleteFromObject = explode(':', $tabletodelete, 4);
2303 if (count($deleteFromObject) >= 2) {
2304 $className = str_replace('@', '', $deleteFromObject[0]);
2305 $filepath = $deleteFromObject[1];
2306 $columnName = $deleteFromObject[2];
2307 if (dol_include_once($filepath)) {
2308 $child_object = new $className($this->db);
2309 '@phan-var-force CommonObject $child_object';
2310 $result = $child_object->deleteByParentField($id, $columnName);
2311 if ($result < 0) {
2312 $error++;
2313 $this->errors[] = $child_object->error;
2314 break;
2315 }
2316 } else {
2317 $error++;
2318 $this->errors[] = 'Cannot include child class file '.$filepath;
2319 break;
2320 }
2321 } else {
2322 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2323 $sql .= " WHERE fk_soc = ".((int) $id);
2324 if (!$this->db->query($sql)) {
2325 $error++;
2326 $this->errors[] = $this->db->lasterror();
2327 break;
2328 }
2329 }
2330 }
2331 }
2332
2333 // Removed extrafields
2334 if (!$error) {
2335 $result = $this->deleteExtraFields();
2336 if ($result < 0) {
2337 $error++;
2338 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2339 }
2340 }
2341
2342 // Remove links to subsidiaries companies
2343 if (!$error) {
2344 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2345 $sql .= " SET parent = NULL";
2346 $sql .= " WHERE parent = ".((int) $id);
2347 if (!$this->db->query($sql)) {
2348 $error++;
2349 $this->errors[] = $this->db->lasterror();
2350 }
2351 }
2352
2353 // Remove third party
2354 if (!$error) {
2355 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2356 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2357 $sql .= " WHERE fk_soc = ".((int) $id);
2358 if (!$this->db->query($sql)) {
2359 $error++;
2360 $this->errors[] = $this->db->lasterror();
2361 }
2362 }
2363
2364 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2365 $sql .= " WHERE rowid = ".((int) $id);
2366 if (!$this->db->query($sql)) {
2367 $error++;
2368 $this->errors[] = $this->db->lasterror();
2369 }
2370 }
2371
2372 if (!$error) {
2373 $this->db->commit();
2374
2375 // Delete directory
2376 if (!empty($conf->societe->multidir_output[$entity])) {
2377 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2378 if (dol_is_dir($docdir)) {
2379 dol_delete_dir_recursive($docdir);
2380 }
2381 }
2382
2383 return 1;
2384 } else {
2385 dol_syslog($this->error, LOG_ERR);
2386 $this->db->rollback();
2387 return -1;
2388 }
2389 } else {
2390 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2391 }
2392 return 0;
2393 }
2394
2395 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2403 public function set_as_client()
2404 {
2405 // phpcs:enable
2406 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2407 return $this->setAsCustomer();
2408 }
2409
2416 public function setAsCustomer()
2417 {
2418 if ($this->id) {
2419 $newclient = 1;
2420 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2421 $newclient = 3; //If prospect, we keep prospect tag
2422 }
2423 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2424 $sql .= " SET client = ".((int) $newclient);
2425 $sql .= " WHERE rowid = ".((int) $this->id);
2426
2427 $resql = $this->db->query($sql);
2428 if ($resql) {
2429 $this->client = $newclient;
2430 return 1;
2431 } else {
2432 return -1;
2433 }
2434 }
2435 return 0;
2436 }
2437
2438 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2447 public function set_remise_client($remise, $note, User $user)
2448 {
2449 // phpcs:enable
2450 global $conf, $langs;
2451
2452 // Parameter cleaning
2453 $note = trim($note);
2454 if (!$note) {
2455 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2456 return -2;
2457 }
2458
2459 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2460
2461 if ($this->id) {
2462 $this->db->begin();
2463
2464 $now = dol_now();
2465
2466 // Position current discount
2467 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2468 $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2469 $sql .= " WHERE rowid = ".((int) $this->id);
2470 $resql = $this->db->query($sql);
2471 if (!$resql) {
2472 $this->db->rollback();
2473 $this->error = $this->db->error();
2474 return -1;
2475 }
2476
2477 // Writes trace in discount history
2478 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2479 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2480 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2481 $sql .= " '".$this->db->escape($note)."',";
2482 $sql .= " ".((int) $user->id);
2483 $sql .= ")";
2484
2485 $resql = $this->db->query($sql);
2486 if (!$resql) {
2487 $this->db->rollback();
2488 $this->error = $this->db->lasterror();
2489 return -1;
2490 }
2491
2492 $this->db->commit();
2493
2494 return 1;
2495 }
2496 return -1;
2497 }
2498
2499 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2508 public function set_remise_supplier($remise, $note, User $user)
2509 {
2510 // phpcs:enable
2511 global $conf, $langs;
2512
2513 // Parameter cleaning
2514 $note = trim($note);
2515 if (!$note) {
2516 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2517 return -2;
2518 }
2519
2520 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2521
2522 if ($this->id) {
2523 $this->db->begin();
2524
2525 $now = dol_now();
2526
2527 // Position current discount
2528 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2529 $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2530 $sql .= " WHERE rowid = ".((int) $this->id);
2531 $resql = $this->db->query($sql);
2532 if (!$resql) {
2533 $this->db->rollback();
2534 $this->error = $this->db->error();
2535 return -1;
2536 }
2537
2538 // Writes trace in discount history
2539 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2540 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2541 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2542 $sql .= " '".$this->db->escape($note)."',";
2543 $sql .= " ".((int) $user->id);
2544 $sql .= ")";
2545
2546 $resql = $this->db->query($sql);
2547 if (!$resql) {
2548 $this->db->rollback();
2549 $this->error = $this->db->lasterror();
2550 return -1;
2551 }
2552
2553 $this->db->commit();
2554 return 1;
2555 }
2556
2557 return -1;
2558 }
2559
2560 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2572 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2573 {
2574 // phpcs:enable
2575 global $langs;
2576
2577 // Clean parameters
2578 $remise = price2num($remise);
2579 $desc = trim($desc);
2580
2581 // Check parameters
2582 if (!($remise > 0)) {
2583 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2584 return -1;
2585 }
2586 if (!$desc) {
2587 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2588 return -2;
2589 }
2590
2591 if ($this->id > 0) {
2592 // Clean vat code
2593 $reg = array();
2594 $vat_src_code = '';
2595 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2596 $vat_src_code = $reg[1];
2597 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2598 }
2599
2600 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2601
2602 $discount = new DiscountAbsolute($this->db);
2603 $discount->fk_soc = $this->id;
2604 $discount->socid = $this->id;
2605
2606 $discount->discount_type = $discount_type;
2607
2608 if ($price_base_type == 'TTC') {
2609 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2610 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2611 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $discount->amount_ttc - (float) $discount->amount_ht, 'MT');
2612 } else {
2613 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2614 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num((float) $remise * (float) $vatrate / 100, 'MT');
2615 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num((float) $discount->amount_ht + (float) $discount->amount_tva, 'MT');
2616 }
2617
2618 $discount->tva_tx = (float) price2num($vatrate);
2619 $discount->vat_src_code = $vat_src_code;
2620
2621 $discount->description = $desc;
2622
2623 $result = $discount->create($user);
2624 if ($result > 0) {
2625 return $result;
2626 } else {
2627 $this->error = $discount->error;
2628 return -3;
2629 }
2630 } else {
2631 return 0;
2632 }
2633 }
2634
2644 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2645 {
2646 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2647
2648 $discountstatic = new DiscountAbsolute($this->db);
2649 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2650 if ($result >= 0) {
2651 return $result;
2652 } else {
2653 $this->error = $discountstatic->error;
2654 return -1;
2655 }
2656 }
2657
2667 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2668 {
2669 global $conf;
2670
2671 $reparray = array();
2672
2673 $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";
2674 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2675 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2676 // Condition here should be the same than into select_dolusers()
2677 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2678 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2679 } else {
2680 $sql .= " WHERE entity IN (0, ".$this->db->sanitize($conf->entity).")";
2681 }
2682
2683 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2684 if (empty($sortfield) && empty($sortorder)) {
2685 $sortfield = 'u.lastname,u.firstname';
2686 $sortorder = 'ASC,ASC';
2687 }
2688 $sql .= $this->db->order($sortfield, $sortorder);
2689
2690 $resql = $this->db->query($sql);
2691 if ($resql) {
2692 $num = $this->db->num_rows($resql);
2693 $i = 0;
2694 while ($i < $num) {
2695 $obj = $this->db->fetch_object($resql);
2696
2697 if (empty($mode)) {
2698 $reparray[$i]['id'] = $obj->rowid;
2699 $reparray[$i]['lastname'] = $obj->lastname;
2700 $reparray[$i]['firstname'] = $obj->firstname;
2701 $reparray[$i]['email'] = $obj->email;
2702 $reparray[$i]['phone'] = $obj->office_phone;
2703 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2704 $reparray[$i]['office_fax'] = $obj->office_fax;
2705 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2706 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2707 $reparray[$i]['job'] = $obj->job;
2708 $reparray[$i]['statut'] = $obj->status; // deprecated
2709 $reparray[$i]['status'] = $obj->status;
2710 $reparray[$i]['entity'] = $obj->entity;
2711 $reparray[$i]['login'] = $obj->login;
2712 $reparray[$i]['photo'] = $obj->photo;
2713 $reparray[$i]['gender'] = $obj->gender;
2714 } else {
2715 $reparray[] = $obj->rowid;
2716 }
2717 $i++;
2718 }
2719 return $reparray;
2720 } else {
2721 dol_print_error($this->db);
2722 return -1;
2723 }
2724 }
2725
2733 public function setPriceLevel($price_level, User $user)
2734 {
2735 if ($this->id) {
2736 $now = dol_now();
2737
2738 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2739 $sql .= " SET price_level = ".((int) $price_level);
2740 $sql .= " WHERE rowid = ".((int) $this->id);
2741
2742 if (!$this->db->query($sql)) {
2743 dol_print_error($this->db);
2744 return -1;
2745 }
2746
2747 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2748 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2749 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2750
2751 if (!$this->db->query($sql)) {
2752 dol_print_error($this->db);
2753 return -1;
2754 }
2755 return 1;
2756 }
2757 return -1;
2758 }
2759
2760 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2768 public function add_commercial(User $user, $commid)
2769 {
2770 // phpcs:enable
2771 $error = 0;
2772
2773 if ($this->id > 0 && $commid > 0) {
2774 $this->db->begin();
2775
2776 if (!$error) {
2777 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2778 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2779
2780 $resql = $this->db->query($sql);
2781 if (!$resql) {
2782 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2783 $error++;
2784 }
2785 }
2786
2787 if (!$error) {
2788 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2789 $sql .= " (fk_soc, fk_user)";
2790 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2791
2792 $resql = $this->db->query($sql);
2793 if (!$resql) {
2794 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2795 $error++;
2796 }
2797 }
2798
2799 if (!$error) {
2800 $this->context = array('commercial_modified' => $commid);
2801
2802 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2803 if ($result < 0) {
2804 $error++;
2805 }
2806 }
2807
2808 if (!$error) {
2809 $this->db->commit();
2810 return 1;
2811 } else {
2812 $this->db->rollback();
2813 return -1;
2814 }
2815 }
2816
2817 return 0;
2818 }
2819
2820 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2828 public function del_commercial(User $user, $commid)
2829 {
2830 // phpcs:enable
2831 $error = 0;
2832 $this->context = array('commercial_modified' => $commid);
2833
2834 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2835 if ($result < 0) {
2836 $error++;
2837 }
2838
2839 if ($this->id > 0 && $commid > 0) {
2840 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2841 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2842
2843 if (!$this->db->query($sql)) {
2844 $error++;
2845 dol_syslog(get_class($this)."::del_commercial Erreur");
2846 }
2847 }
2848
2849 if ($error) {
2850 return -1;
2851 } else {
2852 return 1;
2853 }
2854 }
2855
2863 public function getTooltipContentArray($params)
2864 {
2865 global $conf, $langs, $user;
2866
2867 $langs->loadLangs(['companies', 'commercial']);
2868
2869 $datas = array();
2870
2871 $option = $params['option'] ?? '';
2872 $nofetch = !empty($params['nofetch']);
2873
2874 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2875
2876 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2877 return ['optimize' => $langs->trans("ShowCompany")];
2878 }
2879
2880 if (!empty($this->logo) && class_exists('Form')) {
2881 $photo = '<div class="photointooltip floatright">';
2882 $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.
2883 $photo .= '</div>';
2884 $datas['photo'] = $photo;
2885 } //elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2886 /*$label.= '<div class="photointooltip">';
2887 $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.
2888 $label.= '</div><div style="clear: both;"></div>';*/
2889 // }
2890
2891 $datas['divopen'] = '<div class="centpercent">';
2892
2893 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2894 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2895 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2896 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2897 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2898 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2899 } elseif ($option == 'agenda') {
2900 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2901 } elseif ($option == 'project') {
2902 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2903 } elseif ($option == 'margin') {
2904 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2905 } elseif ($option == 'contact') {
2906 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2907 } elseif ($option == 'ban') {
2908 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2909 }
2910
2911 // By default
2912 if (empty($datas['picto'])) {
2913 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2914 }
2915 if (isset($this->status)) {
2916 $datas['status'] = ' '.$this->getLibStatut(5);
2917 }
2918 if (isset($this->client) && isset($this->fournisseur)) {
2919 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1, '', 0, 'span');
2920 }
2921 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2922 if (!empty($this->name_alias) && empty($noaliasinname)) {
2923 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2924 }
2925 if (!empty($this->email)) {
2926 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2927 }
2928 if (!empty($this->url)) {
2929 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2930 }
2931 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
2932 $phonelist = array();
2933 if ($this->phone) {
2934 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2935 }
2936 // deliberately not making new list because fax uses same list as phone
2937 if ($this->phone_mobile) {
2938 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'phone_mobile');
2939 }
2940 if ($this->fax) {
2941 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2942 }
2943 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2944 }
2945
2946 if (!empty($this->address)) {
2947 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ', ', $langs); // Address + country
2948 } elseif (!empty($this->country_code)) {
2949 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2950 }
2951 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2952 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2953 }
2954
2955 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
2956 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2957 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2958 }
2959 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2960 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2961 }
2962 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2963 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2964 }
2965 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2966 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2967 }
2968 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2969 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2970 }
2971 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2972 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2973 }
2974 }
2975
2976 $datas['separator'] = '<br>';
2977
2978 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2979 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2980 }
2981 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2982 $langs->load('compta');
2983 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
2984 }
2985 // show categories for this record only in ajax to not overload lists
2986 if (!$nofetch && isModEnabled('category') && $this->client) {
2987 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2988 $form = new Form($this->db);
2989 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2990 }
2991 if (!empty($this->code_fournisseur) && $this->fournisseur) {
2992 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2993 }
2994 if (isModEnabled('accounting') && $this->fournisseur) {
2995 $langs->load('compta');
2996 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2997 }
2998 // show categories for this record only in ajax to not overload lists
2999 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
3000 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3001 $form = new Form($this->db);
3002 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
3003 }
3004
3005 $datas['divclose'] = '</div>';
3006
3007 return $datas;
3008 }
3009
3023 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
3024 {
3025 global $conf, $langs, $hookmanager, $user;
3026
3027 if (!empty($conf->dol_no_mouse_hover)) {
3028 $notooltip = 1; // Force disable tooltips
3029 }
3030
3031 $name = $this->name ? $this->name : $this->nom;
3032
3033 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
3034 if (empty($option) && $this->client > 0) {
3035 $option = 'customer';
3036 }
3037 if (empty($option) && $this->fournisseur > 0) {
3038 $option = 'supplier';
3039 }
3040 }
3041
3042 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
3043 $code = '';
3044 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
3045 $code = $this->code_client.' - ';
3046 }
3047
3048 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
3049 $code .= $this->code_fournisseur.' - ';
3050 }
3051
3052 if ($code) {
3053 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
3054 $name = $code.' '.$name;
3055 } else {
3056 $name = $code;
3057 }
3058 }
3059 }
3060
3061 if (!empty($this->name_alias) && empty($noaliasinname)) {
3062 $name .= ' ('.$this->name_alias.')';
3063 }
3064
3065 $result = '';
3066 $params = [
3067 'id' => $this->id,
3068 'objecttype' => $this->element,
3069 'option' => $option,
3070 'nofetch' => 1,
3071 ];
3072 $classfortooltip = 'classfortooltip';
3073 $dataparams = '';
3074 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3075 $classfortooltip = 'classforajaxtooltip';
3076 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3077 $label = '';
3078 } else {
3079 $label = implode($this->getTooltipContentArray($params));
3080 }
3081
3082 $linkstart = '';
3083 $linkend = '';
3084
3085 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
3086 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3087 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3088 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3089 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3090 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3091 } elseif ($option == 'agenda') {
3092 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3093 } elseif ($option == 'project') {
3094 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3095 } elseif ($option == 'margin') {
3096 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3097 } elseif ($option == 'contact') {
3098 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3099 } elseif ($option == 'ban') {
3100 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3101 }
3102
3103 // By default
3104 if (empty($linkstart)) {
3105 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3106 }
3107
3108 // Add type of canvas
3109 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3110 // Add param to save lastsearch_values or not
3111 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3112 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3113 $add_save_lastsearch_values = 1;
3114 }
3115 if ($add_save_lastsearch_values) {
3116 $linkstart .= '&save_lastsearch_values=1';
3117 }
3118 $linkstart .= '"';
3119
3120 $linkclose = '';
3121 if (empty($notooltip)) {
3122 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3123 $label = $langs->trans("ShowCompany");
3124 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3125 }
3126 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3127 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
3128 $target_value = array('_self', '_blank', '_parent', '_top');
3129 if (in_array($target, $target_value)) {
3130 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3131 }
3132 } else {
3133 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3134 }
3135 $linkstart .= $linkclose.'>';
3136 $linkend = '</a>';
3137
3138 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3139 $linkstart = '';
3140 $linkend = '';
3141 }
3142
3143 $result .= $linkstart;
3144 if ($withpicto) {
3145 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3146 }
3147 if ($withpicto != 2) {
3148 $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
3149 }
3150 $result .= $linkend;
3151
3152 global $action;
3153 $hookmanager->initHooks(array('thirdpartydao'));
3154 $parameters = array(
3155 'id' => $this->id,
3156 'getnomurl' => &$result,
3157 'withpicto ' => $withpicto,
3158 'option' => $option,
3159 'maxlen' => $maxlen,
3160 'notooltip' => $notooltip,
3161 'save_lastsearch_value' => $save_lastsearch_value
3162 );
3163 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3164 if ($reshook > 0) {
3165 $result = $hookmanager->resPrint;
3166 } else {
3167 $result .= $hookmanager->resPrint;
3168 }
3169
3170 return $result;
3171 }
3172
3182 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3183 {
3184 global $langs;
3185
3186 $s = '';
3187 if (empty($option) || preg_match('/prospect/', $option)) {
3188 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3189 $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.dolPrintHTMLForAttribute($langs->trans("Prospect")).'"';
3190 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3191 $s .= '>'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
3192 }
3193 }
3194 if (empty($option) || preg_match('/customer/', $option)) {
3195 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3196 $s .= '<'.$tag.' class="customer-back" title="'.dolPrintHTMLForAttribute($langs->trans("Customer")).'"';
3197 $s.= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'"' : '';
3198 $s .= '>'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
3199 }
3200 }
3201 if (empty($option) || preg_match('/supplier/', $option)) {
3202 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3203 $s .= '<'.$tag.' class="vendor-back" title="'.dolPrintHTMLForAttribute($langs->trans("Supplier")).'"';
3204 $s .= $tag == 'a' ? ' href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'"' : '';
3205 $s .= '>'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
3206 }
3207 }
3208
3209 return $s;
3210 }
3211
3212
3219 public function getLibStatut($mode = 0)
3220 {
3221 return $this->LibStatut($this->status, $mode);
3222 }
3223
3224 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3232 public function LibStatut($status, $mode = 0)
3233 {
3234 // phpcs:enable
3235 global $langs;
3236 $langs->load('companies');
3237
3238 $statusType = 'status4';
3239 if ($status == 0) {
3240 $statusType = 'status6';
3241 }
3242
3243 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3244 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3245 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3246 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3247 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3248 }
3249
3250 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3251 }
3252
3253 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3260 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3261 {
3262 // phpcs:enable
3263 global $langs;
3264
3265 $contact_emails = $this->contact_property_array('email', 1);
3266
3267 if ($this->email && $addthirdparty) {
3268 if (empty($this->name)) {
3269 $this->name = $this->nom;
3270 }
3271 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3272 }
3273
3274 //var_dump($contact_emails)
3275 return $contact_emails;
3276 }
3277
3278 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3285 {
3286 // phpcs:enable
3287 global $langs;
3288
3289 $contact_phone = $this->contact_property_array('mobile');
3290
3291 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3292 if (empty($this->name)) {
3293 $this->name = $this->nom;
3294 }
3295 // TODO: Tester si tel non deja present dans tableau contact
3296 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3297 }
3298 return $contact_phone;
3299 }
3300
3301 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3309 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3310 {
3311 // phpcs:enable
3312 global $langs;
3313
3314 $contact_property = array();
3315
3316
3317 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3318 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3319 $sql .= " WHERE fk_soc = ".((int) $this->id);
3320 $sql .= " AND entity IN (".getEntity($this->element).")";
3321 $sql .= " ORDER BY lastname, firstname";
3322
3323 $resql = $this->db->query($sql);
3324 if ($resql) {
3325 $nump = $this->db->num_rows($resql);
3326 if ($nump) {
3327 $sepa = "(";
3328 $sepb = ")";
3329 if ($mode == 'email') {
3330 //$sepa="&lt;"; $sepb="&gt;";
3331 $sepa = "<";
3332 $sepb = ">";
3333 }
3334 $i = 0;
3335 while ($i < $nump) {
3336 $obj = $this->db->fetch_object($resql);
3337 if ($mode == 'email') {
3338 $property = $obj->email;
3339 } elseif ($mode == 'mobile') {
3340 $property = $obj->phone_mobile;
3341 } else {
3342 $property = $obj->$mode;
3343 }
3344
3345 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3346 if ($obj->status == 1 || empty($hidedisabled)) {
3347 if (empty($property)) {
3348 if ($mode == 'email') {
3349 $property = $langs->transnoentitiesnoconv("NoEMail");
3350 } elseif ($mode == 'mobile') {
3351 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3352 }
3353 }
3354
3355 if (!empty($obj->poste)) {
3356 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3357 } else {
3358 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3359 }
3360 }
3361 $i++;
3362 }
3363 }
3364 } else {
3365 dol_print_error($this->db);
3366 }
3367 return $contact_property;
3368 }
3369
3370
3371 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3377 public function contact_array()
3378 {
3379 // phpcs:enable
3380 $contacts = array();
3381
3382 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3383 $resql = $this->db->query($sql);
3384 if ($resql) {
3385 $nump = $this->db->num_rows($resql);
3386 if ($nump) {
3387 $i = 0;
3388 while ($i < $nump) {
3389 $obj = $this->db->fetch_object($resql);
3390 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3391 $i++;
3392 }
3393 }
3394 } else {
3395 dol_print_error($this->db);
3396 }
3397 return $contacts;
3398 }
3399
3400 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3406 public function contact_array_objects()
3407 {
3408 // phpcs:enable
3409 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3410 $contacts = array();
3411
3412 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3413 $resql = $this->db->query($sql);
3414 if ($resql) {
3415 $nump = $this->db->num_rows($resql);
3416 if ($nump) {
3417 $i = 0;
3418 while ($i < $nump) {
3419 $obj = $this->db->fetch_object($resql);
3420 $contact = new Contact($this->db);
3421 $contact->fetch($obj->rowid);
3422 $contacts[] = $contact;
3423 $i++;
3424 }
3425 }
3426 } else {
3427 dol_print_error($this->db);
3428 }
3429 return $contacts;
3430 }
3431
3432 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3440 public function contact_get_property($rowid, $mode)
3441 {
3442 // phpcs:enable
3443 $contact_property = '';
3444
3445 if (empty($rowid)) {
3446 return '';
3447 }
3448
3449 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3450 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3451 $sql .= " WHERE rowid = ".((int) $rowid);
3452
3453 $resql = $this->db->query($sql);
3454 if ($resql) {
3455 $nump = $this->db->num_rows($resql);
3456
3457 if ($nump) {
3458 $obj = $this->db->fetch_object($resql);
3459
3460 if ($mode == 'email') {
3461 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3462 } elseif ($mode == 'mobile') {
3463 $contact_property = $obj->phone_mobile;
3464 }
3465 }
3466 return $contact_property;
3467 } else {
3468 dol_print_error($this->db);
3469 }
3470
3471 return '';
3472 }
3473
3474
3475 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3482 public function display_rib($mode = 'label')
3483 {
3484 // phpcs:enable
3485 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3486
3487 $bac = new CompanyBankAccount($this->db);
3488 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3489 $bac->fetch(0, '', $this->id);
3490
3491 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3492 if ($mode == 'label') {
3493 return $bac->getRibLabel(true);
3494 } elseif ($mode == 'rum') {
3495 if (empty($bac->rum)) {
3496 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3497 $prelevement = new BonPrelevement($this->db);
3498 $bac->fetch_thirdparty();
3499 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3500 }
3501 return $bac->rum;
3502 } elseif ($mode == 'format') {
3503 return $bac->frstrecur;
3504 } else {
3505 return 'BadParameterToFunctionDisplayRib';
3506 }
3507 } else {
3508 return '';
3509 }
3510 }
3511
3512 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3518 public function get_all_rib()
3519 {
3520 // phpcs:enable
3521 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3522 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND fk_soc = ".((int) $this->id);
3523 $result = $this->db->query($sql);
3524 if (!$result) {
3525 $this->error = $this->db->lasterror();
3526 $this->errors[] = $this->db->lasterror();
3527 return 0;
3528 } else {
3529 $num_rows = $this->db->num_rows($result);
3530 $rib_array = array();
3531 if ($num_rows) {
3532 while ($obj = $this->db->fetch_object($result)) {
3533 $rib = new CompanyBankAccount($this->db);
3534 $rib->fetch($obj->rowid);
3535 $rib_array[] = $rib;
3536 }
3537 }
3538 return $rib_array;
3539 }
3540 }
3541
3545 public function getDefaultRib()
3546 {
3547 // phpcs:enable
3548 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3549 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type = 'ban' AND default_rib = 1 AND fk_soc = ". (int) $this->id;
3550 $resql = $this->db->query($sql);
3551 if (!$resql) {
3552 $this->error = $this->db->lasterror();
3553 $this->errors[] = $this->db->lasterror();
3554 return -1;
3555 } else {
3556 $num_rows = $this->db->num_rows($resql);
3557 $rib_array = array();
3558 if ($num_rows) {
3559 while ($obj = $this->db->fetch_object($resql)) {
3560 return $obj->rowid;
3561 }
3562 }
3563 return 0;
3564 }
3565 }
3566
3567
3568 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3577 public function get_codeclient($objsoc = null, $type = 0)
3578 {
3579 // phpcs:enable
3580 global $conf;
3581 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3582 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3583
3584 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3585 foreach ($dirsociete as $dirroot) {
3586 $res = dol_include_once($dirroot.$module.'.php');
3587 if ($res) {
3588 break;
3589 }
3590 }
3592 $mod = new $module($this->db);
3593 '@phan-var-force ModeleThirdPartyCode $mod';
3594
3595 $this->code_client = $mod->getNextValue($objsoc, $type);
3596 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3597
3598 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3599 }
3600 }
3601
3602 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3611 public function get_codefournisseur($objsoc = null, $type = 1)
3612 {
3613 // phpcs:enable
3614 global $conf;
3615 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3616 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3617
3618 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3619 foreach ($dirsociete as $dirroot) {
3620 $res = dol_include_once($dirroot.$module.'.php');
3621 if ($res) {
3622 break;
3623 }
3624 }
3626 $mod = new $module($this->db);
3627 '@phan-var-force ModeleThirdPartyCode $mod';
3628
3629 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3630
3631 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3632 }
3633 }
3634
3635 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3642 public function codeclient_modifiable()
3643 {
3644 // phpcs:enable
3645 global $conf;
3646 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3647 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3648
3649 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3650 foreach ($dirsociete as $dirroot) {
3651 $res = dol_include_once($dirroot.$module.'.php');
3652 if ($res) {
3653 break;
3654 }
3655 }
3656
3657 $mod = new $module($this->db);
3658 '@phan-var-force ModeleThirdPartyCode $mod';
3659
3660 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3661 if ($mod->code_modifiable_null && !$this->code_client) {
3662 return 1;
3663 }
3664 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3665 return 1;
3666 }
3667 if ($mod->code_modifiable) {
3668 return 1; // A mettre en dernier
3669 }
3670 return 0;
3671 } else {
3672 return 0;
3673 }
3674 }
3675
3676
3677 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3684 {
3685 // phpcs:enable
3686 global $conf;
3687 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3688 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3689
3690 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3691 foreach ($dirsociete as $dirroot) {
3692 $res = dol_include_once($dirroot.$module.'.php');
3693 if ($res) {
3694 break;
3695 }
3696 }
3697
3698 $mod = new $module($this->db);
3699 '@phan-var-force ModeleThirdPartyCode $mod';
3700
3701 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3702 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3703 return 1;
3704 }
3705 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3706 return 1;
3707 }
3708 if ($mod->code_modifiable) {
3709 return 1; // A mettre en dernier
3710 }
3711 return 0;
3712 } else {
3713 return 0;
3714 }
3715 }
3716
3717
3718 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3730 public function check_codeclient()
3731 {
3732 // phpcs:enable
3733 global $conf;
3734 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3735 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3736
3737 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3738 foreach ($dirsociete as $dirroot) {
3739 $res = dol_include_once($dirroot.$module.'.php');
3740 if ($res) {
3741 break;
3742 }
3743 }
3744
3745 $mod = new $module($this->db);
3746 '@phan-var-force ModeleThirdPartyCode $mod';
3747
3748 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3749 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3750 if ($result) { // If error
3751 $this->error = $mod->error;
3752 $this->errors = $mod->errors;
3753 }
3754 return $result;
3755 } else {
3756 return 0;
3757 }
3758 }
3759
3760 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3772 public function check_codefournisseur()
3773 {
3774 // phpcs:enable
3775 global $conf;
3776 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3777 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3778
3779 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3780 foreach ($dirsociete as $dirroot) {
3781 $res = dol_include_once($dirroot.$module.'.php');
3782 if ($res) {
3783 break;
3784 }
3785 }
3786
3787 $mod = new $module($this->db);
3788 '@phan-var-force ModeleThirdPartyCode $mod';
3789
3790 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3791 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3792 if ($result) { // If error
3793 $this->error = $mod->error;
3794 $this->errors = $mod->errors;
3795 }
3796 return $result;
3797 } else {
3798 return 0;
3799 }
3800 }
3801
3802 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3811 public function get_codecompta($type)
3812 {
3813 // phpcs:enable
3814 global $conf;
3815
3816 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3817 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
3818 $res = false;
3819 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3820 foreach ($dirsociete as $dirroot) {
3821 $res = dol_include_once($dirroot.$module.'.php');
3822 if ($res) {
3823 break;
3824 }
3825 }
3826
3827 if ($res) {
3828 $mod = new $module();
3829 '@phan-var-force ModeleAccountancyCode $mod';
3830
3831 // Set code count in $mod->code
3832 $result = $mod->get_code($this->db, $this, $type);
3833
3834 if ($type == 'customer') {
3835 $this->code_compta_client = $mod->code;
3836 } elseif ($type == 'supplier') {
3837 $this->code_compta_fournisseur = $mod->code;
3838 }
3839
3840 return $result;
3841 } else {
3842 $this->error = 'ErrorAccountancyCodeNotDefined';
3843 return -1;
3844 }
3845 } else {
3846 if ($type == 'customer') {
3847 $this->code_compta_client = '';
3848 } elseif ($type == 'supplier') {
3849 $this->code_compta_fournisseur = '';
3850 }
3851
3852 return 0;
3853 }
3854 }
3855
3862 public function setParent($id)
3863 {
3864 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3865
3866 if ($this->id) {
3867 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3868 if ($id > 0) {
3869 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3870 if ($sameparent < 0) {
3871 return -1;
3872 }
3873 if ($sameparent == 1) {
3874 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3875 return -1;
3876 }
3877 }
3878
3879 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3880
3881 $resql = $this->db->query($sql);
3882 if ($resql) {
3883 $this->parent = $id;
3884 return 1;
3885 } else {
3886 return -1;
3887 }
3888 }
3889
3890 return -1;
3891 }
3892
3901 public function validateFamilyTree($idparent, $idchild, $counter = 0)
3902 {
3903 if ($counter > 100) {
3904 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3905 }
3906
3907 $sql = 'SELECT s.parent';
3908 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3909 $sql .= ' WHERE rowid = '.((int) $idparent);
3910 $resql = $this->db->query($sql);
3911 if ($resql) {
3912 $obj = $this->db->fetch_object($resql);
3913
3914 if ($obj->parent == '') {
3915 return 0;
3916 } elseif ($obj->parent == $idchild) {
3917 return 1;
3918 } else {
3919 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3920 }
3921 return $sameparent;
3922 } else {
3923 return -1;
3924 }
3925 }
3926
3934 public function getParentsForCompany($company_id, $parents = array())
3935 {
3936 global $langs;
3937
3938 if ($company_id > 0) {
3939 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3940 $resql = $this->db->query($sql);
3941 if ($resql) {
3942 if ($obj = $this->db->fetch_object($resql)) {
3943 $parent = $obj->parent;
3944 if ($parent > 0 && !in_array($parent, $parents)) {
3945 $parents[] = $parent;
3946 return $this->getParentsForCompany($parent, $parents);
3947 } else {
3948 return $parents;
3949 }
3950 }
3951 $this->db->free($resql);
3952 } else {
3953 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3954 }
3955 }
3956 // Return a default value when $company_id is not greater than 0
3957 return array();
3958 }
3959
3960 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3967 public function id_prof_verifiable($idprof)
3968 {
3969 // phpcs:enable
3970 global $conf;
3971
3972 switch ($idprof) {
3973 case 1:
3974 $ret = getDolGlobalBool('SOCIETE_IDPROF1_UNIQUE');
3975 break;
3976 case 2:
3977 $ret = getDolGlobalBool('SOCIETE_IDPROF2_UNIQUE');
3978 break;
3979 case 3:
3980 $ret = getDolGlobalBool('SOCIETE_IDPROF3_UNIQUE');
3981 break;
3982 case 4:
3983 $ret = getDolGlobalBool('SOCIETE_IDPROF4_UNIQUE');
3984 break;
3985 case 5:
3986 $ret = getDolGlobalBool('SOCIETE_IDPROF5_UNIQUE');
3987 break;
3988 case 6:
3989 $ret = getDolGlobalBool('SOCIETE_IDPROF6_UNIQUE');
3990 break;
3991 default:
3992 $ret = false;
3993 }
3994
3995 return $ret;
3996 }
3997
3998 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4007 public function id_prof_exists($idprof, $value, $socid = 0)
4008 {
4009 // phpcs:enable
4010 $field = $idprof;
4011
4012 switch ($idprof) { // For backward compatibility
4013 case '1':
4014 case 'idprof1':
4015 $field = "siren";
4016 break;
4017 case '2':
4018 case 'idprof2':
4019 $field = "siret";
4020 break;
4021 case '3':
4022 case 'idprof3':
4023 $field = "ape";
4024 break;
4025 case '4':
4026 case 'idprof4':
4027 $field = "idprof4";
4028 break;
4029 case '5':
4030 $field = "idprof5";
4031 break;
4032 case '6':
4033 $field = "idprof6";
4034 break;
4035 }
4036
4037 //Verify duplicate entries
4038 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
4039 if ($socid) {
4040 $sql .= " AND rowid <> ".$socid;
4041 }
4042 $resql = $this->db->query($sql);
4043 if ($resql) {
4044 $obj = $this->db->fetch_object($resql);
4045 $count = $obj->nb;
4046 } else {
4047 $count = 0;
4048 print $this->db->error();
4049 }
4050 $this->db->free($resql);
4051
4052 if ($count > 0) {
4053 return true;
4054 } else {
4055 return false;
4056 }
4057 }
4058
4059 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4068 public function id_prof_check($idprof, $soc)
4069 {
4070 // phpcs:enable
4071 global $conf;
4072
4073 // load the library necessary to check the professional identifiers
4074 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
4075
4076 $ok = 1;
4077
4078 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4079 return 1;
4080 }
4081
4082 // Check SIREN
4083 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
4084 return -1;
4085 }
4086
4087 // Check SIRET
4088 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
4089 return -1;
4090 }
4091
4092 //Verify CIF/NIF/NIE if pays ES
4093 if ($idprof == 1 && $soc->country_code == 'ES') {
4094 return isValidTinForES($this->idprof1);
4095 }
4096
4097 //Verify NIF if country is PT
4098 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
4099 return -1;
4100 }
4101
4102 //Verify NIF if country is DZ
4103 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
4104 return -1;
4105 }
4106
4107 //Verify ID Prof 1 if country is BE
4108 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
4109 return -1;
4110 }
4111
4112 return $ok;
4113 }
4114
4115 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4124 public function id_prof_url($idprof, $thirdparty)
4125 {
4126 // phpcs:enable
4127 global $conf, $langs, $hookmanager;
4128
4129 $url = '';
4130 $action = '';
4131
4132 $hookmanager->initHooks(array('idprofurl'));
4133 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4134 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4135 if (empty($reshook)) {
4136 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4137 return '';
4138 }
4139
4140 // TODO Move links to validate professional ID into a dictionary table "country" + "link"
4141 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4142 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4143 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
4144 }
4145 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4146 $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
4147 }
4148 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4149 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
4150 }
4151 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4152 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4153 }
4154 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4155 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
4156 }
4157 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4158 $url = 'http://www.nif.pt/'.$strippedIdProf1;
4159 }
4160
4161 if ($url) {
4162 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4163 }
4164 } else {
4165 return $hookmanager->resPrint;
4166 }
4167
4168 return '';
4169 }
4170
4171 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4177 public function has_projects()
4178 {
4179 // phpcs:enable
4180 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4181 $resql = $this->db->query($sql);
4182 if ($resql) {
4183 $obj = $this->db->fetch_object($resql);
4184 $count = $obj->numproj;
4185 } else {
4186 $count = 0;
4187 print $this->db->error();
4188 }
4189 $this->db->free($resql);
4190 return ($count > 0);
4191 }
4192
4193
4200 public function info($id)
4201 {
4202 $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4203 $sql .= " fk_user_creat, fk_user_modif";
4204 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4205 $sql .= " WHERE s.rowid = ".((int) $id);
4206
4207 $result = $this->db->query($sql);
4208 if ($result) {
4209 if ($this->db->num_rows($result)) {
4210 $obj = $this->db->fetch_object($result);
4211
4212 $this->id = $obj->rowid;
4213
4214 $this->user_creation_id = $obj->fk_user_creat;
4215 $this->user_modification_id = $obj->fk_user_modif;
4216 $this->date_creation = $this->db->jdate($obj->datec);
4217 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4218
4219 $this->ref = $obj->name;
4220 }
4221
4222 $this->db->free($result);
4223 } else {
4224 dol_print_error($this->db);
4225 }
4226 }
4227
4233 public function isACompany()
4234 {
4235 // Define if third party is treated as company (or not) when nature is unknown
4236 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES', 1); // default if not set is 1 because it was like this in all past versions
4237
4238 // Now try to guess using different tips
4239 if (!empty($this->tva_intra)) {
4240 $isACompany = 1;
4241 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4242 $isACompany = 1;
4243 } else {
4244 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) { // never or rarely set
4245 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) { // TODO Add a field is_a_company into dictionary
4246 $isACompany = 0;
4247 }
4248 } else {
4249 $isACompany = 1;
4250 }
4251 }
4252
4253 return (bool) $isACompany;
4254 }
4255
4261 public function isInEEC()
4262 {
4263 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4264 return isInEEC($this);
4265 }
4266
4267 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4273 public function LoadSupplierCateg()
4274 {
4275 // phpcs:enable
4276 $this->SupplierCategories = array();
4277 $sql = "SELECT rowid, label";
4278 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4279 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4280
4281 $resql = $this->db->query($sql);
4282 if ($resql) {
4283 while ($obj = $this->db->fetch_object($resql)) {
4284 $this->SupplierCategories[$obj->rowid] = $obj->label;
4285 }
4286 return 0;
4287 } else {
4288 return -1;
4289 }
4290 }
4291
4292 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4299 public function AddFournisseurInCategory($categorie_id)
4300 {
4301 // phpcs:enable
4302 if ($categorie_id > 0 && $this->id > 0) {
4303 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4304 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4305
4306 if ($resql = $this->db->query($sql)) {
4307 return 0;
4308 }
4309 } else {
4310 return 0;
4311 }
4312 return -1;
4313 }
4314
4320 public function getNbOfEMailings()
4321 {
4322 $sql = "SELECT count(mc.email) as nb";
4323 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4324 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4325 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4326
4327 $resql = $this->db->query($sql);
4328 if ($resql) {
4329 $obj = $this->db->fetch_object($resql);
4330 $nb = $obj->nb;
4331
4332 $this->db->free($resql);
4333 return $nb;
4334 } else {
4335 $this->error = $this->db->error();
4336 return -1;
4337 }
4338 }
4339
4346 public function setNoEmail($no_email)
4347 {
4348 $error = 0;
4349
4350 // Update mass emailing flag into table mailing_unsubscribe
4351 if ($this->email) {
4352 $this->db->begin();
4353
4354 if ($no_email) {
4355 $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)."'";
4356 $resql = $this->db->query($sql);
4357 if ($resql) {
4358 $obj = $this->db->fetch_object($resql);
4359 $noemail = $obj->nb;
4360 if (empty($noemail)) {
4361 $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())."')";
4362 $resql = $this->db->query($sql);
4363 if (!$resql) {
4364 $error++;
4365 $this->error = $this->db->lasterror();
4366 $this->errors[] = $this->error;
4367 }
4368 }
4369 } else {
4370 $error++;
4371 $this->error = $this->db->lasterror();
4372 $this->errors[] = $this->error;
4373 }
4374 } else {
4375 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4376 $resql = $this->db->query($sql);
4377 if (!$resql) {
4378 $error++;
4379 $this->error = $this->db->lasterror();
4380 $this->errors[] = $this->error;
4381 }
4382 }
4383
4384 if (empty($error)) {
4385 $this->no_email = $no_email;
4386 $this->db->commit();
4387 return 1;
4388 } else {
4389 $this->db->rollback();
4390 return $error * -1;
4391 }
4392 }
4393
4394 return 0;
4395 }
4396
4403 public function getNoEmail()
4404 {
4405 if ($this->email) {
4406 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4407 $resql = $this->db->query($sql);
4408 if ($resql) {
4409 $obj = $this->db->fetch_object($resql);
4410 $this->no_email = $obj->nb;
4411 return 1;
4412 } else {
4413 $this->error = $this->db->lasterror();
4414 $this->errors[] = $this->error;
4415 return -1;
4416 }
4417 }
4418 return 0;
4419 }
4420
4421 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4431 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4432 {
4433 // phpcs:enable
4434 global $conf, $user, $langs;
4435
4436 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4437 $fullname = $member->getFullName($langs);
4438
4439 if ($member->morphy == 'mor') {
4440 if (empty($socname)) {
4441 $socname = $member->company ? $member->company : $member->societe;
4442 }
4443 if (!empty($fullname) && empty($socalias)) {
4444 $socalias = $fullname;
4445 }
4446 } elseif (empty($socname) && $member->morphy == 'phy') {
4447 if (empty($socname)) {
4448 $socname = $fullname;
4449 }
4450 if (!empty($member->company) && empty($socalias)) {
4451 $socalias = $member->company;
4452 }
4453 }
4454
4455 $name = $socname;
4456 $alias = $socalias ? $socalias : '';
4457
4458 // Positionne parameters
4459 $this->nom = $name; // TODO deprecated
4460 $this->name = $name;
4461 $this->name_alias = $alias;
4462 $this->address = $member->address;
4463 $this->zip = $member->zip;
4464 $this->town = $member->town;
4465 $this->country_code = $member->country_code;
4466 $this->country_id = $member->country_id;
4467 $this->phone = $member->phone; // Prof phone
4468 $this->email = $member->email;
4469 $this->socialnetworks = $member->socialnetworks;
4470 $this->entity = $member->entity;
4471
4472 $this->client = 1; // A member is a customer by default
4473 $this->code_client = ($customercode ? $customercode : -1);
4474 $this->code_fournisseur = '-1';
4475 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4476 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4477
4478 $this->db->begin();
4479
4480 // Cree et positionne $this->id
4481 $result = $this->create($user);
4482
4483 if ($result >= 0) {
4484 // Auto-create contact on thirdparty creation
4485 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4486 // Fill fields needed by contact
4487 $this->name_bis = $member->lastname;
4488 $this->firstname = $member->firstname;
4489 $this->civility_id = $member->civility_id;
4490
4491 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4492 $result = $this->create_individual($user);
4493
4494 if ($result < 0) {
4495 setEventMessages($this->error, $this->errors, 'errors');
4496 $this->db->rollback();
4497 return -1;
4498 }
4499 }
4500
4501 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4502 $sql .= " SET fk_soc = ".((int) $this->id);
4503 $sql .= " WHERE rowid = ".((int) $member->id);
4504
4505 $resql = $this->db->query($sql);
4506 if ($resql) {
4507 $this->db->commit();
4508 return $this->id;
4509 } else {
4510 $this->error = $this->db->error();
4511
4512 $this->db->rollback();
4513 return -1;
4514 }
4515 } else {
4516 // $this->error deja positionne
4517 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4518
4519 $this->db->rollback();
4520 return $result;
4521 }
4522 }
4523
4530 public function setMysoc(Conf $conf)
4531 {
4532 global $langs;
4533
4534 $this->id = 0;
4535 $this->entity = $conf->entity;
4536 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4537 $this->nom = $this->name; // deprecated
4538 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4539 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4540 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4541 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4542
4543 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4544
4545 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4546
4547 // We define country_id, country_code and country
4548 $country_id = 0;
4549 $country_code = $country_label = '';
4550 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4551 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4552 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4553 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4554 $country_code = $tmp[1];
4555 $country_label = $tmp[2];
4556 } else {
4557 // For backward compatibility
4558 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4559 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4560 $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
4561 $country_label = getCountry($country_id, '', $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4562 }
4563 }
4564 $this->country_id = $country_id;
4565 $this->country_code = $country_code;
4566 $this->country = $country_label;
4567 if (is_object($langs)) {
4568 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4569 }
4570
4571 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4572 // We define state_id, state_code and state
4573 $state_id = 0;
4574 $state_code = '';
4575 $state_label = '';
4576 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4577 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4578 $state_id = (int) $tmp[0];
4579 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4580 $state_code = $tmp[1];
4581 $state_label = $tmp[2];
4582 } else { // For backward compatibility
4583 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);
4584 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4585 $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
4586 $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
4587 }
4588 }
4589 $this->state_id = $state_id;
4590 $this->state_code = $state_code;
4591 $this->state = $state_label;
4592 if (is_object($langs)) {
4593 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4594 }
4595
4596 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4597 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4598 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4599 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4600
4601 // Social networks
4602 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4603 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4604 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4605 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4606 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4607 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4608 $this->socialnetworks = array();
4609 if (!empty($facebook_url)) {
4610 $this->socialnetworks['facebook'] = $facebook_url;
4611 }
4612 if (!empty($twitter_url)) {
4613 $this->socialnetworks['twitter'] = $twitter_url;
4614 }
4615 if (!empty($linkedin_url)) {
4616 $this->socialnetworks['linkedin'] = $linkedin_url;
4617 }
4618 if (!empty($instagram_url)) {
4619 $this->socialnetworks['instagram'] = $instagram_url;
4620 }
4621 if (!empty($youtube_url)) {
4622 $this->socialnetworks['youtube'] = $youtube_url;
4623 }
4624 if (!empty($github_url)) {
4625 $this->socialnetworks['github'] = $github_url;
4626 }
4627
4628 // Id prof generiques
4629 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4630 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4631 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4632 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4633 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4634 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4635 $this->idprof7 = getDolGlobalString('MAIN_INFO_PROFID7');
4636 $this->idprof8 = getDolGlobalString('MAIN_INFO_PROFID8');
4637 $this->idprof9 = getDolGlobalString('MAIN_INFO_PROFID9');
4638 $this->idprof10 = getDolGlobalString('MAIN_INFO_PROFID10');
4639 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4640 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4641 $this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;
4642 $this->forme_juridique_code = getDolGlobalInt('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4643 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4644 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4645 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4646 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4647 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4648 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4649 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4650 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4651
4652 // Define if company use vat or not
4653 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4654
4655 // Define if company use local taxes
4656 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4657 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4658
4659 $this->termsofsale = getDolGlobalString('MAIN_INFO_SOCIETE_TERMSOFSALE');
4660 }
4661
4669 public function initAsSpecimen()
4670 {
4671 $now = dol_now();
4672
4673 // Initialize parameters
4674 $this->id = 0;
4675 $this->entity = 1;
4676 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4677 $this->nom = $this->name; // For backward compatibility
4678 $this->ref_ext = 'Ref ext';
4679 $this->specimen = 1;
4680 $this->address = '21 jump street';
4681 $this->zip = '99999';
4682 $this->town = 'MyTown';
4683 $this->state_id = 1;
4684 $this->state_code = 'AA';
4685 $this->state = 'MyState';
4686 $this->country_id = 1;
4687 $this->country_code = 'FR';
4688 $this->email = 'specimen@specimen.com';
4689 $this->socialnetworks = array(
4690 'skype' => 'skypepseudo',
4691 'twitter' => 'twitterpseudo',
4692 'facebook' => 'facebookpseudo',
4693 'linkedin' => 'linkedinpseudo',
4694 );
4695 $this->url = 'http://www.specimen.com';
4696
4697 $this->phone = '0909090901';
4698 $this->phone_mobile = '0909090901';
4699 $this->fax = '0909090909';
4700
4701 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4702 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4703 $this->typent_code = 'TE_OTHER';
4704 $this->capital = 10000;
4705 $this->client = 1;
4706 $this->prospect = 1;
4707 $this->fournisseur = 1;
4708 $this->tva_assuj = 1;
4709 $this->tva_intra = 'EU1234567';
4710 $this->note_public = 'This is a comment (public)';
4711 $this->note_private = 'This is a comment (private)';
4712
4713 $this->idprof1 = 'idprof1';
4714 $this->idprof2 = 'idprof2';
4715 $this->idprof3 = 'idprof3';
4716 $this->idprof4 = 'idprof4';
4717 $this->idprof5 = 'idprof5';
4718 $this->idprof6 = 'idprof6';
4719
4720 return 1;
4721 }
4722
4729 public function useLocalTax($localTaxNum = 0)
4730 {
4731 $sql = "SELECT t.localtax1, t.localtax2";
4732 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4733 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4734 $sql .= " AND t.active = 1";
4735 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4736 if (empty($localTaxNum)) {
4737 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4738 } elseif ($localTaxNum == 1) {
4739 $sql .= " AND t.localtax1_type <> '0'";
4740 } elseif ($localTaxNum == 2) {
4741 $sql .= " AND t.localtax2_type <> '0'";
4742 }
4743
4744 $resql = $this->db->query($sql);
4745 if ($resql) {
4746 return ($this->db->num_rows($resql) > 0);
4747 } else {
4748 return false;
4749 }
4750 }
4751
4757 public function useNPR()
4758 {
4759 $sql = "SELECT t.rowid";
4760 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4761 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4762 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4763 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4764
4765 dol_syslog("useNPR", LOG_DEBUG);
4766 $resql = $this->db->query($sql);
4767 if ($resql) {
4768 return ($this->db->num_rows($resql) > 0);
4769 } else {
4770 return false;
4771 }
4772 }
4773
4780 public function useRevenueStamp()
4781 {
4782 $sql = "SELECT COUNT(*) as nb";
4783 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4784 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4785 $sql .= " AND r.active = 1";
4786
4787 dol_syslog("useRevenueStamp", LOG_DEBUG);
4788 $resql = $this->db->query($sql);
4789 if ($resql) {
4790 $obj = $this->db->fetch_object($resql);
4791 return ($obj->nb > 0);
4792 } else {
4793 $this->error = $this->db->lasterror();
4794 return false;
4795 }
4796 }
4797
4803 public function getLibProspLevel()
4804 {
4805 return $this->LibProspLevel($this->fk_prospectlevel);
4806 }
4807
4808 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4815 public function LibProspLevel($fk_prospectlevel)
4816 {
4817 // phpcs:enable
4818 global $langs;
4819
4820 $label = '';
4821 if ($fk_prospectlevel != '') {
4822 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
4823 // If label is not found in language file, we get label from cache/database
4824 if ($label == "ProspectLevel".$fk_prospectlevel) {
4825 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4826 }
4827 }
4828
4829 return $label;
4830 }
4831
4839 public function getLibProspCommStatut($mode = 0, $label = '')
4840 {
4841 return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4842 }
4843
4844 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4858 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4859 {
4860 // phpcs:enable
4861 global $langs;
4862
4863 $langs->load('customers');
4864
4865 if ($mode == 2) {
4866 if ($status == '-1' || $status == 'ST_NO') {
4867 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4868 } elseif ($status == '0' || $status == 'ST_NEVER') {
4869 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4870 } elseif ($status == '1' || $status == 'ST_TODO') {
4871 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4872 } elseif ($status == '2' || $status == 'ST_PEND') {
4873 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4874 } elseif ($status == '3' || $status == 'ST_DONE') {
4875 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4876 } else {
4877 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);
4878 }
4879 } elseif ($mode == 3) {
4880 if ($status == '-1' || $status == 'ST_NO') {
4881 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"');
4882 } elseif ($status == '0' || $status == 'ST_NEVER') {
4883 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"');
4884 } elseif ($status == '1' || $status == 'ST_TODO') {
4885 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"');
4886 } elseif ($status == '2' || $status == 'ST_PEND') {
4887 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"');
4888 } elseif ($status == '3' || $status == 'ST_DONE') {
4889 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"');
4890 } else {
4891 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, '0', $picto, 'class="inline-block valignmiddle"');
4892 }
4893 } elseif ($mode == 4) {
4894 if ($status == '-1' || $status == 'ST_NO') {
4895 return img_action($langs->trans("StatusProspect-1"), '-1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4896 } elseif ($status == '0' || $status == 'ST_NEVER') {
4897 return img_action($langs->trans("StatusProspect0"), '0', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4898 } elseif ($status == '1' || $status == 'ST_TODO') {
4899 return img_action($langs->trans("StatusProspect1"), '1', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4900 } elseif ($status == '2' || $status == 'ST_PEND') {
4901 return img_action($langs->trans("StatusProspect2"), '2', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4902 } elseif ($status == '3' || $status == 'ST_DONE') {
4903 return img_action($langs->trans("StatusProspect3"), '3', $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4904 } else {
4905 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);
4906 }
4907 }
4908
4909 return "Error, mode/status not found";
4910 }
4911
4918 public function getOutstandingProposals($mode = 'customer')
4919 {
4920 $table = 'propal';
4921 if ($mode == 'supplier') {
4922 $table = 'supplier_proposal';
4923 }
4924
4925 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4926 $sql .= " WHERE fk_soc = ".((int) $this->id);
4927 if ($mode == 'supplier') {
4928 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4929 } else {
4930 $sql .= " AND entity IN (".getEntity('propal').")";
4931 }
4932
4933 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4934
4935 $resql = $this->db->query($sql);
4936 if ($resql) {
4937 $outstandingOpened = 0;
4938 $outstandingTotal = 0;
4939 $outstandingTotalIncTax = 0;
4940 $arrayofref = array();
4941 while ($obj = $this->db->fetch_object($resql)) {
4942 $arrayofref[$obj->rowid] = $obj->ref;
4943 $outstandingTotal += $obj->total_ht;
4944 $outstandingTotalIncTax += $obj->total_ttc;
4945 if ($obj->status != 0) {
4946 // Not a draft
4947 $outstandingOpened += $obj->total_ttc;
4948 }
4949 }
4950 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4951 } else {
4952 return array();
4953 }
4954 }
4955
4962 public function getOutstandingOrders($mode = 'customer')
4963 {
4964 $table = 'commande';
4965 if ($mode == 'supplier') {
4966 $table = 'commande_fournisseur';
4967 }
4968
4969 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4970 $sql .= " WHERE fk_soc = ".((int) $this->id);
4971 if ($mode == 'supplier') {
4972 $sql .= " AND entity IN (".getEntity('supplier_order').")";
4973 } else {
4974 $sql .= " AND entity IN (".getEntity('commande').")";
4975 }
4976
4977 dol_syslog("getOutstandingOrders", LOG_DEBUG);
4978 $resql = $this->db->query($sql);
4979 if ($resql) {
4980 $outstandingOpened = 0;
4981 $outstandingTotal = 0;
4982 $outstandingTotalIncTax = 0;
4983 $arrayofref = array();
4984 while ($obj = $this->db->fetch_object($resql)) {
4985 $arrayofref[$obj->rowid] = $obj->ref;
4986 $outstandingTotal += $obj->total_ht;
4987 $outstandingTotalIncTax += $obj->total_ttc;
4988 if ($obj->status != 0) {
4989 // Not a draft
4990 $outstandingOpened += $obj->total_ttc;
4991 }
4992 }
4993 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4994 } else {
4995 return array();
4996 }
4997 }
4998
5006 public function getOutstandingBills($mode = 'customer', $late = 0)
5007 {
5008 $table = 'facture';
5009 if ($mode == 'supplier') {
5010 $table = 'facture_fourn';
5011 }
5012
5013 /* Accurate value of remain to pay is to sum remaintopay for each invoice
5014 $paiement = $invoice->getSommePaiement();
5015 $creditnotes=$invoice->getSumCreditNotesUsed();
5016 $deposits=$invoice->getSumDepositsUsed();
5017 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
5018 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
5019 */
5020 $today = dol_get_first_hour(dol_now('tzuser')); // Returns today at 00:00 in the user's time zone
5021
5022 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
5023 $sql .= " WHERE fk_soc = ".((int) $this->id);
5024 if (!empty($late)) {
5025 $sql .= " AND date_lim_reglement < '".$this->db->idate($today)."'";
5026 }
5027 if ($mode == 'supplier') {
5028 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
5029 } else {
5030 $sql .= " AND entity IN (".getEntity('invoice').")";
5031 }
5032
5033 dol_syslog("getOutstandingBills", LOG_DEBUG);
5034 $resql = $this->db->query($sql);
5035 if ($resql) {
5036 $outstandingOpened = 0;
5037 $outstandingTotal = 0;
5038 $outstandingTotalIncTax = 0;
5039 $arrayofref = array();
5040 $arrayofrefopened = array();
5041 if ($mode == 'supplier') {
5042 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
5043 $tmpobject = new FactureFournisseur($this->db);
5044 } else {
5045 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
5046 $tmpobject = new Facture($this->db);
5047 }
5048 while ($obj = $this->db->fetch_object($resql)) {
5049 $arrayofref[$obj->rowid] = $obj->ref;
5050 $tmpobject->id = $obj->rowid;
5051
5052 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5053 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
5054 ) {
5055 $outstandingTotal += $obj->total_ht;
5056 $outstandingTotalIncTax += $obj->total_ttc;
5057 }
5058
5059 $remaintopay = 0;
5060
5061 if ($obj->paye == 0
5062 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
5063 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
5064 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
5065 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
5066 $paiement = $tmpobject->getSommePaiement();
5067 $creditnotes = $tmpobject->getSumCreditNotesUsed();
5068 $deposits = $tmpobject->getSumDepositsUsed();
5069
5070 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
5071 $outstandingOpened += $remaintopay;
5072 }
5073
5074 //if credit note is converted but not used
5075 // TODO Do this also for customer ?
5076 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
5077 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
5078 $remaintopay -= $remainingcreditnote;
5079 $outstandingOpened -= $remainingcreditnote;
5080 }
5081
5082 if ($remaintopay) {
5083 $arrayofrefopened[$obj->rowid] = $obj->ref;
5084 }
5085 }
5086 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'incl taxes'
5087 } else {
5088 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
5089 return array();
5090 }
5091 }
5092
5099 public function getLibCustProspStatut()
5100 {
5101 return $this->LibCustProspStatut($this->client);
5102 }
5103
5104 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5111 public function LibCustProspStatut($status)
5112 {
5113 // phpcs:enable
5114 global $langs;
5115 $langs->load('companies');
5116
5117 if ($status == 0) {
5118 return $langs->trans("NorProspectNorCustomer");
5119 } elseif ($status == 1) {
5120 return $langs->trans("Customer");
5121 } elseif ($status == 2) {
5122 return $langs->trans("Prospect");
5123 } elseif ($status == 3) {
5124 return $langs->trans("ProspectCustomer");
5125 }
5126
5127 return '';
5128 }
5129
5130
5142 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5143 {
5144 global $langs;
5145
5146 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5147 $modelpath = "core/modules/bank/doc/";
5148
5149 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5150 $companybankaccount = new CompanyBankAccount($this->db);
5151 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5152 if (!$result) {
5153 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5154 }
5155 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5156 $this->last_main_doc = $companybankaccount->last_main_doc;
5157 } else {
5158 // Positionne le modele sur le nom du modele a utiliser
5159 if (!dol_strlen($modele)) {
5160 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5161 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5162 } else {
5163 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5164 return 0;
5165 }
5166 }
5167
5168 if (!isset($this->bank_account)) {
5169 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5170 $bac = new CompanyBankAccount($this->db);
5171 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5172 $result = $bac->fetch(0, '', $this->id);
5173 if ($result > 0) {
5174 $this->bank_account = $bac;
5175 } else {
5176 $this->bank_account = '';
5177 }
5178 }
5179
5180 $modelpath = "core/modules/societe/doc/";
5181
5182 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5183 }
5184
5185 return $result;
5186 }
5187
5188
5200 public function setCategories($categories, $type_categ)
5201 {
5202 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5203
5204 // Decode type
5205 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5206 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5207 return -1;
5208 }
5209
5210 return parent::setCategoriesCommon($categories, $type_categ);
5211 }
5212
5220 public function setSalesRep($salesrep, $onlyAdd = false)
5221 {
5222 global $user;
5223
5224 // Handle single user
5225 if (!is_array($salesrep)) {
5226 $salesrep = array($salesrep);
5227 }
5228
5229 $to_del = array(); // Nothing to delete
5230 $to_add = $salesrep;
5231 if ($onlyAdd === false) {
5232 // Get current users
5233 $existing = $this->getSalesRepresentatives($user, 1);
5234
5235 // Diff
5236 if (is_array($existing)) {
5237 $to_del = array_diff($existing, $salesrep);
5238 $to_add = array_diff($salesrep, $existing);
5239 }
5240 }
5241
5242 $error = 0;
5243
5244 // Process
5245 foreach ($to_del as $del) {
5246 $this->del_commercial($user, $del);
5247 }
5248 foreach ($to_add as $add) {
5249 $result = $this->add_commercial($user, $add);
5250 if ($result < 0) {
5251 $error++;
5252 break;
5253 }
5254 }
5255
5256 return $error ? -1 : 1;
5257 }
5258
5265 public function setThirdpartyType($typent_id)
5266 {
5267 global $user;
5268
5269 dol_syslog(__METHOD__, LOG_DEBUG);
5270
5271 if ($this->id) {
5272 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5273
5274 if ($result > 0) {
5275 $this->typent_id = $typent_id;
5276 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5277 return 1;
5278 } else {
5279 return -1;
5280 }
5281 } else {
5282 return -1;
5283 }
5284 }
5285
5295 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5296 {
5297 if ($origin_id == $dest_id) {
5298 dol_syslog('Error: Try to merge a thirdparty into itself');
5299 return false;
5300 }
5301
5302 // 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.
5303 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5304 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5305 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5306 $sql .= ' SELECT fk_user ';
5307 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5308 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5309
5310 $resql = $dbs->query($sql);
5311 while ($obj = $dbs->fetch_object($resql)) {
5312 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5313 }
5314
5315 // 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.
5316 // Do not include llx_societe because it will be replaced later.
5317 $tables = array(
5318 'societe_account',
5319 'societe_commerciaux',
5320 'societe_prices',
5321 'societe_remise',
5322 'societe_remise_except',
5323 'societe_rib'
5324 );
5325
5326 // TODO When we merge societe_account, we may get 2 lines for the stripe account. Must fix this.
5327
5328 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5329 }
5330
5339 public function setAccountancyCode($type, $value)
5340 {
5341 global $user, $langs, $conf;
5342
5343 $this->db->begin();
5344
5345 if ($type == 'buy') {
5346 $field = 'accountancy_code_buy';
5347 } elseif ($type == 'sell') {
5348 $field = 'accountancy_code_sell';
5349 } else {
5350 return -1;
5351 }
5352
5353 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5354 $sql .= $field." = '".$this->db->escape($value)."'";
5355 $sql .= " WHERE rowid = ".((int) $this->id);
5356
5357 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5358 $resql = $this->db->query($sql);
5359
5360 if ($resql) {
5361 // Call triggers
5362 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5363 $interface = new Interfaces($this->db);
5364 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5365 if ($result < 0) {
5366 $this->errors = $interface->errors;
5367 $this->db->rollback();
5368 return -1;
5369 }
5370 // End call triggers
5371
5372 $this->$field = $value;
5373
5374 $this->db->commit();
5375 return 1;
5376 } else {
5377 $this->error = $this->db->lasterror();
5378 $this->db->rollback();
5379 return -1;
5380 }
5381 }
5382
5389 public function fetchPartnerships($mode)
5390 {
5391 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5392
5393 $this->partnerships[] = array();
5394
5395 return 1;
5396 }
5397
5405 public function getKanbanView($option = '', $arraydata = array())
5406 {
5407 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5408
5409 $return = '<div class="box-flex-item box-flex-grow-zero">';
5410 $return .= '<div class="info-box info-box-sm">';
5411 $return .= '<span class="info-box-icon bg-infobox-action">';
5412 $return .= img_picto('', $this->picto);
5413 $return .= '</span>';
5414 $return .= '<div class="info-box-content">';
5415 $return .= '<div class="info-box-ref inline-block tdoverflowmax125 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref);
5416 $return .= '</div>';
5417 if (!empty($this->phone)) {
5418 $return .= '<div class="inline-block valignmiddle">';
5419 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5420 $return .= dol_print_phone($this->phone, $this->country_code, 0, $this->id, 'tel', 'hidenum', 'phone', $this->phone, 0, 'paddingleft paddingright');
5421 $return .= '</div>';
5422 }
5423 if (!empty($this->email)) {
5424 $return .= '<div class="inline-block valignmiddle">';
5425 $return .= dol_print_email($this->email, 0, $this->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
5426 $return .= '</div>';
5427 }
5428 if ($selected >= 0) {
5429 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5430 }
5431 if (property_exists($this, 'code_client')) {
5432 $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5433 }
5434 if (method_exists($this, 'getLibStatut')) {
5435 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5436 }
5437 $return .= '</div>'; // end info-box-content
5438 $return .= '</div>';
5439 $return .= '</div>';
5440
5441 return $return;
5442 }
5443
5453 public function getContacts($list = 0, $code = '', $element = '')
5454 {
5455 // phpcs:enable
5456 global $langs;
5457
5458 $tab = array();
5459
5460 $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
5461 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5462 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5463 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5464 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5465 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5466 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5467 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5468 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5469 if (!empty($element)) {
5470 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5471 }
5472 if ($code) {
5473 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5474 }
5475 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5476 $sql .= " AND tc.source = 'external'";
5477 $sql .= " AND tc.active = 1";
5478
5479 $sql .= " ORDER BY t.lastname ASC";
5480
5481 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5482 $resql = $this->db->query($sql);
5483 if ($resql) {
5484 $num = $this->db->num_rows($resql);
5485 $i = 0;
5486 while ($i < $num) {
5487 $obj = $this->db->fetch_object($resql);
5488
5489 if (!$list) {
5490 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5491 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5492 $tab[$i] = array(
5493 'source' => $obj->source,
5494 'socid' => $obj->socid,
5495 'id' => $obj->id,
5496 'nom' => $obj->lastname, // For backward compatibility
5497 'civility' => $obj->civility,
5498 'lastname' => $obj->lastname,
5499 'firstname' => $obj->firstname,
5500 'email' => $obj->email,
5501 'login' => (empty($obj->login) ? '' : $obj->login),
5502 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5503 'statuscontact' => $obj->statuscontact,
5504 'rowid' => $obj->rowid,
5505 'code' => $obj->code,
5506 'element' => $obj->element,
5507 'libelle' => $libelle_type,
5508 'status' => $obj->statuslink,
5509 'fk_c_type_contact' => $obj->fk_c_type_contact
5510 );
5511 } else {
5512 $tab[$i] = $obj->id;
5513 }
5514
5515 $i++;
5516 }
5517
5518 return $tab;
5519 } else {
5520 $this->error = $this->db->lasterror();
5521 dol_print_error($this->db);
5522 return -1;
5523 }
5524 }
5525
5536 public function mergeCompany($soc_origin_id)
5537 {
5538 global $conf, $langs, $hookmanager, $user, $action;
5539
5540 $error = 0;
5541 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5542
5543 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5544
5545 if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5546 $this->error = $langs->trans('ErrorRecordNotFound');
5547 $error++;
5548 }
5549
5550 if (!$error) {
5551 $this->db->begin();
5552
5553 // Recopy some data
5554 $this->client |= $soc_origin->client;
5555 $this->fournisseur |= $soc_origin->fournisseur;
5556 $listofproperties = array(
5557 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5558 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5559 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5560 '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',
5561 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5562 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5563 );
5564 foreach ($listofproperties as $property) {
5565 if (empty($this->$property)) {
5566 $this->$property = $soc_origin->$property;
5567 }
5568 }
5569
5570 if ($this->typent_id == -1) {
5571 $this->typent_id = $soc_origin->typent_id;
5572 }
5573
5574 // Concat some data
5575 $listofproperties = array(
5576 'note_public', 'note_private'
5577 );
5578 foreach ($listofproperties as $property) {
5579 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5580 }
5581
5582 // Merge extrafields
5583 if (is_array($soc_origin->array_options)) {
5584 foreach ($soc_origin->array_options as $key => $val) {
5585 if (empty($this->array_options[$key])) {
5586 $this->array_options[$key] = $val;
5587 }
5588 }
5589 }
5590
5591 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5592 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5593 $this->name_bis = $this->name;
5594 }
5595
5596 // Merge categories
5597 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5598 $static_cat = new Categorie($this->db);
5599
5600 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5601 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5602 $custcats = array_merge($custcats, $custcats_ori);
5603 $this->setCategories($custcats, 'customer');
5604
5605 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5606 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5607 $suppcats = array_merge($suppcats, $suppcats_ori);
5608 $this->setCategories($suppcats, 'supplier');
5609
5610 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5611 if ($soc_origin->code_client == $this->code_client
5612 || $soc_origin->code_fournisseur == $this->code_fournisseur
5613 || $soc_origin->barcode == $this->barcode) {
5614 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5615 $soc_origin->code_client = '';
5616 $soc_origin->code_fournisseur = '';
5617 $soc_origin->barcode = '';
5618 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5619 }
5620
5621 // Update
5622 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5623
5624 if ($result < 0) {
5625 $error++;
5626 }
5627
5628 // Move links
5629 if (!$error) {
5630 $objects = array(
5631 'Adherent' => '/adherents/class/adherent.class.php',
5632 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5633 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5634 'Propal' => '/comm/propal/class/propal.class.php',
5635 'Commande' => '/commande/class/commande.class.php',
5636 'Facture' => '/compta/facture/class/facture.class.php',
5637 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5638 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5639 'Contact' => '/contact/class/contact.class.php',
5640 'Contrat' => '/contrat/class/contrat.class.php',
5641 'Expedition' => '/expedition/class/expedition.class.php',
5642 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5643 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5644 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5645 'Reception' => '/reception/class/reception.class.php',
5646 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5647 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5648 'Product' => '/product/class/product.class.php',
5649 //'ProductThirparty' => '...', // for llx_product_thirdparty
5650 'Project' => '/projet/class/project.class.php',
5651 'User' => '/user/class/user.class.php',
5652 'Account' => '/compta/bank/class/account.class.php',
5653 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5654 'Societe' => '/societe/class/societe.class.php',
5655 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirdparty of Societe.
5656 );
5657 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5658 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5659 }
5660 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5661 $objects['Mo'] = '/mrp/class/mo.class.php';
5662 }
5663 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5664 $objects['Don'] = '/don/class/don.class.php';
5665 }
5666 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5667 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5668 }
5669 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5670 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5671 }
5672 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5673 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5674 }
5675
5676 //First, all core objects must update their tables
5677 foreach ($objects as $object_name => $object_file) {
5678 /* $object_file is never an array -> code commented
5679 if (is_array($object_file)) {
5680 if (empty($object_file['enabled'])) {
5681 continue;
5682 }
5683 $object_file = $object_file['file'];
5684 }
5685 */
5686
5687 require_once DOL_DOCUMENT_ROOT.$object_file;
5688
5689 if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5690 $error++;
5691 $this->error = $this->db->lasterror();
5692 break;
5693 }
5694 }
5695 }
5696
5697 // External modules should update their ones too
5698 if (!$error) {
5699 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5700 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5701
5702 if ($reshook < 0) {
5703 $this->error = $hookmanager->error;
5704 $this->errors = $hookmanager->errors;
5705 $error++;
5706 }
5707 }
5708
5709
5710 if (!$error) {
5711 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5712
5713 // Call trigger
5714 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5715 if ($result < 0) {
5716 $error++;
5717 }
5718 // End call triggers
5719 }
5720
5721 if (!$error) {
5722 // We finally remove the old thirdparty
5723 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5724 $this->error = $soc_origin->error;
5725 $this->errors = $soc_origin->errors;
5726 $error++;
5727 }
5728 }
5729
5730
5731 if (!$error) {
5732 // Move files from the dir of the third party to delete into the dir of the third party to keep
5733 if (!empty($conf->societe->multidir_output[$this->entity])) {
5734 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5735 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5736
5737 if (dol_is_dir($srcdir)) {
5738 $dirlist = dol_dir_list($srcdir, 'files', 1);
5739 foreach ($dirlist as $filetomove) {
5740 $destfile = $destdir.'/'.$filetomove['relativename'];
5741 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5742 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5743 }
5744 //exit;
5745 }
5746 }
5747 }
5748
5749 if (!$error) {
5750 $this->db->commit();
5751 return 0;
5752 } else {
5753 $langs->load("errors");
5754 $this->error = $langs->trans('ErrorsThirdpartyMerge');
5755 $this->db->rollback();
5756 return -1;
5757 }
5758 }
5759
5760 return -1;
5761 }
5762}
$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 $mysoc in most ca...
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.
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:660
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=0)
Move a file into another name.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
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:153