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