dolibarr 20.0.5
societe.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5 * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2013-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
12 * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
16 * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
17 * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
18 * Copyright (C) 2019-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 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{
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
139 public $oldcopy;
140
145 public $SupplierCategories = array();
146
151 public $prefixCustomerIsRequired;
152
182 public $fields = array(
183 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'noteditable' => 1, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id', 'css' => 'left'),
184 'parent' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => -1, 'position' => 20),
185 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
186 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 30),
187 'nom' => array('type' => 'varchar(128)', 'label' => 'Nom', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox' => 1),
188 'name_alias' => array('type' => 'varchar(128)', 'label' => 'Name alias', 'enabled' => 1, 'visible' => -1, 'position' => 36, 'showoncombobox' => 2),
189 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 40, 'index' => 1),
190 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 45),
191 'code_client' => array('type' => 'varchar(24)', 'label' => 'CustomerCode', 'enabled' => 1, 'visible' => -1, 'position' => 55),
192 'code_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierCode', 'enabled' => 1, 'visible' => -1, 'position' => 60),
193 'code_compta' => array('type' => 'varchar(24)', 'label' => 'CustomerAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 65),
194 'code_compta_fournisseur' => array('type' => 'varchar(24)', 'label' => 'SupplierAccountancyCode', 'enabled' => 1, 'visible' => -1, 'position' => 70),
195 'address' => array('type' => 'varchar(255)', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
196 'zip' => array('type' => 'varchar(25)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
197 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
198 'fk_departement' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
199 'fk_pays' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95),
200 'phone' => array('type' => 'varchar(20)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 100),
201 'phone_mobile' => array('type' => 'varchar(20)', 'label' => 'PhoneMobile', 'enabled' => 1, 'visible' => -1, 'position' => 102),
202 'fax' => array('type' => 'varchar(20)', 'label' => 'Fax', 'enabled' => 1, 'visible' => -1, 'position' => 105),
203 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 110),
204 'email' => array('type' => 'varchar(128)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 115),
205 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 120),
206 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170),
207 'fk_typent' => array('type' => 'integer', 'label' => 'TypeOfCompany', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'),
208 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180),
209 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
210 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190),
211 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195),
212 'ape' => array('type' => 'varchar(128)', 'label' => 'Idprof3', 'enabled' => 1, 'visible' => -1, 'position' => 200),
213 'idprof4' => array('type' => 'varchar(128)', 'label' => 'Idprof4', 'enabled' => 1, 'visible' => -1, 'position' => 205),
214 'idprof5' => array('type' => 'varchar(128)', 'label' => 'Idprof5', 'enabled' => 1, 'visible' => -1, 'position' => 206),
215 'idprof6' => array('type' => 'varchar(128)', 'label' => 'Idprof6', 'enabled' => 1, 'visible' => -1, 'position' => 207),
216 'tva_intra' => array('type' => 'varchar(20)', 'label' => 'Tva intra', 'enabled' => 1, 'visible' => -1, 'position' => 210),
217 'capital' => array('type' => 'double(24,8)', 'label' => 'Capital', 'enabled' => 1, 'visible' => -1, 'position' => 215),
218 'fk_stcomm' => array('type' => 'integer', 'label' => 'CommercialStatus', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 220),
219 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 225),
220 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 230),
221 'prefix_comm' => array('type' => 'varchar(5)', 'label' => 'Prefix comm', 'enabled' => "getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible' => -1, 'position' => 235),
222 'client' => array('type' => 'tinyint(4)', 'label' => 'Client', 'enabled' => 1, 'visible' => -1, 'position' => 240),
223 'fournisseur' => array('type' => 'tinyint(4)', 'label' => 'Fournisseur', 'enabled' => 1, 'visible' => -1, 'position' => 245),
224 'supplier_account' => array('type' => 'varchar(32)', 'label' => 'Supplier account', 'enabled' => 1, 'visible' => -1, 'position' => 250),
225 'fk_prospectlevel' => array('type' => 'varchar(12)', 'label' => 'ProspectLevel', 'enabled' => 1, 'visible' => -1, 'position' => 255),
226 'customer_bad' => array('type' => 'tinyint(4)', 'label' => 'Customer bad', 'enabled' => 1, 'visible' => -1, 'position' => 260),
227 'customer_rate' => array('type' => 'double', 'label' => 'Customer rate', 'enabled' => 1, 'visible' => -1, 'position' => 265),
228 'supplier_rate' => array('type' => 'double', 'label' => 'Supplier rate', 'enabled' => 1, 'visible' => -1, 'position' => 270),
229 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 275),
230 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 280),
231 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
232 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
233 'mode_reglement' => array('type' => 'tinyint(4)', 'label' => 'Mode reglement', 'enabled' => 1, 'visible' => -1, 'position' => 295),
234 'cond_reglement' => array('type' => 'tinyint(4)', 'label' => 'Cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 300),
235 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 301),
236 'mode_reglement_supplier' => array('type' => 'integer', 'label' => 'Mode reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 305),
237 'cond_reglement_supplier' => array('type' => 'integer', 'label' => 'Cond reglement supplier', 'enabled' => 1, 'visible' => -1, 'position' => 308),
238 'outstanding_limit' => array('type' => 'double(24,8)', 'label' => 'OutstandingBill', 'enabled' => 1, 'visible' => -1, 'position' => 310, 'isameasure' => 1),
239 '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),
240 '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),
241 'fk_shipping_method' => array('type' => 'integer', 'label' => 'Fk shipping method', 'enabled' => 1, 'visible' => -1, 'position' => 330),
242 'tva_assuj' => array('type' => 'tinyint(4)', 'label' => 'Tva assuj', 'enabled' => 1, 'visible' => -1, 'position' => 335),
243 'localtax1_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax1 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 340),
244 'localtax1_value' => array('type' => 'double(6,3)', 'label' => 'Localtax1 value', 'enabled' => 1, 'visible' => -1, 'position' => 345),
245 'localtax2_assuj' => array('type' => 'tinyint(4)', 'label' => 'Localtax2 assuj', 'enabled' => 1, 'visible' => -1, 'position' => 350),
246 'localtax2_value' => array('type' => 'double(6,3)', 'label' => 'Localtax2 value', 'enabled' => 1, 'visible' => -1, 'position' => 355),
247 'vat_reverse_charge' => array('type' => 'tinyint(4)', 'label' => 'Vat reverse charge', 'enabled' => 1, 'visible' => -1, 'position' => 335),
248 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 1, 'visible' => -1, 'position' => 360),
249 'price_level' => array('type' => 'integer', 'label' => 'Price level', 'enabled' => '$conf->global->PRODUIT_MULTIPRICES || getDolGlobalString("PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES")', 'visible' => -1, 'position' => 365),
250 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 370),
251 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 375),
252 'fk_barcode_type' => array('type' => 'integer', 'label' => 'Fk barcode type', 'enabled' => 1, 'visible' => -1, 'position' => 405),
253 'webservices_url' => array('type' => 'varchar(255)', 'label' => 'Webservices url', 'enabled' => 1, 'visible' => -1, 'position' => 410),
254 'webservices_key' => array('type' => 'varchar(128)', 'label' => 'Webservices key', 'enabled' => 1, 'visible' => -1, 'position' => 415),
255 'fk_incoterms' => array('type' => 'integer', 'label' => 'Fk incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 425),
256 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'Location incoterms', 'enabled' => 1, 'visible' => -1, 'position' => 430),
257 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 435),
258 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
259 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 440),
260 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 445),
261 'fk_account' => array('type' => 'integer', 'label' => 'PaymentBankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 450),
262 'fk_warehouse' => array('type' => 'integer', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'position' => 455),
263 'logo' => array('type' => 'varchar(255)', 'label' => 'Logo', 'enabled' => 1, 'visible' => -1, 'position' => 400),
264 'logo_squarred' => array('type' => 'varchar(255)', 'label' => 'Logo squarred', 'enabled' => 1, 'visible' => -1, 'position' => 401),
265 'status' => array('type' => 'tinyint(4)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
266 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000),
267 );
268
272 public $entity;
273
280 public $nom;
281
285 public $name;
286
291 public $name_alias;
292
296 public $particulier;
297
302 public $status = 1;
303
307 public $region_code;
308
312 public $region;
313
317 public $country_id;
318
324 public $departement_code;
325
331 public $departement;
332
338 public $pays;
339
344 public $phone;
349 public $phone_mobile;
354 public $fax;
355
360 public $email;
361
366 public $no_email;
367
373 public $skype;
374
380 public $twitter;
381
387 public $facebook;
388
394 public $linkedin;
395
400 public $url;
401
406 public $barcode;
407
408 // 6 professional id (usage depends on country)
409
414 public $idprof1;
415
421 public $siren;
422
423
428 public $idprof2;
429
435 public $siret;
436
441 public $idprof3;
442
448 public $ape;
449
454 public $idprof4;
455
460 public $idprof5;
461
466 public $idprof6;
467
472 public $idprof7;
473
478 public $idprof8;
479
484 public $idprof9;
485
490 public $idprof10;
491
496 public $socialobject;
497
501 public $prefix_comm;
502
506 public $tva_assuj = 1;
507
511 public $tva_intra;
512
516 public $vat_reverse_charge = 0;
517
518 // Local taxes
519 public $localtax1_assuj;
520 public $localtax1_value;
521 public $localtax2_assuj;
522 public $localtax2_value;
523
527 public $managers;
528
532 public $capital;
533
537 public $typent_id = 0;
538 public $typent_code;
539 public $effectif;
540 public $effectif_id = 0;
541 public $forme_juridique_code;
542 public $forme_juridique = 0;
543
544 public $remise_percent;
545 public $remise_supplier_percent;
546
547 public $mode_reglement_id;
548 public $cond_reglement_id;
549 public $deposit_percent;
550 public $mode_reglement_supplier_id;
551 public $cond_reglement_supplier_id;
552 public $transport_mode_supplier_id;
553
557 public $fk_prospectlevel;
558
562 public $name_bis;
563
564 //Log data
565
570 public $date_modification;
571
577 public $user_modification;
578
583 public $date_creation;
584
590 public $user_creation;
591
596 public $client = 0;
597
602 public $prospect = 0;
603
608 public $fournisseur;
609
614 public $code_client;
615
620 public $code_fournisseur;
621
626 public $code_compta_client;
627
634 public $code_compta;
635
640 public $accountancy_code_customer;
641
646 public $code_compta_fournisseur;
647
652 public $accountancy_code_supplier;
653
658 public $code_compta_product;
659
665 public $note;
666
671 public $note_private;
672
677 public $note_public;
678
683 public $stcomm_id;
684
689 public $stcomm_picto;
690
695 public $status_prospect_label;
696
701 public $price_level;
702
706 public $outstanding_limit;
707
711 public $order_min_amount;
712
716 public $supplier_order_min_amount;
717
722 public $commercial_id;
723
728 public $parent;
729
734 public $default_lang;
735
739 public $ref;
740
746 public $ref_ext;
747
754 public $import_key;
755
760 public $webservices_url;
761
766 public $webservices_key;
767
771 public $logo;
772
776 public $logo_small;
777
781 public $logo_mini;
782
786 public $logo_squarred;
787
791 public $logo_squarred_small;
792
796 public $logo_squarred_mini;
797
801 public $accountancy_code_sell;
802
806 public $accountancy_code_buy;
807
808 // Multicurrency
812 public $fk_multicurrency;
813
814 // Warehouse
818 public $fk_warehouse;
819
823 public $multicurrency_code;
824
825 // Fields loaded by fetchPartnerships()
826
827 public $partnerships = array();
828
829
833 public $bank_account;
834
835
836 const STATUS_CEASED = 0;
837 const STATUS_INACTIVITY = 1;
838
842 const NO_CUSTOMER = 0;
843
847 const CUSTOMER = 1;
848
852 const PROSPECT = 2;
853
858
862 const NO_SUPPLIER = 0;
863
867 const SUPPLIER = 1;
868
869
875 public function __construct($db)
876 {
877 global $conf;
878
879 $this->db = $db;
880
881 $this->ismultientitymanaged = 1;
882 $this->isextrafieldmanaged = 1;
883 $this->client = 0;
884 $this->prospect = 0;
885 $this->fournisseur = 0;
886 $this->typent_id = 0;
887 $this->effectif_id = 0;
888 $this->forme_juridique_code = 0;
889 $this->tva_assuj = 1;
890 $this->vat_reverse_charge = 0;
891 $this->status = 1;
892
893 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
894 $this->fields['address']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
895 $this->fields['zip']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
896 $this->fields['town']['showoncombobox'] = getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST');
897 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
898 }
899 }
900
901
910 public function create(User $user, $notrigger = 0)
911 {
912 global $langs, $conf;
913
914 $error = 0;
915
916 // Clean parameters
917 if (empty($this->status)) {
918 $this->status = 0;
919 }
920 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
921 $this->setUpperOrLowerCase();
922 $this->nom = $this->name; // For backward compatibility
923
924 if (empty($this->client)) {
925 $this->client = 0;
926 }
927 if (empty($this->fournisseur)) {
928 $this->fournisseur = 0;
929 }
930 $this->import_key = trim((string) $this->import_key);
931
932 $this->accountancy_code_customer = trim((string) $this->code_compta);
933 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
934 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
935 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
936
937 if (!empty($this->multicurrency_code)) {
938 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
939 }
940 if (empty($this->fk_multicurrency)) {
941 $this->multicurrency_code = '';
942 $this->fk_multicurrency = 0;
943 }
944
945 dol_syslog(get_class($this)."::create ".$this->name);
946
947 $now = dol_now();
948
949 if (empty($this->date_creation)) {
950 $this->date_creation = $now;
951 }
952
953 $this->db->begin();
954
955 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
956 if ($this->code_client == -1 || $this->code_client === 'auto') {
957 $this->get_codeclient($this, 0);
958 }
959 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
960 $this->get_codefournisseur($this, 1);
961 }
962
963 // Check more parameters (including mandatory setup
964 // If error, this->errors[] is filled
965 $result = $this->verify();
966
967 if ($result >= 0) {
968 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
969
970 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
971 $sql .= "nom";
972 $sql .= ", name_alias";
973 $sql .= ", entity";
974 $sql .= ", datec";
975 $sql .= ", fk_user_creat";
976 $sql .= ", fk_typent";
977 $sql .= ", canvas";
978 $sql .= ", status";
979 $sql .= ", ref_ext";
980 $sql .= ", fk_stcomm";
981 $sql .= ", fk_incoterms";
982 $sql .= ", location_incoterms";
983 $sql .= ", import_key";
984 $sql .= ", fk_multicurrency";
985 $sql .= ", multicurrency_code";
986 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
987 $sql .= ", vat_reverse_charge";
988 $sql .= ", accountancy_code_buy";
989 $sql .= ", accountancy_code_sell";
990 }
991 $sql .= ") VALUES ('".$this->db->escape($this->name)."',";
992 $sql .= " '".$this->db->escape($this->name_alias)."',";
993 $sql .= " ".((int) $this->entity).",";
994 $sql .= " '".$this->db->idate($this->date_creation)."'";
995 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
996 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
997 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
998 $sql .= ", ".((int) $this->status);
999 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1000 $sql .= ", 0";
1001 $sql .= ", ".(int) $this->fk_incoterms;
1002 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1003 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1004 $sql .= ", ".(int) $this->fk_multicurrency;
1005 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1006 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1007 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1008 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1009 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1010 }
1011 $sql .= ")";
1012
1013 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1014
1015 $result = $this->db->query($sql);
1016 if ($result) {
1017 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
1018
1019 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
1020
1021 // update accountancy for this entity
1022 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1023 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1024
1025 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1026 $sql .= " fk_soc";
1027 $sql .= ", entity";
1028 $sql .= ", vat_reverse_charge";
1029 $sql .= ", accountancy_code_customer";
1030 $sql .= ", accountancy_code_supplier";
1031 $sql .= ", accountancy_code_buy";
1032 $sql .= ", accountancy_code_sell";
1033 $sql .= ") VALUES (";
1034 $sql .= $this->id;
1035 $sql .= ", ".((int) $conf->entity);
1036 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1037 $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1038 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1039 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1040 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1041 $sql .= ")";
1042 $result = $this->db->query($sql);
1043 if (!$result) {
1044 $error++;
1045 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1046 }
1047 }
1048
1049 // Ajout du commercial affecte
1050 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1051 $this->add_commercial($user, $this->commercial_id);
1052 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1053 // si un commercial cree un client il lui est affecte automatiquement
1054 $this->add_commercial($user, $user->id);
1055 }
1056
1057 if ($ret >= 0) {
1058 if (! $notrigger) {
1059 // Call trigger
1060 $result = $this->call_trigger('COMPANY_CREATE', $user);
1061 if ($result < 0) {
1062 $error++;
1063 }
1064 // End call triggers
1065 }
1066 } else {
1067 $error++;
1068 }
1069
1070 if (!$error) {
1071 dol_syslog(get_class($this)."::Create success id=".$this->id);
1072 $this->db->commit();
1073 return $this->id;
1074 } else {
1075 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.implode(',', $this->errors)), LOG_ERR);
1076 $this->db->rollback();
1077 return -4;
1078 }
1079 } else {
1080 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1081 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1082 $result = -1;
1083 } else {
1084 $this->error = $this->db->lasterror();
1085 $result = -2;
1086 }
1087 $this->db->rollback();
1088 return $result;
1089 }
1090 } else {
1091 $this->db->rollback();
1092 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1093 return -3;
1094 }
1095 }
1096
1097
1098 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1108 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1109 {
1110 global $conf;
1111
1112 $error = 0;
1113
1114 $this->db->begin();
1115
1116 // phpcs:enable
1117 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1118 $contact = new Contact($this->db);
1119
1120 $contact->name = $this->name_bis;
1121 $contact->firstname = $this->firstname;
1122 $contact->civility_id = $this->civility_id;
1123 $contact->socid = $this->id; // fk_soc
1124 $contact->statut = 1; // deprecated
1125 $contact->status = 1;
1126 $contact->priv = 0;
1127 $contact->country_id = $this->country_id;
1128 $contact->state_id = $this->state_id;
1129 $contact->address = $this->address;
1130 $contact->email = $this->email;
1131 $contact->zip = $this->zip;
1132 $contact->town = $this->town;
1133 $this->setUpperOrLowerCase();
1134 $contact->phone_pro = $this->phone;
1135
1136 $contactId = $contact->create($user, $notrigger);
1137 if ($contactId < 0) {
1138 $error++;
1139 $this->error = $contact->error;
1140 $this->errors = $contact->errors;
1141 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1142 }
1143
1144 if (empty($error) && is_array($tags) && !empty($tags)) {
1145 $result = $contact->setCategories($tags);
1146 if ($result < 0) {
1147 $error++;
1148 $this->error = $contact->error;
1149 $this->errors = array_merge($this->errors, $contact->errors);
1150 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1151 $contactId = $result;
1152 }
1153 }
1154
1155 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1156 $result = $contact->setNoEmail($no_email);
1157 if ($result < 0) {
1158 $this->error = $contact->error;
1159 $this->errors = array_merge($this->errors, $contact->errors);
1160 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1161 $contactId = $result;
1162 }
1163 }
1164
1165 if (empty($error)) {
1166 dol_syslog(get_class($this)."::create_individual success");
1167 $this->db->commit();
1168 } else {
1169 $this->db->rollback();
1170 }
1171
1172 return $contactId;
1173 }
1174
1181 public function verify()
1182 {
1183 global $conf, $langs, $mysoc;
1184
1185 $error = 0;
1186 $this->errors = array();
1187
1188 $result = 0;
1189 $this->name = trim($this->name);
1190 $this->nom = $this->name; // For backward compatibility
1191
1192 if (!$this->name) {
1193 $this->errors[] = 'ErrorBadThirdPartyName';
1194 $result = -2;
1195 }
1196
1197 if ($this->client) {
1198 $rescode = $this->check_codeclient();
1199 if ($rescode != 0 && $rescode != -5) {
1200 if ($rescode == -1) {
1201 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1202 } elseif ($rescode == -2) {
1203 $this->errors[] = 'ErrorCustomerCodeRequired';
1204 } elseif ($rescode == -3) {
1205 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1206 } elseif ($rescode == -4) {
1207 $this->errors[] = 'ErrorPrefixRequired';
1208 } else {
1209 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1210 }
1211
1212 $result = -3;
1213 }
1214 }
1215
1216 if ($this->fournisseur) {
1217 $rescode = $this->check_codefournisseur();
1218 if ($rescode != 0 && $rescode != -5) {
1219 if ($rescode == -1) {
1220 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1221 } elseif ($rescode == -2) {
1222 $this->errors[] = 'ErrorSupplierCodeRequired';
1223 } elseif ($rescode == -3) {
1224 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1225 } elseif ($rescode == -4) {
1226 $this->errors[] = 'ErrorPrefixRequired';
1227 } else {
1228 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1229 }
1230 $result = -3;
1231 }
1232 }
1233
1234 // Check for duplicate or mandatory fields defined into setup
1235 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1236 foreach ($array_to_check as $key) {
1237 $keymin = strtolower($key);
1238 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1239 $keymin = 'code_compta';
1240 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1241 $keymin = 'code_compta_fournisseur';
1242 }
1243 $i = (int) preg_replace('/[^0-9]/', '', $key);
1244 $vallabel = $this->$keymin;
1245
1246 if ($i > 0) {
1247 if ($this->isACompany()) {
1248 // Check for mandatory prof id (but only if country is same than ours)
1249 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1250 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1251 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1252 $langs->load("errors");
1253 $error++;
1254 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1255 }
1256 }
1257 }
1258
1259 // Check for unicity on profid
1260 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1261 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1262 $langs->load("errors");
1263 $error++;
1264 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1265 }
1266 }
1267 } else {
1268 //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1269 //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1270 if ($key == 'EMAIL') {
1271 // Check for mandatory
1272 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEmail($this->email)) {
1273 $langs->load("errors");
1274 $error++;
1275 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1276 }
1277
1278 // Check for unicity
1279 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1280 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1281 $langs->load("errors");
1282 $error++;
1283 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1284 }
1285 }
1286 } elseif ($key == 'TVA_INTRA') {
1287 // Check for unicity
1288 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1289 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1290 $langs->load("errors");
1291 $error++;
1292 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1293 }
1294 }
1295 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1296 // Check for unicity
1297 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1298 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1299 $langs->loadLangs(array("errors", 'compta'));
1300 $error++;
1301 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1302 }
1303 }
1304
1305 // Check for mandatory
1306 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1307 $langs->loadLangs(array("errors", 'compta'));
1308 $error++;
1309 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1310 }
1311 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1312 // Check for unicity
1313 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1314 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1315 $langs->loadLangs(array("errors", 'compta'));
1316 $error++;
1317 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1318 }
1319 }
1320
1321 // Check for mandatory
1322 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1323 $langs->loadLangs(array("errors", 'compta'));
1324 $error++;
1325 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1326 }
1327 }
1328 }
1329 }
1330
1331 if ($error) {
1332 $result = -4;
1333 }
1334
1335 return $result;
1336 }
1337
1350 public function update($id, User $user, $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1351 {
1352 global $langs, $conf, $hookmanager;
1353
1354 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1355
1356 if (empty($id)) {
1357 $id = $this->id;
1358 }
1359 if (empty($this->country_id) && !empty($this->country_code)) {
1360 $this->country_id = dol_getIdFromCode($this->db, $this->country_code, 'c_country', 'code', 'rowid');
1361 }
1362
1363 $error = 0;
1364
1365 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1366
1367 $now = dol_now();
1368
1369 // Clean parameters
1370 $this->id = $id;
1371 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1372 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1373 $this->nom = $this->name; // For backward compatibility
1374 $this->name_alias = trim((string) $this->name_alias);
1375 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1376 $this->address = trim((string) $this->address);
1377 $this->zip = trim((string) $this->zip);
1378 $this->town = trim((string) $this->town);
1379 $this->state_id = (is_numeric($this->state_id)) ? (int) $this->state_id : 0;
1380 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1381 $this->phone = trim((string) $this->phone);
1382 $this->phone = preg_replace("/\s/", "", $this->phone);
1383 $this->phone = preg_replace("/\./", "", $this->phone);
1384 $this->phone_mobile = trim((string) $this->phone_mobile);
1385 $this->phone_mobile = preg_replace("/\s/", "", $this->phone_mobile);
1386 $this->phone_mobile = preg_replace("/\./", "", $this->phone_mobile);
1387 $this->fax = trim((string) $this->fax);
1388 $this->fax = preg_replace("/\s/", "", $this->fax);
1389 $this->fax = preg_replace("/\./", "", $this->fax);
1390 $this->email = trim((string) $this->email);
1391 $this->url = $this->url ? clean_url($this->url, 0) : '';
1392 $this->note_private = (empty($this->note_private) ? '' : trim($this->note_private));
1393 $this->note_public = (empty($this->note_public) ? '' : trim($this->note_public));
1394 $this->idprof1 = trim((string) $this->idprof1);
1395 $this->idprof2 = trim((string) $this->idprof2);
1396 $this->idprof3 = trim((string) $this->idprof3);
1397 $this->idprof4 = trim((string) $this->idprof4);
1398 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1399 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1400 $this->prefix_comm = trim((string) $this->prefix_comm);
1401 $this->outstanding_limit = price2num($this->outstanding_limit);
1402 $this->order_min_amount = price2num($this->order_min_amount);
1403 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1404
1405 $this->tva_assuj = (is_numeric($this->tva_assuj)) ? (int) trim((string) $this->tva_assuj) : 0;
1406 $this->tva_intra = trim($this->tva_intra);
1407 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? 0 : 1;
1408 if (empty($this->status)) {
1409 $this->status = 0;
1410 }
1411
1412 if (!empty($this->multicurrency_code)) {
1413 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1414 }
1415 if (empty($this->fk_multicurrency)) {
1416 $this->multicurrency_code = '';
1417 $this->fk_multicurrency = 0;
1418 }
1419
1420 // Local taxes
1421 $this->localtax1_assuj = trim($this->localtax1_assuj);
1422 $this->localtax2_assuj = trim($this->localtax2_assuj);
1423
1424 $this->localtax1_value = trim($this->localtax1_value);
1425 $this->localtax2_value = trim($this->localtax2_value);
1426
1427 $this->capital = ($this->capital != '') ? (float) price2num(trim((string) $this->capital)) : null;
1428
1429 $this->effectif_id = trim((string) $this->effectif_id);
1430 $this->forme_juridique_code = trim((string) $this->forme_juridique_code);
1431
1432 //Gencod
1433 $this->barcode = trim($this->barcode);
1434
1435 // For automatic creation
1436 if ($this->code_client == -1 || $this->code_client === 'auto') {
1437 $this->get_codeclient($this, 0);
1438 }
1439 if ($this->code_fournisseur == '-1' || $this->code_fournisseur === 'auto') {
1440 $this->get_codefournisseur($this, 1);
1441 }
1442
1443 $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1444 $this->code_compta = $this->code_compta_client; // for backward compatibility
1445 $this->code_compta_fournisseur = (empty($this->code_compta_fournisseur) ? '' : trim($this->code_compta_fournisseur));
1446
1447 // Check parameters. More tests are done later in the ->verify()
1448 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1449 $langs->load("errors");
1450 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1451 return -1;
1452 }
1453
1454 $customer = false;
1455 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1456 // If $allowmodcodeclient is set and value is not set, we generate it
1457 if (empty($this->code_compta_client)) {
1458 $ret = $this->get_codecompta('customer');
1459 if ($ret < 0) {
1460 return -1;
1461 }
1462 }
1463
1464 $customer = true;
1465 }
1466
1467 $supplier = false;
1468 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1469 // If $allowmodcodefournisseur is set and value is not set, we generate it
1470 if (empty($this->code_compta_fournisseur)) {
1471 $ret = $this->get_codecompta('supplier');
1472 if ($ret < 0) {
1473 return -1;
1474 }
1475 }
1476
1477 $supplier = true;
1478 }
1479
1480 //Web services
1481 $this->webservices_url = $this->webservices_url ? clean_url($this->webservices_url, 0) : '';
1482 $this->webservices_key = trim($this->webservices_key);
1483
1484 $this->accountancy_code_buy = (empty($this->accountancy_code_buy) ? '' : trim($this->accountancy_code_buy));
1485 $this->accountancy_code_sell = (empty($this->accountancy_code_sell) ? '' : trim($this->accountancy_code_sell));
1486
1487 //Incoterms
1488 $this->fk_incoterms = (int) $this->fk_incoterms;
1489 $this->location_incoterms = trim($this->location_incoterms);
1490
1491 $this->db->begin();
1492
1493 // Check name is required and codes are ok or unique.
1494 // If error, this->errors[] is filled
1495 $result = 0;
1496 if ($action != 'add' && $action != 'merge') {
1497 // We don't check when update called during a create because verify was already done.
1498 // 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
1499 $result = $this->verify();
1500
1501 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1502 // So we can update record that were using and old numbering rule.
1503 if (is_array($this->errors)) {
1504 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1505 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1506 unset($this->errors[$key]); // Remove error message
1507 }
1508 }
1509 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1510 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1511 unset($this->errors[$key]); // Remove error message
1512 }
1513 }
1514 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1515 $result = 0;
1516 }
1517 }
1518 }
1519 $this->setUpperOrLowerCase();
1520 if ($result >= 0) {
1521 dol_syslog(get_class($this)."::update verify ok or not done");
1522
1523 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1524 $sql .= "entity = ".$this->db->escape($this->entity);
1525 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1526 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1527 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1528 $sql .= ",address = '".$this->db->escape($this->address)."'";
1529
1530 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1531 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1532
1533 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1534 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1535
1536 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1537 $sql .= ",phone_mobile = ".(!empty($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
1538 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1539 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1540 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1541 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1542
1543 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1544
1545 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1546 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1547
1548 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1549 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1550 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1551 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1552 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1553 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1554
1555 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1556 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1557 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1558 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1559 }
1560 $sql .= ",status = ".((int) $this->status);
1561
1562 // Local taxes
1563 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1564 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1565 if ($this->localtax1_assuj == 1) {
1566 if ($this->localtax1_value != '') {
1567 $sql .= ",localtax1_value =".$this->localtax1_value;
1568 } else {
1569 $sql .= ",localtax1_value =0.000";
1570 }
1571 } else {
1572 $sql .= ",localtax1_value =0.000";
1573 }
1574
1575 if ($this->localtax2_assuj == 1) {
1576 if ($this->localtax2_value != '') {
1577 $sql .= ",localtax2_value =".$this->localtax2_value;
1578 } else {
1579 $sql .= ",localtax2_value =0.000";
1580 }
1581 } else {
1582 $sql .= ",localtax2_value =0.000";
1583 }
1584
1585 $sql .= ",capital = ".($this->capital === null ? "null" : $this->capital);
1586
1587 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1588
1589 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1590 if (isset($this->stcomm_id)) {
1591 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1592 }
1593 if (isset($this->typent_id)) {
1594 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1595 }
1596
1597 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1598
1599 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1600 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1601 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1602 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1603 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1604 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1605 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1606 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1607
1608 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1609 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1610 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1611 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1612 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1613 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1614 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1615 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1616 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1617 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1618 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1619 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1620 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1621 if ($customer) {
1622 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1623 }
1624
1625 if ($supplier) {
1626 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1627 }
1628 }
1629 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1630 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1631
1632 //Incoterms
1633 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1634 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1635
1636 if ($customer) {
1637 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1638 }
1639
1640 if ($supplier) {
1641 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1642 }
1643 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1644 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1645 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1646 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1647 $sql .= " WHERE rowid = ".(int) $id;
1648
1649 $resql = $this->db->query($sql);
1650 if ($resql) {
1651 if (is_object($this->oldcopy)) { // If we have information on old values
1652 if ($this->oldcopy->country_id != $this->country_id) {
1653 unset($this->country_code);
1654 unset($this->country);
1655 }
1656 if ($this->oldcopy->state_id != $this->state_id) {
1657 unset($this->state_code);
1658 unset($this->state);
1659 }
1660 } else {
1661 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1662 unset($this->country);
1663 unset($this->state_code);
1664 unset($this->state);
1665 }
1666
1667 $nbrowsaffected = $this->db->affected_rows($resql);
1668
1669 if (!$error && $nbrowsaffected) {
1670 // Update information on linked member if it is an update
1671 if (!$nosyncmember && isModEnabled('member')) {
1672 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1673
1674 dol_syslog(get_class($this)."::update update linked member");
1675
1676 $lmember = new Adherent($this->db);
1677 $result = $lmember->fetch(0, 0, $this->id);
1678
1679 if ($result > 0) {
1680 $lmember->company = $this->name;
1681 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1682 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1683 $lmember->address = $this->address;
1684 $lmember->zip = $this->zip;
1685 $lmember->town = $this->town;
1686 $lmember->email = $this->email;
1687 $lmember->socialnetworks = $this->socialnetworks;
1688 $lmember->phone = $this->phone;
1689 $lmember->state_id = $this->state_id;
1690 $lmember->country_id = $this->country_id;
1691 $lmember->default_lang = $this->default_lang;
1692
1693 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1694 if ($result < 0) {
1695 $this->error = $lmember->error;
1696 $this->errors = array_merge($this->errors, $lmember->errors);
1697 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1698 $error++;
1699 }
1700 } elseif ($result < 0) {
1701 $this->error = $lmember->error;
1702 $error++;
1703 }
1704 }
1705 }
1706
1707 $action = 'update';
1708
1709 // update accountancy for this entity
1710 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1711 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1712
1713 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1714 $sql .= " fk_soc";
1715 $sql .= ", entity";
1716 $sql .= ", vat_reverse_charge";
1717 $sql .= ", accountancy_code_customer";
1718 $sql .= ", accountancy_code_supplier";
1719 $sql .= ", accountancy_code_buy";
1720 $sql .= ", accountancy_code_sell";
1721 $sql .= ") VALUES (";
1722 $sql .= $this->id;
1723 $sql .= ", ".$conf->entity;
1724 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1725 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1726 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1727 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1728 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1729 $sql .= ")";
1730 $result = $this->db->query($sql);
1731 if (!$result) {
1732 $error++;
1733 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1734 }
1735 }
1736
1737 // Actions on extra fields
1738 if (!$error) {
1739 $result = $this->insertExtraFields();
1740 if ($result < 0) {
1741 $error++;
1742 }
1743 }
1744 // Actions on extra languages
1745 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1746 $result = $this->insertExtraLanguages();
1747 if ($result < 0) {
1748 $error++;
1749 }
1750 }
1751
1752 if (!$error && $call_trigger) {
1753 // Call trigger
1754 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1755 if ($result < 0) {
1756 $error++;
1757 }
1758 // End call triggers
1759 }
1760
1761 if (!$error) {
1762 dol_syslog(get_class($this)."::Update success");
1763 $this->db->commit();
1764 return 1;
1765 } else {
1766 $this->db->rollback();
1767 return -1;
1768 }
1769 } else {
1770 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1771 // Doublon
1772 $this->error = $langs->trans("ErrorDuplicateField");
1773 $result = -1;
1774 } else {
1775 $this->error = $this->db->lasterror();
1776 $result = -2;
1777 }
1778 $this->db->rollback();
1779 return $result;
1780 }
1781 } else {
1782 $this->db->rollback();
1783 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1784 return -3;
1785 }
1786 }
1787
1807 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
1808 {
1809 global $langs;
1810 global $conf;
1811
1812 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)) {
1813 return -1;
1814 }
1815
1816 $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';
1817 $sql .= ', s.status, s.fk_warehouse';
1818 $sql .= ', s.price_level';
1819 $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1820 $sql .= ', s.phone, s.phone_mobile, s.fax, s.email';
1821 $sql .= ', s.socialnetworks';
1822 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1823 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1824 $sql .= ', s.capital, s.tva_intra';
1825 $sql .= ', s.fk_typent as typent_id';
1826 $sql .= ', s.fk_effectif as effectif_id';
1827 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1828 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1829 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1830 $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1831 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1832 } else {
1833 $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1834 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1835 }
1836 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1837 $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';
1838 $sql .= ', s.fk_account, s.tva_assuj';
1839 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1840 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1841 $sql .= ', s.fk_shipping_method';
1842 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1843 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1844 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1845 $sql .= ', fj.libelle as forme_juridique';
1846 $sql .= ', e.libelle as effectif';
1847 $sql .= ', c.code as country_code, c.label as country';
1848 $sql .= ', d.code_departement as state_code, d.nom as state';
1849 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1850 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1851 $sql .= ', te.code as typent_code';
1852 $sql .= ', i.libelle as label_incoterms';
1853 if (!isModEnabled('multicompany')) {
1854 $sql .= ', s.remise_client, s.remise_supplier';
1855 } else {
1856 $sql .= ', sr.remise_client, sr2.remise_supplier';
1857 }
1858 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1859 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1860 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1861 }
1862 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1863 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1864 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1865 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1866 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1867 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1868 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1869 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1870 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1871 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1872 if (isModEnabled('multicompany')) {
1873 $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').'))';
1874 $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').'))';
1875 }
1876 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1877
1878 // Filter on client or supplier, for Client::fetch() and Fournisseur::fetch()
1879 if ($is_client) {
1880 $sql .= ' AND s.client > 0';
1881 }
1882 if ($is_supplier) {
1883 $sql .= ' AND s.fournisseur > 0';
1884 } // if both false, no test (the thirdparty can be client and/or supplier)
1885
1886 if ($rowid) {
1887 $sql .= ' AND s.rowid = '.((int) $rowid);
1888 }
1889 if ($ref) {
1890 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1891 }
1892 if ($ref_alias) {
1893 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1894 }
1895 if ($ref_ext) {
1896 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1897 }
1898 if ($barcode) {
1899 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1900 }
1901 if ($idprof1) {
1902 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1903 }
1904 if ($idprof2) {
1905 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1906 }
1907 if ($idprof3) {
1908 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1909 }
1910 if ($idprof4) {
1911 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1912 }
1913 if ($idprof5) {
1914 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1915 }
1916 if ($idprof6) {
1917 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1918 }
1919 if ($email) {
1920 $sql .= " AND s.email = '".$this->db->escape($email)."'";
1921 }
1922
1923 $resql = $this->db->query($sql);
1924 if ($resql) {
1925 $num = $this->db->num_rows($resql);
1926 if ($num > 1) {
1927 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1928 dol_syslog($this->error, LOG_ERR);
1929 $result = -2;
1930 } elseif ($num) { // $num = 1
1931 $obj = $this->db->fetch_object($resql);
1932
1933 $this->id = $obj->rowid;
1934 $this->entity = $obj->entity;
1935 $this->canvas = $obj->canvas;
1936
1937 $this->ref = $obj->name;
1938 $this->name = $obj->name;
1939 $this->nom = $obj->name; // deprecated
1940 $this->name_alias = $obj->name_alias;
1941 $this->ref_ext = $obj->ref_ext;
1942
1943 $this->date_creation = $this->db->jdate($obj->date_creation);
1944 $this->date_modification = $this->db->jdate($obj->date_modification);
1945 $this->user_creation_id = $obj->fk_user_creat;
1946 $this->user_modification_id = $obj->fk_user_modif;
1947
1948 $this->address = $obj->address;
1949 $this->zip = $obj->zip;
1950 $this->town = $obj->town;
1951
1952 $this->country_id = $obj->country_id;
1953 $this->country_code = $obj->country_id ? $obj->country_code : '';
1954 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1955
1956 $this->state_id = $obj->state_id;
1957 $this->state_code = $obj->state_code;
1958 $this->region_id = $obj->region_id;
1959 $this->region_code = $obj->region_code;
1960 $this->state = ($obj->state != '-' ? $obj->state : '');
1961
1962 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1963 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1964 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1965 $this->status_prospect_label = $label; // label status prospect
1966 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1967
1968 $this->email = $obj->email;
1969 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1970
1971 $this->url = $obj->url;
1972 $this->phone = $obj->phone;
1973 $this->phone_mobile = $obj->phone_mobile;
1974 $this->fax = $obj->fax;
1975
1976 $this->parent = $obj->parent;
1977
1978 $this->idprof1 = $obj->idprof1;
1979 $this->idprof2 = $obj->idprof2;
1980 $this->idprof3 = $obj->idprof3;
1981 $this->idprof4 = $obj->idprof4;
1982 $this->idprof5 = $obj->idprof5;
1983 $this->idprof6 = $obj->idprof6;
1984
1985 $this->capital = $obj->capital;
1986
1987 $this->code_client = $obj->code_client;
1988 $this->code_fournisseur = $obj->code_fournisseur;
1989
1990 $this->code_compta = $obj->code_compta; // For backward compatibility
1991 $this->code_compta_client = $obj->code_compta;
1992 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1993
1994 $this->barcode = $obj->barcode;
1995
1996 $this->tva_assuj = $obj->tva_assuj;
1997 $this->tva_intra = $obj->tva_intra;
1998
1999 if (!empty($obj->spe_vat_reverse_charge)) {
2000 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
2001 } elseif (!empty($obj->soc_vat_reverse_charge)) {
2002 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
2003 } else {
2004 $this->vat_reverse_charge = 0;
2005 }
2006
2007 $this->status = $obj->status;
2008
2009 // Local Taxes
2010 $this->localtax1_assuj = $obj->localtax1_assuj;
2011 $this->localtax2_assuj = $obj->localtax2_assuj;
2012
2013 $this->localtax1_value = $obj->localtax1_value;
2014 $this->localtax2_value = $obj->localtax2_value;
2015
2016 $this->typent_id = $obj->typent_id;
2017 $this->typent_code = $obj->typent_code;
2018
2019 $this->effectif_id = $obj->effectif_id;
2020 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
2021
2022 $this->forme_juridique_code = $obj->forme_juridique_code;
2023 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
2024
2025 $this->fk_prospectlevel = $obj->fk_prospectlevel;
2026
2027 $this->prefix_comm = $obj->prefix_comm;
2028
2029 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
2030 $this->remise_supplier_percent = $obj->remise_supplier;
2031
2032 $this->mode_reglement_id = $obj->mode_reglement;
2033 $this->cond_reglement_id = $obj->cond_reglement;
2034 $this->deposit_percent = $obj->deposit_percent;
2035 $this->transport_mode_id = $obj->transport_mode;
2036 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
2037 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
2038 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
2039 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2040 $this->fk_account = $obj->fk_account;
2041
2042 $this->client = $obj->client;
2043 $this->fournisseur = $obj->fournisseur;
2044
2045 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2046 $this->note_private = $obj->note_private;
2047 $this->note_public = $obj->note_public;
2048 $this->model_pdf = $obj->model_pdf;
2049 $this->default_lang = $obj->default_lang;
2050 $this->logo = $obj->logo;
2051 $this->logo_squarred = $obj->logo_squarred;
2052
2053 $this->webservices_url = $obj->webservices_url;
2054 $this->webservices_key = $obj->webservices_key;
2055
2056 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2057 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2058
2059 $this->outstanding_limit = $obj->outstanding_limit;
2060 $this->order_min_amount = $obj->order_min_amount;
2061 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2062
2063 // multiprix
2064 $this->price_level = $obj->price_level;
2065
2066 // warehouse
2067 $this->fk_warehouse = $obj->fk_warehouse;
2068
2069 $this->import_key = $obj->import_key;
2070
2071 //Incoterms
2072 $this->fk_incoterms = $obj->fk_incoterms;
2073 $this->location_incoterms = $obj->location_incoterms;
2074 $this->label_incoterms = $obj->label_incoterms;
2075
2076 // multicurrency
2077 $this->fk_multicurrency = $obj->fk_multicurrency;
2078 $this->multicurrency_code = $obj->multicurrency_code;
2079
2080 // pdf
2081 $this->model_pdf = $obj->model_pdf;
2082 $this->last_main_doc = $obj->last_main_doc;
2083
2084 $result = $this->id;
2085
2086 // fetch optionals attributes and labels
2087 $this->fetch_optionals();
2088 } else {
2089 $result = 0;
2090 }
2091
2092 $this->db->free($resql);
2093 } else {
2094 $this->error = $this->db->lasterror();
2095 $this->errors[] = $this->db->lasterror();
2096 $result = -3;
2097 }
2098
2099 // Use first price level if level not defined for third party
2100 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && empty($this->price_level)) {
2101 $this->price_level = 1;
2102 }
2103
2104 return $result;
2105 }
2106
2127 public function findNearest($rowid = 0, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '', $is_client = 0, $is_supplier = 0)
2128 {
2129 // A rowid is known, it is a unique key so we found it
2130 if ($rowid) {
2131 return $rowid;
2132 }
2133
2134 // We try to find the thirdparty with exact matching on all fields
2135 // TODO Replace this with step by step search
2136 // Then search on barcode if we have it (+ restriction on is_client and is_supplier)
2137 // Then search on profids with a OR (+ restriction on is_client and is_supplier)
2138 // Then search on email (+ restriction on is_client and is_supplier)
2139 // Then search ref, ref_ext or alias with a OR (+ restriction on is_client and is_supplier)
2140 $tmpthirdparty = new Societe($this->db);
2141 $result = $tmpthirdparty->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias, $is_client, $is_supplier);
2142
2143 return $result;
2144 }
2145
2154 public function delete($id, User $fuser = null, $call_trigger = 1)
2155 {
2156 global $conf, $user;
2157
2158 if (empty($fuser)) {
2159 $fuser = $user;
2160 }
2161
2162 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2163
2164 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2165
2166 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2167 $error = 0;
2168
2169 // Test if child exists
2170 $objectisused = $this->isObjectUsed($id);
2171 if (empty($objectisused)) {
2172 $this->db->begin();
2173
2174 // User is mandatory for trigger call
2175 if (!$error && $call_trigger) {
2176 // Call trigger
2177 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2178 if ($result < 0) {
2179 $error++;
2180 }
2181 // End call triggers
2182 }
2183
2184 if (!$error) {
2185 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2186 $static_cat = new Categorie($this->db);
2187 $toute_categs = array();
2188
2189 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2190 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2191 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2192
2193 // Remove each "Categorie"
2194 foreach ($toute_categs as $type => $categs_type) {
2195 foreach ($categs_type as $cat) {
2196 $cat->del_type($this, $type);
2197 }
2198 }
2199 }
2200
2201 if (!$error) {
2202 foreach ($this->childtablesoncascade as $tabletodelete) {
2203 $deleteFromObject = explode(':', $tabletodelete, 4);
2204 if (count($deleteFromObject) >= 2) {
2205 $className = str_replace('@', '', $deleteFromObject[0]);
2206 $filepath = $deleteFromObject[1];
2207 $columnName = $deleteFromObject[2];
2208 if (dol_include_once($filepath)) {
2209 $child_object = new $className($this->db);
2210 $result = $child_object->deleteByParentField($id, $columnName);
2211 if ($result < 0) {
2212 $error++;
2213 $this->errors[] = $child_object->error;
2214 break;
2215 }
2216 } else {
2217 $error++;
2218 $this->errors[] = 'Cannot include child class file '.$filepath;
2219 break;
2220 }
2221 } else {
2222 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2223 $sql .= " WHERE fk_soc = ".((int) $id);
2224 if (!$this->db->query($sql)) {
2225 $error++;
2226 $this->errors[] = $this->db->lasterror();
2227 break;
2228 }
2229 }
2230 }
2231 }
2232
2233 // Removed extrafields
2234 if (!$error) {
2235 $result = $this->deleteExtraFields();
2236 if ($result < 0) {
2237 $error++;
2238 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2239 }
2240 }
2241
2242 // Remove links to subsidiaries companies
2243 if (!$error) {
2244 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2245 $sql .= " SET parent = NULL";
2246 $sql .= " WHERE parent = ".((int) $id);
2247 if (!$this->db->query($sql)) {
2248 $error++;
2249 $this->errors[] = $this->db->lasterror();
2250 }
2251 }
2252
2253 // Remove third party
2254 if (!$error) {
2255 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2256 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2257 $sql .= " WHERE fk_soc = ".((int) $id);
2258 if (!$this->db->query($sql)) {
2259 $error++;
2260 $this->errors[] = $this->db->lasterror();
2261 }
2262 }
2263
2264 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2265 $sql .= " WHERE rowid = ".((int) $id);
2266 if (!$this->db->query($sql)) {
2267 $error++;
2268 $this->errors[] = $this->db->lasterror();
2269 }
2270 }
2271
2272 if (!$error) {
2273 $this->db->commit();
2274
2275 // Delete directory
2276 if (!empty($conf->societe->multidir_output[$entity])) {
2277 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2278 if (dol_is_dir($docdir)) {
2279 dol_delete_dir_recursive($docdir);
2280 }
2281 }
2282
2283 return 1;
2284 } else {
2285 dol_syslog($this->error, LOG_ERR);
2286 $this->db->rollback();
2287 return -1;
2288 }
2289 } else {
2290 dol_syslog("Can't remove thirdparty with id ".$id.". There are ".$objectisused." children", LOG_WARNING);
2291 }
2292 return 0;
2293 }
2294
2295 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2303 public function set_as_client()
2304 {
2305 global $conf;
2306 // phpcs:enable
2307 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2308 return $this->setAsCustomer();
2309 }
2310
2317 public function setAsCustomer()
2318 {
2319 if ($this->id) {
2320 $newclient = 1;
2321 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2322 $newclient = 3; //If prospect, we keep prospect tag
2323 }
2324 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2325 $sql .= " SET client = ".((int) $newclient);
2326 $sql .= " WHERE rowid = ".((int) $this->id);
2327
2328 $resql = $this->db->query($sql);
2329 if ($resql) {
2330 $this->client = $newclient;
2331 return 1;
2332 } else {
2333 return -1;
2334 }
2335 }
2336 return 0;
2337 }
2338
2339 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2348 public function set_remise_client($remise, $note, User $user)
2349 {
2350 // phpcs:enable
2351 global $conf, $langs;
2352
2353 // Parameter cleaning
2354 $note = trim($note);
2355 if (!$note) {
2356 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2357 return -2;
2358 }
2359
2360 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2361
2362 if ($this->id) {
2363 $this->db->begin();
2364
2365 $now = dol_now();
2366
2367 // Position current discount
2368 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2369 $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2370 $sql .= " WHERE rowid = ".((int) $this->id);
2371 $resql = $this->db->query($sql);
2372 if (!$resql) {
2373 $this->db->rollback();
2374 $this->error = $this->db->error();
2375 return -1;
2376 }
2377
2378 // Writes trace in discount history
2379 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2380 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2381 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2382 $sql .= " '".$this->db->escape($note)."',";
2383 $sql .= " ".((int) $user->id);
2384 $sql .= ")";
2385
2386 $resql = $this->db->query($sql);
2387 if (!$resql) {
2388 $this->db->rollback();
2389 $this->error = $this->db->lasterror();
2390 return -1;
2391 }
2392
2393 $this->db->commit();
2394
2395 return 1;
2396 }
2397 return -1;
2398 }
2399
2400 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2409 public function set_remise_supplier($remise, $note, User $user)
2410 {
2411 // phpcs:enable
2412 global $conf, $langs;
2413
2414 // Parameter cleaning
2415 $note = trim($note);
2416 if (!$note) {
2417 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2418 return -2;
2419 }
2420
2421 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2422
2423 if ($this->id) {
2424 $this->db->begin();
2425
2426 $now = dol_now();
2427
2428 // Position current discount
2429 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2430 $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2431 $sql .= " WHERE rowid = ".((int) $this->id);
2432 $resql = $this->db->query($sql);
2433 if (!$resql) {
2434 $this->db->rollback();
2435 $this->error = $this->db->error();
2436 return -1;
2437 }
2438
2439 // Writes trace in discount history
2440 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2441 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2442 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2443 $sql .= " '".$this->db->escape($note)."',";
2444 $sql .= " ".((int) $user->id);
2445 $sql .= ")";
2446
2447 $resql = $this->db->query($sql);
2448 if (!$resql) {
2449 $this->db->rollback();
2450 $this->error = $this->db->lasterror();
2451 return -1;
2452 }
2453
2454 $this->db->commit();
2455 return 1;
2456 }
2457
2458 return -1;
2459 }
2460
2461 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2473 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2474 {
2475 // phpcs:enable
2476 global $langs;
2477
2478 // Clean parameters
2479 $remise = price2num($remise);
2480 $desc = trim($desc);
2481
2482 // Check parameters
2483 if (!($remise > 0)) {
2484 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2485 return -1;
2486 }
2487 if (!$desc) {
2488 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2489 return -2;
2490 }
2491
2492 if ($this->id > 0) {
2493 // Clean vat code
2494 $reg = array();
2495 $vat_src_code = '';
2496 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2497 $vat_src_code = $reg[1];
2498 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2499 }
2500
2501 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2502
2503 $discount = new DiscountAbsolute($this->db);
2504 $discount->fk_soc = $this->id;
2505 $discount->socid = $this->id;
2506
2507 $discount->discount_type = $discount_type;
2508 $discount->multicurrency_code = $this->multicurrency_code;
2509 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
2510 $discount->multicurrency_tx = $this->multicurrency_tx;
2511
2512 if ($price_base_type == 'TTC') {
2513 $discount->amount_ttc = price2num($remise, 'MT');
2514 $discount->amount_ht = price2num((float) $remise / (1 + (float) $vatrate / 100), 'MT');
2515 $discount->amount_tva = price2num((float) $discount->amount_ttc - (float) $discount->amount_ht, 'MT');
2516
2517 $discount->multicurrency_amount_ttc = price2num((float) $remise * (float) $discount->multicurrency_tx, 'MT');
2518 $discount->multicurrency_amount_ht = price2num(((float) $remise / (1 + (float) $vatrate / 100)) * (float) $discount->multicurrency_tx, 'MT');
2519 $discount->multicurrency_amount_tva = price2num(((float) $discount->amount_ttc - (float) $discount->amount_ht) * (float) $discount->multicurrency_tx, 'MT');
2520 } else {
2521 $discount->amount_ht = price2num($remise, 'MT');
2522 $discount->amount_tva = price2num((float) $remise * (float) $vatrate / 100, 'MT');
2523 $discount->amount_ttc = price2num((float) $discount->amount_ht + (float) $discount->amount_tva, 'MT');
2524
2525 $discount->multicurrency_amount_ht = price2num((float) $remise * (float) $discount->multicurrency_tx, 'MT');
2526 $discount->multicurrency_amount_tva = price2num(((float) $remise * (float) $vatrate / 100) * (float) $discount->multicurrency_tx, 'MT');
2527 $discount->multicurrency_amount_ttc = price2num(((float) $discount->amount_ht + (float) $discount->amount_tva) * (float) $discount->multicurrency_tx, 'MT');
2528 }
2529
2530 $discount->tva_tx = (float) price2num($vatrate);
2531 $discount->vat_src_code = $vat_src_code;
2532
2533 $discount->description = $desc;
2534
2535 $result = $discount->create($user);
2536 if ($result > 0) {
2537 return $result;
2538 } else {
2539 $this->error = $discount->error;
2540 return -3;
2541 }
2542 } else {
2543 return 0;
2544 }
2545 }
2546
2556 public function getAvailableDiscounts($user = null, $filter = '', $maxvalue = 0, $discount_type = 0)
2557 {
2558 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2559
2560 $discountstatic = new DiscountAbsolute($this->db);
2561 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2562 if ($result >= 0) {
2563 return $result;
2564 } else {
2565 $this->error = $discountstatic->error;
2566 return -1;
2567 }
2568 }
2569
2579 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2580 {
2581 global $conf;
2582
2583 $reparray = array();
2584
2585 $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";
2586 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2587 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2588 // Condition here should be the same than into select_dolusers()
2589 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2590 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2591 } else {
2592 $sql .= " WHERE entity IN (0, ".$this->db->sanitize($conf->entity).")";
2593 }
2594
2595 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2596 if (empty($sortfield) && empty($sortorder)) {
2597 $sortfield = 'u.lastname,u.firstname';
2598 $sortorder = 'ASC,ASC';
2599 }
2600 $sql .= $this->db->order($sortfield, $sortorder);
2601
2602 $resql = $this->db->query($sql);
2603 if ($resql) {
2604 $num = $this->db->num_rows($resql);
2605 $i = 0;
2606 while ($i < $num) {
2607 $obj = $this->db->fetch_object($resql);
2608
2609 if (empty($mode)) {
2610 $reparray[$i]['id'] = $obj->rowid;
2611 $reparray[$i]['lastname'] = $obj->lastname;
2612 $reparray[$i]['firstname'] = $obj->firstname;
2613 $reparray[$i]['email'] = $obj->email;
2614 $reparray[$i]['phone'] = $obj->office_phone;
2615 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2616 $reparray[$i]['office_fax'] = $obj->office_fax;
2617 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2618 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2619 $reparray[$i]['job'] = $obj->job;
2620 $reparray[$i]['statut'] = $obj->status; // deprecated
2621 $reparray[$i]['status'] = $obj->status;
2622 $reparray[$i]['entity'] = $obj->entity;
2623 $reparray[$i]['login'] = $obj->login;
2624 $reparray[$i]['photo'] = $obj->photo;
2625 $reparray[$i]['gender'] = $obj->gender;
2626 } else {
2627 $reparray[] = $obj->rowid;
2628 }
2629 $i++;
2630 }
2631 return $reparray;
2632 } else {
2633 dol_print_error($this->db);
2634 return -1;
2635 }
2636 }
2637
2645 public function setPriceLevel($price_level, User $user)
2646 {
2647 if ($this->id) {
2648 $now = dol_now();
2649
2650 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2651 $sql .= " SET price_level = ".((int) $price_level);
2652 $sql .= " WHERE rowid = ".((int) $this->id);
2653
2654 if (!$this->db->query($sql)) {
2655 dol_print_error($this->db);
2656 return -1;
2657 }
2658
2659 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2660 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2661 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2662
2663 if (!$this->db->query($sql)) {
2664 dol_print_error($this->db);
2665 return -1;
2666 }
2667 return 1;
2668 }
2669 return -1;
2670 }
2671
2672 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2680 public function add_commercial(User $user, $commid)
2681 {
2682 // phpcs:enable
2683 $error = 0;
2684
2685 if ($this->id > 0 && $commid > 0) {
2686 $this->db->begin();
2687
2688 if (!$error) {
2689 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2690 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2691
2692 $resql = $this->db->query($sql);
2693 if (!$resql) {
2694 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2695 $error++;
2696 }
2697 }
2698
2699 if (!$error) {
2700 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2701 $sql .= " (fk_soc, fk_user)";
2702 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2703
2704 $resql = $this->db->query($sql);
2705 if (!$resql) {
2706 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2707 $error++;
2708 }
2709 }
2710
2711 if (!$error) {
2712 $this->context = array('commercial_modified' => $commid);
2713
2714 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2715 if ($result < 0) {
2716 $error++;
2717 }
2718 }
2719
2720 if (!$error) {
2721 $this->db->commit();
2722 return 1;
2723 } else {
2724 $this->db->rollback();
2725 return -1;
2726 }
2727 }
2728
2729 return 0;
2730 }
2731
2732 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2740 public function del_commercial(User $user, $commid)
2741 {
2742 // phpcs:enable
2743 $error = 0;
2744 $this->context = array('commercial_modified' => $commid);
2745
2746 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2747 if ($result < 0) {
2748 $error++;
2749 }
2750
2751 if ($this->id > 0 && $commid > 0) {
2752 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2753 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2754
2755 if (!$this->db->query($sql)) {
2756 $error++;
2757 dol_syslog(get_class($this)."::del_commercial Erreur");
2758 }
2759 }
2760
2761 if ($error) {
2762 return -1;
2763 } else {
2764 return 1;
2765 }
2766 }
2767
2775 public function getTooltipContentArray($params)
2776 {
2777 global $conf, $langs, $user;
2778
2779 $langs->loadLangs(['companies', 'commercial']);
2780
2781 $datas = array();
2782
2783 $option = $params['option'] ?? '';
2784 $nofetch = !empty($params['nofetch']);
2785
2786 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2787
2788 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2789 return ['optimize' => $langs->trans("ShowCompany")];
2790 }
2791
2792 if (!empty($this->logo) && class_exists('Form')) {
2793 $photo = '<div class="photointooltip floatright">';
2794 $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.
2795 $photo .= '</div>';
2796 $datas['photo'] = $photo;
2797 } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2798 /*$label.= '<div class="photointooltip">';
2799 $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.
2800 $label.= '</div><div style="clear: both;"></div>';*/
2801 }
2802
2803 $datas['divopen'] = '<div class="centpercent">';
2804
2805 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2806 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2807 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2808 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2809 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2810 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2811 } elseif ($option == 'agenda') {
2812 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2813 } elseif ($option == 'project') {
2814 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2815 } elseif ($option == 'margin') {
2816 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2817 } elseif ($option == 'contact') {
2818 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2819 } elseif ($option == 'ban') {
2820 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2821 }
2822
2823 // By default
2824 if (empty($datas['picto'])) {
2825 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2826 }
2827 if (isset($this->status)) {
2828 $datas['status'] = ' '.$this->getLibStatut(5);
2829 }
2830 if (isset($this->client) && isset($this->fournisseur)) {
2831 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2832 }
2833 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2834 if (!empty($this->name_alias) && empty($noaliasinname)) {
2835 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2836 }
2837 if (!empty($this->email)) {
2838 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2839 }
2840 if (!empty($this->url)) {
2841 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2842 }
2843 if (!empty($this->phone) || !empty($this->phone_mobile) || !empty($this->fax)) {
2844 $phonelist = array();
2845 if ($this->phone) {
2846 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2847 }
2848 // deliberately not making new list because fax uses same list as phone
2849 if ($this->phone_mobile) {
2850 $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp', 'phone_mobile');
2851 }
2852 if ($this->fax) {
2853 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2854 }
2855 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2856 }
2857
2858 if (!empty($this->address)) {
2859 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2860 } elseif (!empty($this->country_code)) {
2861 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2862 }
2863 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2864 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2865 }
2866
2867 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
2868 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2869 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2870 }
2871 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2872 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2873 }
2874 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2875 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2876 }
2877 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2878 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2879 }
2880 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2881 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2882 }
2883 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2884 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2885 }
2886 }
2887
2888 $datas['separator'] = '<br>';
2889
2890 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2891 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2892 }
2893 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2894 $langs->load('compta');
2895 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2896 }
2897 // show categories for this record only in ajax to not overload lists
2898 if (!$nofetch && isModEnabled('category') && $this->client) {
2899 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2900 $form = new Form($this->db);
2901 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2902 }
2903 if (!empty($this->code_fournisseur) && $this->fournisseur) {
2904 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2905 }
2906 if (isModEnabled('accounting') && $this->fournisseur) {
2907 $langs->load('compta');
2908 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2909 }
2910 // show categories for this record only in ajax to not overload lists
2911 if (!$nofetch && isModEnabled('category') && $this->fournisseur) {
2912 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2913 $form = new Form($this->db);
2914 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2915 }
2916
2917 $datas['divclose'] = '</div>';
2918
2919 return $datas;
2920 }
2921
2935 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '', $morecss = '')
2936 {
2937 global $conf, $langs, $hookmanager, $user;
2938
2939 if (!empty($conf->dol_no_mouse_hover)) {
2940 $notooltip = 1; // Force disable tooltips
2941 }
2942
2943 $name = $this->name ? $this->name : $this->nom;
2944
2945 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
2946 if (empty($option) && $this->client > 0) {
2947 $option = 'customer';
2948 }
2949 if (empty($option) && $this->fournisseur > 0) {
2950 $option = 'supplier';
2951 }
2952 }
2953
2954 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
2955 $code = '';
2956 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
2957 $code = $this->code_client.' - ';
2958 }
2959
2960 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
2961 $code .= $this->code_fournisseur.' - ';
2962 }
2963
2964 if ($code) {
2965 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
2966 $name = $code.' '.$name;
2967 } else {
2968 $name = $code;
2969 }
2970 }
2971 }
2972
2973 if (!empty($this->name_alias) && empty($noaliasinname)) {
2974 $name .= ' ('.$this->name_alias.')';
2975 }
2976
2977 $result = '';
2978 $params = [
2979 'id' => $this->id,
2980 'objecttype' => $this->element,
2981 'option' => $option,
2982 'nofetch' => 1,
2983 ];
2984 $classfortooltip = 'classfortooltip';
2985 $dataparams = '';
2986 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2987 $classfortooltip = 'classforajaxtooltip';
2988 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2989 $label = '';
2990 } else {
2991 $label = implode($this->getTooltipContentArray($params));
2992 }
2993
2994 $linkstart = '';
2995 $linkend = '';
2996
2997 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2998 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2999 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3000 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
3001 } elseif ($option == 'supplier' || $option == 'category_supplier') {
3002 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
3003 } elseif ($option == 'agenda') {
3004 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
3005 } elseif ($option == 'project') {
3006 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
3007 } elseif ($option == 'margin') {
3008 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
3009 } elseif ($option == 'contact') {
3010 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
3011 } elseif ($option == 'ban') {
3012 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
3013 }
3014
3015 // By default
3016 if (empty($linkstart)) {
3017 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
3018 }
3019
3020 // Add type of canvas
3021 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
3022 // Add param to save lastsearch_values or not
3023 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3024 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3025 $add_save_lastsearch_values = 1;
3026 }
3027 if ($add_save_lastsearch_values) {
3028 $linkstart .= '&save_lastsearch_values=1';
3029 }
3030 $linkstart .= '"';
3031
3032 $linkclose = '';
3033 if (empty($notooltip)) {
3034 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3035 $label = $langs->trans("ShowCompany");
3036 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3037 }
3038 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
3039 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').' refurl valignmiddle"';
3040 $target_value = array('_self', '_blank', '_parent', '_top');
3041 if (in_array($target, $target_value)) {
3042 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3043 }
3044 } else {
3045 $linkclose .= ' class="valignmiddle'.($morecss ? ' '.$morecss : '').'"';
3046 }
3047 $linkstart .= $linkclose.'>';
3048 $linkend = '</a>';
3049
3050 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
3051 $linkstart = '';
3052 $linkend = '';
3053 }
3054
3055 $result .= $linkstart;
3056 if ($withpicto) {
3057 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3058 }
3059 if ($withpicto != 2) {
3060 $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
3061 }
3062 $result .= $linkend;
3063
3064 global $action;
3065 $hookmanager->initHooks(array('thirdpartydao'));
3066 $parameters = array(
3067 'id' => $this->id,
3068 'getnomurl' => &$result,
3069 'withpicto ' => $withpicto,
3070 'option' => $option,
3071 'maxlen' => $maxlen,
3072 'notooltip' => $notooltip,
3073 'save_lastsearch_value' => $save_lastsearch_value
3074 );
3075 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3076 if ($reshook > 0) {
3077 $result = $hookmanager->resPrint;
3078 } else {
3079 $result .= $hookmanager->resPrint;
3080 }
3081
3082 return $result;
3083 }
3084
3094 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
3095 {
3096 global $conf, $langs;
3097
3098 $s = '';
3099 if (empty($option) || preg_match('/prospect/', $option)) {
3100 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3101 $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.'>';
3102 }
3103 }
3104 if (empty($option) || preg_match('/customer/', $option)) {
3105 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3106 $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.'>';
3107 }
3108 }
3109 if (empty($option) || preg_match('/supplier/', $option)) {
3110 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3111 $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.'>';
3112 }
3113 }
3114 return $s;
3115 }
3116
3117
3124 public function getLibStatut($mode = 0)
3125 {
3126 return $this->LibStatut($this->status, $mode);
3127 }
3128
3129 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3137 public function LibStatut($status, $mode = 0)
3138 {
3139 // phpcs:enable
3140 global $langs;
3141 $langs->load('companies');
3142
3143 $statusType = 'status4';
3144 if ($status == 0) {
3145 $statusType = 'status6';
3146 }
3147
3148 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3149 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3150 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3151 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3152 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3153 }
3154
3155 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3156 }
3157
3158 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3165 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3166 {
3167 // phpcs:enable
3168 global $langs;
3169
3170 $contact_emails = $this->contact_property_array('email', 1);
3171
3172 if ($this->email && $addthirdparty) {
3173 if (empty($this->name)) {
3174 $this->name = $this->nom;
3175 }
3176 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3177 }
3178
3179 //var_dump($contact_emails)
3180 return $contact_emails;
3181 }
3182
3183 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3190 {
3191 // phpcs:enable
3192 global $langs;
3193
3194 $contact_phone = $this->contact_property_array('mobile');
3195
3196 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it to mobile of contacts
3197 if (empty($this->name)) {
3198 $this->name = $this->nom;
3199 }
3200 // TODO: Tester si tel non deja present dans tableau contact
3201 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3202 }
3203 return $contact_phone;
3204 }
3205
3206 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3214 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3215 {
3216 // phpcs:enable
3217 global $langs;
3218
3219 $contact_property = array();
3220
3221
3222 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3223 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3224 $sql .= " WHERE fk_soc = ".((int) $this->id);
3225 $sql .= " AND entity IN (".getEntity($this->element).")";
3226 $sql .= " ORDER BY lastname, firstname";
3227
3228 $resql = $this->db->query($sql);
3229 if ($resql) {
3230 $nump = $this->db->num_rows($resql);
3231 if ($nump) {
3232 $sepa = "(";
3233 $sepb = ")";
3234 if ($mode == 'email') {
3235 //$sepa="&lt;"; $sepb="&gt;";
3236 $sepa = "<";
3237 $sepb = ">";
3238 }
3239 $i = 0;
3240 while ($i < $nump) {
3241 $obj = $this->db->fetch_object($resql);
3242 if ($mode == 'email') {
3243 $property = $obj->email;
3244 } elseif ($mode == 'mobile') {
3245 $property = $obj->phone_mobile;
3246 } else {
3247 $property = $obj->$mode;
3248 }
3249
3250 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3251 if ($obj->status == 1 || empty($hidedisabled)) {
3252 if (empty($property)) {
3253 if ($mode == 'email') {
3254 $property = $langs->transnoentitiesnoconv("NoEMail");
3255 } elseif ($mode == 'mobile') {
3256 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3257 }
3258 }
3259
3260 if (!empty($obj->poste)) {
3261 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3262 } else {
3263 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3264 }
3265 }
3266 $i++;
3267 }
3268 }
3269 } else {
3270 dol_print_error($this->db);
3271 }
3272 return $contact_property;
3273 }
3274
3275
3276 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3282 public function contact_array()
3283 {
3284 // phpcs:enable
3285 $contacts = array();
3286
3287 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3288 $resql = $this->db->query($sql);
3289 if ($resql) {
3290 $nump = $this->db->num_rows($resql);
3291 if ($nump) {
3292 $i = 0;
3293 while ($i < $nump) {
3294 $obj = $this->db->fetch_object($resql);
3295 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3296 $i++;
3297 }
3298 }
3299 } else {
3300 dol_print_error($this->db);
3301 }
3302 return $contacts;
3303 }
3304
3305 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3311 public function contact_array_objects()
3312 {
3313 // phpcs:enable
3314 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3315 $contacts = array();
3316
3317 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3318 $resql = $this->db->query($sql);
3319 if ($resql) {
3320 $nump = $this->db->num_rows($resql);
3321 if ($nump) {
3322 $i = 0;
3323 while ($i < $nump) {
3324 $obj = $this->db->fetch_object($resql);
3325 $contact = new Contact($this->db);
3326 $contact->fetch($obj->rowid);
3327 $contacts[] = $contact;
3328 $i++;
3329 }
3330 }
3331 } else {
3332 dol_print_error($this->db);
3333 }
3334 return $contacts;
3335 }
3336
3337 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3345 public function contact_get_property($rowid, $mode)
3346 {
3347 // phpcs:enable
3348 $contact_property = '';
3349
3350 if (empty($rowid)) {
3351 return '';
3352 }
3353
3354 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3355 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3356 $sql .= " WHERE rowid = ".((int) $rowid);
3357
3358 $resql = $this->db->query($sql);
3359 if ($resql) {
3360 $nump = $this->db->num_rows($resql);
3361
3362 if ($nump) {
3363 $obj = $this->db->fetch_object($resql);
3364
3365 if ($mode == 'email') {
3366 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3367 } elseif ($mode == 'mobile') {
3368 $contact_property = $obj->phone_mobile;
3369 }
3370 }
3371 return $contact_property;
3372 } else {
3373 dol_print_error($this->db);
3374 }
3375
3376 return '';
3377 }
3378
3379
3380 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3387 public function display_rib($mode = 'label')
3388 {
3389 // phpcs:enable
3390 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3391
3392 $bac = new CompanyBankAccount($this->db);
3393 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
3394 $bac->fetch(0, '', $this->id);
3395
3396 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3397 if ($mode == 'label') {
3398 return $bac->getRibLabel(true);
3399 } elseif ($mode == 'rum') {
3400 if (empty($bac->rum)) {
3401 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3402 $prelevement = new BonPrelevement($this->db);
3403 $bac->fetch_thirdparty();
3404 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3405 }
3406 return $bac->rum;
3407 } elseif ($mode == 'format') {
3408 return $bac->frstrecur;
3409 } else {
3410 return 'BadParameterToFunctionDisplayRib';
3411 }
3412 } else {
3413 return '';
3414 }
3415 }
3416
3417 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3423 public function get_all_rib()
3424 {
3425 // phpcs:enable
3426 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3427 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3428 $result = $this->db->query($sql);
3429 if (!$result) {
3430 $this->error++;
3431 $this->errors[] = $this->db->lasterror;
3432 return 0;
3433 } else {
3434 $num_rows = $this->db->num_rows($result);
3435 $rib_array = array();
3436 if ($num_rows) {
3437 while ($obj = $this->db->fetch_object($result)) {
3438 $rib = new CompanyBankAccount($this->db);
3439 $rib->fetch($obj->rowid);
3440 $rib_array[] = $rib;
3441 }
3442 }
3443 return $rib_array;
3444 }
3445 }
3446
3447 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3456 public function get_codeclient($objsoc = null, $type = 0)
3457 {
3458 // phpcs:enable
3459 global $conf;
3460 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3461 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3462
3463 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3464 foreach ($dirsociete as $dirroot) {
3465 $res = dol_include_once($dirroot.$module.'.php');
3466 if ($res) {
3467 break;
3468 }
3469 }
3471 $mod = new $module($this->db);
3472
3473 $this->code_client = $mod->getNextValue($objsoc, $type);
3474 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3475
3476 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3477 }
3478 }
3479
3480 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3489 public function get_codefournisseur($objsoc = null, $type = 1)
3490 {
3491 // phpcs:enable
3492 global $conf;
3493 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3494 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3495
3496 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3497 foreach ($dirsociete as $dirroot) {
3498 $res = dol_include_once($dirroot.$module.'.php');
3499 if ($res) {
3500 break;
3501 }
3502 }
3504 $mod = new $module($this->db);
3505
3506 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3507
3508 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3509 }
3510 }
3511
3512 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3519 public function codeclient_modifiable()
3520 {
3521 // phpcs:enable
3522 global $conf;
3523 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3524 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3525
3526 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3527 foreach ($dirsociete as $dirroot) {
3528 $res = dol_include_once($dirroot.$module.'.php');
3529 if ($res) {
3530 break;
3531 }
3532 }
3533
3534 $mod = new $module($this->db);
3535
3536 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3537 if ($mod->code_modifiable_null && !$this->code_client) {
3538 return 1;
3539 }
3540 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3541 return 1;
3542 }
3543 if ($mod->code_modifiable) {
3544 return 1; // A mettre en dernier
3545 }
3546 return 0;
3547 } else {
3548 return 0;
3549 }
3550 }
3551
3552
3553 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3560 {
3561 // phpcs:enable
3562 global $conf;
3563 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3564 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3565
3566 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3567 foreach ($dirsociete as $dirroot) {
3568 $res = dol_include_once($dirroot.$module.'.php');
3569 if ($res) {
3570 break;
3571 }
3572 }
3573
3574 $mod = new $module($this->db);
3575
3576 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3577 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3578 return 1;
3579 }
3580 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3581 return 1;
3582 }
3583 if ($mod->code_modifiable) {
3584 return 1; // A mettre en dernier
3585 }
3586 return 0;
3587 } else {
3588 return 0;
3589 }
3590 }
3591
3592
3593 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3605 public function check_codeclient()
3606 {
3607 // phpcs:enable
3608 global $conf;
3609 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3610 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3611
3612 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3613 foreach ($dirsociete as $dirroot) {
3614 $res = dol_include_once($dirroot.$module.'.php');
3615 if ($res) {
3616 break;
3617 }
3618 }
3619
3620 $mod = new $module($this->db);
3621
3622 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3623 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3624 if ($result) { // If error
3625 $this->error = $mod->error;
3626 $this->errors = $mod->errors;
3627 }
3628 return $result;
3629 } else {
3630 return 0;
3631 }
3632 }
3633
3634 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3646 public function check_codefournisseur()
3647 {
3648 // phpcs:enable
3649 global $conf;
3650 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3651 $module = getDolGlobalString('SOCIETE_CODECLIENT_ADDON');
3652
3653 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3654 foreach ($dirsociete as $dirroot) {
3655 $res = dol_include_once($dirroot.$module.'.php');
3656 if ($res) {
3657 break;
3658 }
3659 }
3660
3661 $mod = new $module($this->db);
3662
3663 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3664 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3665 if ($result) { // If error
3666 $this->error = $mod->error;
3667 $this->errors = $mod->errors;
3668 }
3669 return $result;
3670 } else {
3671 return 0;
3672 }
3673 }
3674
3675 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3684 public function get_codecompta($type)
3685 {
3686 // phpcs:enable
3687 global $conf;
3688
3689 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3690 $module = getDolGlobalString('SOCIETE_CODECOMPTA_ADDON');
3691 $res = false;
3692 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3693 foreach ($dirsociete as $dirroot) {
3694 $res = dol_include_once($dirroot.$module.'.php');
3695 if ($res) {
3696 break;
3697 }
3698 }
3699
3700 if ($res) {
3701 $mod = new $module();
3702
3703 // Set code count in $mod->code
3704 $result = $mod->get_code($this->db, $this, $type);
3705
3706 if ($type == 'customer') {
3707 $this->code_compta_client = $mod->code;
3708 $this->code_compta = $this->code_compta_client; // For backward compatibility
3709 } elseif ($type == 'supplier') {
3710 $this->code_compta_fournisseur = $mod->code;
3711 }
3712
3713 return $result;
3714 } else {
3715 $this->error = 'ErrorAccountancyCodeNotDefined';
3716 return -1;
3717 }
3718 } else {
3719 if ($type == 'customer') {
3720 $this->code_compta_client = '';
3721 $this->code_compta = '';
3722 } elseif ($type == 'supplier') {
3723 $this->code_compta_fournisseur = '';
3724 }
3725
3726 return 0;
3727 }
3728 }
3729
3736 public function setParent($id)
3737 {
3738 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3739
3740 if ($this->id) {
3741 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3742 if ($id > 0) {
3743 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3744 if ($sameparent < 0) {
3745 return -1;
3746 }
3747 if ($sameparent == 1) {
3748 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3749 return -1;
3750 }
3751 }
3752
3753 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3754
3755 $resql = $this->db->query($sql);
3756 if ($resql) {
3757 $this->parent = $id;
3758 return 1;
3759 } else {
3760 return -1;
3761 }
3762 }
3763
3764 return -1;
3765 }
3766
3775 public function validateFamilyTree($idparent, $idchild, $counter = 0)
3776 {
3777 if ($counter > 100) {
3778 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3779 }
3780
3781 $sql = 'SELECT s.parent';
3782 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3783 $sql .= ' WHERE rowid = '.((int) $idparent);
3784 $resql = $this->db->query($sql);
3785 if ($resql) {
3786 $obj = $this->db->fetch_object($resql);
3787
3788 if ($obj->parent == '') {
3789 return 0;
3790 } elseif ($obj->parent == $idchild) {
3791 return 1;
3792 } else {
3793 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3794 }
3795 return $sameparent;
3796 } else {
3797 return -1;
3798 }
3799 }
3800
3808 public function getParentsForCompany($company_id, $parents = array())
3809 {
3810 global $langs;
3811
3812 if ($company_id > 0) {
3813 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3814 $resql = $this->db->query($sql);
3815 if ($resql) {
3816 if ($obj = $this->db->fetch_object($resql)) {
3817 $parent = $obj->parent;
3818 if ($parent > 0 && !in_array($parent, $parents)) {
3819 $parents[] = $parent;
3820 return $this->getParentsForCompany($parent, $parents);
3821 } else {
3822 return $parents;
3823 }
3824 }
3825 $this->db->free($resql);
3826 } else {
3827 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3828 }
3829 }
3830 // Return a default value when $company_id is not greater than 0
3831 return array();
3832 }
3833
3834 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3841 public function id_prof_verifiable($idprof)
3842 {
3843 // phpcs:enable
3844 global $conf;
3845
3846 switch ($idprof) {
3847 case 1:
3848 $ret = (!getDolGlobalString('SOCIETE_IDPROF1_UNIQUE') ? false : true);
3849 break;
3850 case 2:
3851 $ret = (!getDolGlobalString('SOCIETE_IDPROF2_UNIQUE') ? false : true);
3852 break;
3853 case 3:
3854 $ret = (!getDolGlobalString('SOCIETE_IDPROF3_UNIQUE') ? false : true);
3855 break;
3856 case 4:
3857 $ret = (!getDolGlobalString('SOCIETE_IDPROF4_UNIQUE') ? false : true);
3858 break;
3859 case 5:
3860 $ret = (!getDolGlobalString('SOCIETE_IDPROF5_UNIQUE') ? false : true);
3861 break;
3862 case 6:
3863 $ret = (!getDolGlobalString('SOCIETE_IDPROF6_UNIQUE') ? false : true);
3864 break;
3865 default:
3866 $ret = false;
3867 }
3868
3869 return $ret;
3870 }
3871
3872 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3881 public function id_prof_exists($idprof, $value, $socid = 0)
3882 {
3883 // phpcs:enable
3884 $field = $idprof;
3885
3886 switch ($idprof) { // For backward compatibility
3887 case '1':
3888 case 'idprof1':
3889 $field = "siren";
3890 break;
3891 case '2':
3892 case 'idprof2':
3893 $field = "siret";
3894 break;
3895 case '3':
3896 case 'idprof3':
3897 $field = "ape";
3898 break;
3899 case '4':
3900 case 'idprof4':
3901 $field = "idprof4";
3902 break;
3903 case '5':
3904 $field = "idprof5";
3905 break;
3906 case '6':
3907 $field = "idprof6";
3908 break;
3909 }
3910
3911 //Verify duplicate entries
3912 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3913 if ($socid) {
3914 $sql .= " AND rowid <> ".$socid;
3915 }
3916 $resql = $this->db->query($sql);
3917 if ($resql) {
3918 $obj = $this->db->fetch_object($resql);
3919 $count = $obj->nb;
3920 } else {
3921 $count = 0;
3922 print $this->db->error();
3923 }
3924 $this->db->free($resql);
3925
3926 if ($count > 0) {
3927 return true;
3928 } else {
3929 return false;
3930 }
3931 }
3932
3933 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3942 public function id_prof_check($idprof, $soc)
3943 {
3944 // phpcs:enable
3945 global $conf;
3946
3947 // load the library necessary to check the professional identifiers
3948 require_once DOL_DOCUMENT_ROOT.'/core/lib/profid.lib.php';
3949
3950 $ok = 1;
3951
3952 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
3953 return 1;
3954 }
3955
3956 // Check SIREN
3957 if ($idprof == 1 && $soc->country_code == 'FR' && !isValidSiren($this->idprof1)) {
3958 return -1;
3959 }
3960
3961 // Check SIRET
3962 if ($idprof == 2 && $soc->country_code == 'FR' && !isValidSiret($this->idprof2)) {
3963 return -1;
3964 }
3965
3966 //Verify CIF/NIF/NIE if pays ES
3967 if ($idprof == 1 && $soc->country_code == 'ES') {
3968 return isValidTinForES($this->idprof1);
3969 }
3970
3971 //Verify NIF if country is PT
3972 if ($idprof == 1 && $soc->country_code == 'PT' && !isValidTinForPT($this->idprof1)) {
3973 return -1;
3974 }
3975
3976 //Verify NIF if country is DZ
3977 if ($idprof == 1 && $soc->country_code == 'DZ' && !isValidTinForDZ($this->idprof1)) {
3978 return -1;
3979 }
3980
3981 //Verify ID Prof 1 if country is BE
3982 if ($idprof == 1 && $soc->country_code == 'BE' && !isValidTinForBE($this->idprof1)) {
3983 return -1;
3984 }
3985
3986 return $ok;
3987 }
3988
3989 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3998 public function id_prof_url($idprof, $thirdparty)
3999 {
4000 // phpcs:enable
4001 global $conf, $langs, $hookmanager;
4002
4003 $url = '';
4004 $action = '';
4005
4006 $hookmanager->initHooks(array('idprofurl'));
4007 $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
4008 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4009 if (empty($reshook)) {
4010 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4011 return '';
4012 }
4013
4014 // TODO Move links to validate professional ID into a dictionary table "country" + "link"
4015 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4016 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4017 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
4018 }
4019 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4020 $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
4021 }
4022 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4023 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
4024 }
4025 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4026 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4027 }
4028 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4029 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
4030 }
4031 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4032 $url = 'http://www.nif.pt/'.$strippedIdProf1;
4033 }
4034
4035 if ($url) {
4036 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4037 }
4038 } else {
4039 return $hookmanager->resPrint;
4040 }
4041
4042 return '';
4043 }
4044
4045 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4051 public function has_projects()
4052 {
4053 // phpcs:enable
4054 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4055 $resql = $this->db->query($sql);
4056 if ($resql) {
4057 $obj = $this->db->fetch_object($resql);
4058 $count = $obj->numproj;
4059 } else {
4060 $count = 0;
4061 print $this->db->error();
4062 }
4063 $this->db->free($resql);
4064 return ($count > 0);
4065 }
4066
4067
4074 public function info($id)
4075 {
4076 $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4077 $sql .= " fk_user_creat, fk_user_modif";
4078 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4079 $sql .= " WHERE s.rowid = ".((int) $id);
4080
4081 $result = $this->db->query($sql);
4082 if ($result) {
4083 if ($this->db->num_rows($result)) {
4084 $obj = $this->db->fetch_object($result);
4085
4086 $this->id = $obj->rowid;
4087
4088 $this->user_creation_id = $obj->fk_user_creat;
4089 $this->user_modification_id = $obj->fk_user_modif;
4090 $this->date_creation = $this->db->jdate($obj->datec);
4091 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4092
4093 $this->ref = $obj->name;
4094 }
4095
4096 $this->db->free($result);
4097 } else {
4098 dol_print_error($this->db);
4099 }
4100 }
4101
4107 public function isACompany()
4108 {
4109 // Define if third party is treated as company (or not) when nature is unknown
4110 $isACompany = getDolGlobalInt('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES');
4111
4112 // Now try to guess using different tips
4113 if (!empty($this->tva_intra)) {
4114 $isACompany = 1;
4115 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4116 $isACompany = 1;
4117 } else {
4118 if (!getDolGlobalString('MAIN_CUSTOMERS_ARE_COMPANIES_EVEN_IF_SET_AS_INDIVIDUAL')) {
4119 // TODO Add a field is_a_company into dictionary
4120 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4121 $isACompany = 0;
4122 } else {
4123 $isACompany = 1;
4124 }
4125 } else {
4126 $isACompany = 1;
4127 }
4128 }
4129
4130 return (bool) $isACompany;
4131 }
4132
4138 public function isInEEC()
4139 {
4140 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4141 return isInEEC($this);
4142 }
4143
4144 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4150 public function LoadSupplierCateg()
4151 {
4152 // phpcs:enable
4153 $this->SupplierCategories = array();
4154 $sql = "SELECT rowid, label";
4155 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4156 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4157
4158 $resql = $this->db->query($sql);
4159 if ($resql) {
4160 while ($obj = $this->db->fetch_object($resql)) {
4161 $this->SupplierCategories[$obj->rowid] = $obj->label;
4162 }
4163 return 0;
4164 } else {
4165 return -1;
4166 }
4167 }
4168
4169 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4176 public function AddFournisseurInCategory($categorie_id)
4177 {
4178 // phpcs:enable
4179 if ($categorie_id > 0 && $this->id > 0) {
4180 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4181 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4182
4183 if ($resql = $this->db->query($sql)) {
4184 return 0;
4185 }
4186 } else {
4187 return 0;
4188 }
4189 return -1;
4190 }
4191
4197 public function getNbOfEMailings()
4198 {
4199 $sql = "SELECT count(mc.email) as nb";
4200 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4201 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4202 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4203
4204 $resql = $this->db->query($sql);
4205 if ($resql) {
4206 $obj = $this->db->fetch_object($resql);
4207 $nb = $obj->nb;
4208
4209 $this->db->free($resql);
4210 return $nb;
4211 } else {
4212 $this->error = $this->db->error();
4213 return -1;
4214 }
4215 }
4216
4223 public function setNoEmail($no_email)
4224 {
4225 $error = 0;
4226
4227 // Update mass emailing flag into table mailing_unsubscribe
4228 if ($this->email) {
4229 $this->db->begin();
4230
4231 if ($no_email) {
4232 $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)."'";
4233 $resql = $this->db->query($sql);
4234 if ($resql) {
4235 $obj = $this->db->fetch_object($resql);
4236 $noemail = $obj->nb;
4237 if (empty($noemail)) {
4238 $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())."')";
4239 $resql = $this->db->query($sql);
4240 if (!$resql) {
4241 $error++;
4242 $this->error = $this->db->lasterror();
4243 $this->errors[] = $this->error;
4244 }
4245 }
4246 } else {
4247 $error++;
4248 $this->error = $this->db->lasterror();
4249 $this->errors[] = $this->error;
4250 }
4251 } else {
4252 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4253 $resql = $this->db->query($sql);
4254 if (!$resql) {
4255 $error++;
4256 $this->error = $this->db->lasterror();
4257 $this->errors[] = $this->error;
4258 }
4259 }
4260
4261 if (empty($error)) {
4262 $this->no_email = $no_email;
4263 $this->db->commit();
4264 return 1;
4265 } else {
4266 $this->db->rollback();
4267 return $error * -1;
4268 }
4269 }
4270
4271 return 0;
4272 }
4273
4280 public function getNoEmail()
4281 {
4282 if ($this->email) {
4283 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4284 $resql = $this->db->query($sql);
4285 if ($resql) {
4286 $obj = $this->db->fetch_object($resql);
4287 $this->no_email = $obj->nb;
4288 return 1;
4289 } else {
4290 $this->error = $this->db->lasterror();
4291 $this->errors[] = $this->error;
4292 return -1;
4293 }
4294 }
4295 return 0;
4296 }
4297
4298 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4308 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4309 {
4310 // phpcs:enable
4311 global $conf, $user, $langs;
4312
4313 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4314 $fullname = $member->getFullName($langs);
4315
4316 if ($member->morphy == 'mor') {
4317 if (empty($socname)) {
4318 $socname = $member->company ? $member->company : $member->societe;
4319 }
4320 if (!empty($fullname) && empty($socalias)) {
4321 $socalias = $fullname;
4322 }
4323 } elseif (empty($socname) && $member->morphy == 'phy') {
4324 if (empty($socname)) {
4325 $socname = $fullname;
4326 }
4327 if (!empty($member->company) && empty($socalias)) {
4328 $socalias = $member->company;
4329 }
4330 }
4331
4332 $name = $socname;
4333 $alias = $socalias ? $socalias : '';
4334
4335 // Positionne parameters
4336 $this->nom = $name; // TODO deprecated
4337 $this->name = $name;
4338 $this->name_alias = $alias;
4339 $this->address = $member->address;
4340 $this->zip = $member->zip;
4341 $this->town = $member->town;
4342 $this->country_code = $member->country_code;
4343 $this->country_id = $member->country_id;
4344 $this->phone = $member->phone; // Prof phone
4345 $this->email = $member->email;
4346 $this->socialnetworks = $member->socialnetworks;
4347 $this->entity = $member->entity;
4348
4349 $this->client = 1; // A member is a customer by default
4350 $this->code_client = ($customercode ? $customercode : -1);
4351 $this->code_fournisseur = '-1';
4352 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4353 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4354
4355 $this->db->begin();
4356
4357 // Cree et positionne $this->id
4358 $result = $this->create($user);
4359
4360 if ($result >= 0) {
4361 // Auto-create contact on thirdparty creation
4362 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4363 // Fill fields needed by contact
4364 $this->name_bis = $member->lastname;
4365 $this->firstname = $member->firstname;
4366 $this->civility_id = $member->civility_id;
4367
4368 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4369 $result = $this->create_individual($user);
4370
4371 if ($result < 0) {
4372 setEventMessages($this->error, $this->errors, 'errors');
4373 $this->db->rollback();
4374 return -1;
4375 }
4376 }
4377
4378 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4379 $sql .= " SET fk_soc = ".((int) $this->id);
4380 $sql .= " WHERE rowid = ".((int) $member->id);
4381
4382 $resql = $this->db->query($sql);
4383 if ($resql) {
4384 $this->db->commit();
4385 return $this->id;
4386 } else {
4387 $this->error = $this->db->error();
4388
4389 $this->db->rollback();
4390 return -1;
4391 }
4392 } else {
4393 // $this->error deja positionne
4394 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".implode(',', $this->errors), LOG_ERR);
4395
4396 $this->db->rollback();
4397 return $result;
4398 }
4399 }
4400
4407 public function setMysoc(Conf $conf)
4408 {
4409 global $langs;
4410
4411 $this->id = 0;
4412 $this->entity = $conf->entity;
4413 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4414 $this->nom = $this->name; // deprecated
4415 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4416 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4417 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4418 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4419
4420 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4421
4422 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4423
4424 // We define country_id, country_code and country
4425 $country_id = 0;
4426 $country_code = $country_label = '';
4427 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4428 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4429 $country_id = (is_numeric($tmp[0])) ? (int) $tmp[0] : 0;
4430 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4431 $country_code = $tmp[1];
4432 $country_label = $tmp[2];
4433 } else {
4434 // For backward compatibility
4435 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4436 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4437 $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
4438 $country_label = getCountry($country_id, 0, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
4439 }
4440 }
4441 $this->country_id = $country_id;
4442 $this->country_code = $country_code;
4443 $this->country = $country_label;
4444 if (is_object($langs)) {
4445 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4446 }
4447
4448 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4449 // We define state_id, state_code and state
4450 $state_id = 0;
4451 $state_code = $state_label = '';
4452 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4453 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4454 $state_id = $tmp[0];
4455 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4456 $state_code = $tmp[1];
4457 $state_label = $tmp[2];
4458 } else { // For backward compatibility
4459 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);
4460 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4461 $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
4462 $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
4463 }
4464 }
4465 $this->state_id = $state_id;
4466 $this->state_code = $state_code;
4467 $this->state = $state_label;
4468 if (is_object($langs)) {
4469 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4470 }
4471
4472 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4473 $this->phone_mobile = getDolGlobalString('MAIN_INFO_SOCIETE_MOBILE');
4474 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4475 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4476
4477 // Social networks
4478 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4479 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4480 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4481 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4482 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4483 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4484 $this->socialnetworks = array();
4485 if (!empty($facebook_url)) {
4486 $this->socialnetworks['facebook'] = $facebook_url;
4487 }
4488 if (!empty($twitter_url)) {
4489 $this->socialnetworks['twitter'] = $twitter_url;
4490 }
4491 if (!empty($linkedin_url)) {
4492 $this->socialnetworks['linkedin'] = $linkedin_url;
4493 }
4494 if (!empty($instagram_url)) {
4495 $this->socialnetworks['instagram'] = $instagram_url;
4496 }
4497 if (!empty($youtube_url)) {
4498 $this->socialnetworks['youtube'] = $youtube_url;
4499 }
4500 if (!empty($github_url)) {
4501 $this->socialnetworks['github'] = $github_url;
4502 }
4503
4504 // Id prof generiques
4505 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4506 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4507 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4508 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4509 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4510 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4511 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
4512 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4513 $this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;
4514 $this->forme_juridique_code = getDolGlobalString('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4515 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4516 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4517 $this->logo = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4518 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4519 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4520 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4521 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4522 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4523
4524 // Define if company use vat or not
4525 $this->tva_assuj = getDolGlobalInt('FACTURE_TVAOPTION');
4526
4527 // Define if company use local taxes
4528 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4529 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4530 }
4531
4539 public function initAsSpecimen()
4540 {
4541 $now = dol_now();
4542
4543 // Initialize parameters
4544 $this->id = 0;
4545 $this->entity = 1;
4546 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4547 $this->nom = $this->name; // For backward compatibility
4548 $this->ref_ext = 'Ref ext';
4549 $this->specimen = 1;
4550 $this->address = '21 jump street';
4551 $this->zip = '99999';
4552 $this->town = 'MyTown';
4553 $this->state_id = 1;
4554 $this->state_code = 'AA';
4555 $this->state = 'MyState';
4556 $this->country_id = 1;
4557 $this->country_code = 'FR';
4558 $this->email = 'specimen@specimen.com';
4559 $this->socialnetworks = array(
4560 'skype' => 'skypepseudo',
4561 'twitter' => 'twitterpseudo',
4562 'facebook' => 'facebookpseudo',
4563 'linkedin' => 'linkedinpseudo',
4564 );
4565 $this->url = 'http://www.specimen.com';
4566
4567 $this->phone = '0909090901';
4568 $this->phone_mobile = '0909090901';
4569 $this->fax = '0909090909';
4570
4571 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4572 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4573 $this->capital = 10000;
4574 $this->client = 1;
4575 $this->prospect = 1;
4576 $this->fournisseur = 1;
4577 $this->tva_assuj = 1;
4578 $this->tva_intra = 'EU1234567';
4579 $this->note_public = 'This is a comment (public)';
4580 $this->note_private = 'This is a comment (private)';
4581
4582 $this->idprof1 = 'idprof1';
4583 $this->idprof2 = 'idprof2';
4584 $this->idprof3 = 'idprof3';
4585 $this->idprof4 = 'idprof4';
4586 $this->idprof5 = 'idprof5';
4587 $this->idprof6 = 'idprof6';
4588
4589 return 1;
4590 }
4591
4598 public function useLocalTax($localTaxNum = 0)
4599 {
4600 $sql = "SELECT t.localtax1, t.localtax2";
4601 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4602 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4603 $sql .= " AND t.active = 1";
4604 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4605 if (empty($localTaxNum)) {
4606 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4607 } elseif ($localTaxNum == 1) {
4608 $sql .= " AND t.localtax1_type <> '0'";
4609 } elseif ($localTaxNum == 2) {
4610 $sql .= " AND t.localtax2_type <> '0'";
4611 }
4612
4613 $resql = $this->db->query($sql);
4614 if ($resql) {
4615 return ($this->db->num_rows($resql) > 0);
4616 } else {
4617 return false;
4618 }
4619 }
4620
4626 public function useNPR()
4627 {
4628 $sql = "SELECT t.rowid";
4629 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4630 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4631 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4632 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4633
4634 dol_syslog("useNPR", LOG_DEBUG);
4635 $resql = $this->db->query($sql);
4636 if ($resql) {
4637 return ($this->db->num_rows($resql) > 0);
4638 } else {
4639 return false;
4640 }
4641 }
4642
4649 public function useRevenueStamp()
4650 {
4651 $sql = "SELECT COUNT(*) as nb";
4652 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4653 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4654 $sql .= " AND r.active = 1";
4655
4656 dol_syslog("useRevenueStamp", LOG_DEBUG);
4657 $resql = $this->db->query($sql);
4658 if ($resql) {
4659 $obj = $this->db->fetch_object($resql);
4660 return (($obj->nb > 0) ? true : false);
4661 } else {
4662 $this->error = $this->db->lasterror();
4663 return false;
4664 }
4665 }
4666
4672 public function getLibProspLevel()
4673 {
4674 return $this->LibProspLevel($this->fk_prospectlevel);
4675 }
4676
4677 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4684 public function LibProspLevel($fk_prospectlevel)
4685 {
4686 // phpcs:enable
4687 global $langs;
4688
4689 $label = '';
4690 if ($fk_prospectlevel != '') {
4691 $label = $langs->trans("ProspectLevel".$fk_prospectlevel);
4692 // If label is not found in language file, we get label from cache/database
4693 if ($label == "ProspectLevel".$fk_prospectlevel) {
4694 $label = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4695 }
4696 }
4697
4698 return $label;
4699 }
4700
4708 public function getLibProspCommStatut($mode = 0, $label = '')
4709 {
4710 return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4711 }
4712
4713 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4727 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4728 {
4729 // phpcs:enable
4730 global $langs;
4731
4732 $langs->load('customers');
4733
4734 if ($mode == 2) {
4735 if ($status == '-1' || $status == 'ST_NO') {
4736 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4737 } elseif ($status == '0' || $status == 'ST_NEVER') {
4738 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4739 } elseif ($status == '1' || $status == 'ST_TODO') {
4740 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4741 } elseif ($status == '2' || $status == 'ST_PEND') {
4742 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4743 } elseif ($status == '3' || $status == 'ST_DONE') {
4744 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4745 } else {
4746 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);
4747 }
4748 } elseif ($mode == 3) {
4749 if ($status == '-1' || $status == 'ST_NO') {
4750 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"');
4751 } elseif ($status == '0' || $status == 'ST_NEVER') {
4752 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"');
4753 } elseif ($status == '1' || $status == 'ST_TODO') {
4754 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"');
4755 } elseif ($status == '2' || $status == 'ST_PEND') {
4756 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"');
4757 } elseif ($status == '3' || $status == 'ST_DONE') {
4758 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"');
4759 } else {
4760 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"');
4761 }
4762 } elseif ($mode == 4) {
4763 if ($status == '-1' || $status == 'ST_NO') {
4764 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4765 } elseif ($status == '0' || $status == 'ST_NEVER') {
4766 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4767 } elseif ($status == '1' || $status == 'ST_TODO') {
4768 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4769 } elseif ($status == '2' || $status == 'ST_PEND') {
4770 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4771 } elseif ($status == '3' || $status == 'ST_DONE') {
4772 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4773 } else {
4774 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);
4775 }
4776 }
4777
4778 return "Error, mode/status not found";
4779 }
4780
4787 public function getOutstandingProposals($mode = 'customer')
4788 {
4789 $table = 'propal';
4790 if ($mode == 'supplier') {
4791 $table = 'supplier_proposal';
4792 }
4793
4794 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4795 $sql .= " WHERE fk_soc = ".((int) $this->id);
4796 if ($mode == 'supplier') {
4797 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4798 } else {
4799 $sql .= " AND entity IN (".getEntity('propal').")";
4800 }
4801
4802 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4803
4804 $resql = $this->db->query($sql);
4805 if ($resql) {
4806 $outstandingOpened = 0;
4807 $outstandingTotal = 0;
4808 $outstandingTotalIncTax = 0;
4809 $arrayofref = array();
4810 while ($obj = $this->db->fetch_object($resql)) {
4811 $arrayofref[$obj->rowid] = $obj->ref;
4812 $outstandingTotal += $obj->total_ht;
4813 $outstandingTotalIncTax += $obj->total_ttc;
4814 if ($obj->status != 0) {
4815 // Not a draft
4816 $outstandingOpened += $obj->total_ttc;
4817 }
4818 }
4819 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4820 } else {
4821 return array();
4822 }
4823 }
4824
4831 public function getOutstandingOrders($mode = 'customer')
4832 {
4833 $table = 'commande';
4834 if ($mode == 'supplier') {
4835 $table = 'commande_fournisseur';
4836 }
4837
4838 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4839 $sql .= " WHERE fk_soc = ".((int) $this->id);
4840 if ($mode == 'supplier') {
4841 $sql .= " AND entity IN (".getEntity('supplier_order').")";
4842 } else {
4843 $sql .= " AND entity IN (".getEntity('commande').")";
4844 }
4845
4846 dol_syslog("getOutstandingOrders", LOG_DEBUG);
4847 $resql = $this->db->query($sql);
4848 if ($resql) {
4849 $outstandingOpened = 0;
4850 $outstandingTotal = 0;
4851 $outstandingTotalIncTax = 0;
4852 $arrayofref = array();
4853 while ($obj = $this->db->fetch_object($resql)) {
4854 $arrayofref[$obj->rowid] = $obj->ref;
4855 $outstandingTotal += $obj->total_ht;
4856 $outstandingTotalIncTax += $obj->total_ttc;
4857 if ($obj->status != 0) {
4858 // Not a draft
4859 $outstandingOpened += $obj->total_ttc;
4860 }
4861 }
4862 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref); // 'opened' is 'incl taxes'
4863 } else {
4864 return array();
4865 }
4866 }
4867
4875 public function getOutstandingBills($mode = 'customer', $late = 0)
4876 {
4877 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
4878
4879 $table = 'facture';
4880 if ($mode == 'supplier') {
4881 $table = 'facture_fourn';
4882 }
4883
4884 /* Accurate value of remain to pay is to sum remaintopay for each invoice
4885 $paiement = $invoice->getSommePaiement();
4886 $creditnotes=$invoice->getSumCreditNotesUsed();
4887 $deposits=$invoice->getSumDepositsUsed();
4888 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4889 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4890 */
4891 $today = dol_get_first_hour(dol_now('tzuser')); // Returns today at 00:00 in the user's time zone
4892
4893 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4894 $sql .= " WHERE fk_soc = ".((int) $this->id);
4895 if (!empty($late)) {
4896 $sql .= " AND date_lim_reglement < '".$this->db->idate($today)."'";
4897 }
4898 if ($mode == 'supplier') {
4899 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4900 } else {
4901 $sql .= " AND entity IN (".getEntity('invoice').")";
4902 }
4903
4904 dol_syslog("getOutstandingBills", LOG_DEBUG);
4905 $resql = $this->db->query($sql);
4906 if ($resql) {
4907 $outstandingOpened = 0;
4908 $outstandingTotal = 0;
4909 $outstandingTotalIncTax = 0;
4910 $arrayofref = array();
4911 $arrayofrefopened = array();
4912 if ($mode == 'supplier') {
4913 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4914 $tmpobject = new FactureFournisseur($this->db);
4915 } else {
4916 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4917 $tmpobject = new Facture($this->db);
4918 }
4919 while ($obj = $this->db->fetch_object($resql)) {
4920 $arrayofref[$obj->rowid] = $obj->ref;
4921 $tmpobject->id = $obj->rowid;
4922
4923 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4924 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4925 ) {
4926 $outstandingTotal += $obj->total_ht;
4927 $outstandingTotalIncTax += $obj->total_ttc;
4928 }
4929
4930 $remaintopay = 0;
4931
4932 if ($obj->paye == 0
4933 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4934 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandoned
4935 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4936 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandoned for undefined reason
4937 $paiement = $tmpobject->getSommePaiement();
4938 $creditnotes = $tmpobject->getSumCreditNotesUsed();
4939 $deposits = $tmpobject->getSumDepositsUsed();
4940
4941 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4942 $outstandingOpened += $remaintopay;
4943 }
4944
4945 //if credit note is converted but not used
4946 // TODO Do this also for customer ?
4947 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4948 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4949 $remaintopay -= $remainingcreditnote;
4950 $outstandingOpened -= $remainingcreditnote;
4951 }
4952
4953 if ($remaintopay) {
4954 $arrayofrefopened[$obj->rowid] = $obj->ref;
4955 }
4956 }
4957 return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax, 'refs' => $arrayofref, 'refsopened' => $arrayofrefopened); // 'opened' is 'incl taxes'
4958 } else {
4959 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4960 return array();
4961 }
4962 }
4963
4970 public function getLibCustProspStatut()
4971 {
4972 return $this->LibCustProspStatut($this->client);
4973 }
4974
4975 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4982 public function LibCustProspStatut($status)
4983 {
4984 // phpcs:enable
4985 global $langs;
4986 $langs->load('companies');
4987
4988 if ($status == 0) {
4989 return $langs->trans("NorProspectNorCustomer");
4990 } elseif ($status == 1) {
4991 return $langs->trans("Customer");
4992 } elseif ($status == 2) {
4993 return $langs->trans("Prospect");
4994 } elseif ($status == 3) {
4995 return $langs->trans("ProspectCustomer");
4996 }
4997
4998 return '';
4999 }
5000
5001
5013 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5014 {
5015 global $langs;
5016
5017 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5018 $modelpath = "core/modules/bank/doc/";
5019
5020 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5021 $companybankaccount = new CompanyBankAccount($this->db);
5022 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5023 if (!$result) {
5024 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5025 }
5026 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5027 $this->last_main_doc = $companybankaccount->last_main_doc;
5028 } else {
5029 // Positionne le modele sur le nom du modele a utiliser
5030 if (!dol_strlen($modele)) {
5031 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5032 $modele = getDolGlobalString('COMPANY_ADDON_PDF');
5033 } else {
5034 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5035 return 0;
5036 }
5037 }
5038
5039 if (!isset($this->bank_account)) {
5040 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5041 $bac = new CompanyBankAccount($this->db);
5042 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
5043 $result = $bac->fetch(0, '', $this->id);
5044 if ($result > 0) {
5045 $this->bank_account = $bac;
5046 } else {
5047 $this->bank_account = '';
5048 }
5049 }
5050
5051 $modelpath = "core/modules/societe/doc/";
5052
5053 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5054 }
5055
5056 return $result;
5057 }
5058
5059
5071 public function setCategories($categories, $type_categ)
5072 {
5073 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5074
5075 // Decode type
5076 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5077 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5078 return -1;
5079 }
5080
5081 return parent::setCategoriesCommon($categories, $type_categ);
5082 }
5083
5091 public function setSalesRep($salesrep, $onlyAdd = false)
5092 {
5093 global $user;
5094
5095 // Handle single user
5096 if (!is_array($salesrep)) {
5097 $salesrep = array($salesrep);
5098 }
5099
5100 $to_del = array(); // Nothing to delete
5101 $to_add = $salesrep;
5102 if ($onlyAdd === false) {
5103 // Get current users
5104 $existing = $this->getSalesRepresentatives($user, 1);
5105
5106 // Diff
5107 if (is_array($existing)) {
5108 $to_del = array_diff($existing, $salesrep);
5109 $to_add = array_diff($salesrep, $existing);
5110 }
5111 }
5112
5113 $error = 0;
5114
5115 // Process
5116 foreach ($to_del as $del) {
5117 $this->del_commercial($user, $del);
5118 }
5119 foreach ($to_add as $add) {
5120 $result = $this->add_commercial($user, $add);
5121 if ($result < 0) {
5122 $error++;
5123 break;
5124 }
5125 }
5126
5127 return $error ? -1 : 1;
5128 }
5129
5136 public function setThirdpartyType($typent_id)
5137 {
5138 global $user;
5139
5140 dol_syslog(__METHOD__, LOG_DEBUG);
5141
5142 if ($this->id) {
5143 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5144
5145 if ($result > 0) {
5146 $this->typent_id = $typent_id;
5147 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5148 return 1;
5149 } else {
5150 return -1;
5151 }
5152 } else {
5153 return -1;
5154 }
5155 }
5156
5166 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5167 {
5168 if ($origin_id == $dest_id) {
5169 dol_syslog('Error: Try to merge a thirdparty into itself');
5170 return false;
5171 }
5172
5173 // 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.
5174 // Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
5175 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5176 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5177 $sql .= ' SELECT fk_user ';
5178 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5179 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5180
5181 $resql = $dbs->query($sql);
5182 while ($obj = $dbs->fetch_object($resql)) {
5183 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5184 }
5185
5186 // llx_societe_extrafields table must not be here because we don't care about the old thirdparty extrafields that are managed directly into mergeCompany.
5187 // Do not include llx_societe because it will be replaced later.
5188 $tables = array(
5189 'societe_account',
5190 'societe_commerciaux',
5191 'societe_prices',
5192 'societe_remise',
5193 'societe_remise_except',
5194 'societe_rib'
5195 );
5196
5197 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5198 }
5199
5208 public function setAccountancyCode($type, $value)
5209 {
5210 global $user, $langs, $conf;
5211
5212 $this->db->begin();
5213
5214 if ($type == 'buy') {
5215 $field = 'accountancy_code_buy';
5216 } elseif ($type == 'sell') {
5217 $field = 'accountancy_code_sell';
5218 } else {
5219 return -1;
5220 }
5221
5222 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5223 $sql .= $field." = '".$this->db->escape($value)."'";
5224 $sql .= " WHERE rowid = ".((int) $this->id);
5225
5226 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5227 $resql = $this->db->query($sql);
5228
5229 if ($resql) {
5230 // Call triggers
5231 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5232 $interface = new Interfaces($this->db);
5233 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5234 if ($result < 0) {
5235 $this->errors = $interface->errors;
5236 $this->db->rollback();
5237 return -1;
5238 }
5239 // End call triggers
5240
5241 $this->$field = $value;
5242
5243 $this->db->commit();
5244 return 1;
5245 } else {
5246 $this->error = $this->db->lasterror();
5247 $this->db->rollback();
5248 return -1;
5249 }
5250 }
5251
5258 public function fetchPartnerships($mode)
5259 {
5260 global $langs;
5261
5262 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5263
5264
5265 $this->partnerships[] = array();
5266
5267 return 1;
5268 }
5269
5277 public function getKanbanView($option = '', $arraydata = array())
5278 {
5279 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5280
5281 $return = '<div class="box-flex-item box-flex-grow-zero">';
5282 $return .= '<div class="info-box info-box-sm">';
5283 $return .= '<span class="info-box-icon bg-infobox-action">';
5284 $return .= img_picto('', $this->picto);
5285 $return .= '</span>';
5286 $return .= '<div class="info-box-content">';
5287 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
5288 if ($selected >= 0) {
5289 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5290 }
5291 if (property_exists($this, 'code_client')) {
5292 $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5293 }
5294 if (method_exists($this, 'getLibStatut')) {
5295 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5296 }
5297 $return .= '</div>';
5298 $return .= '</div>';
5299 $return .= '</div>';
5300
5301 return $return;
5302 }
5303
5313 public function getContacts($list = 0, $code = '', $element = '')
5314 {
5315 // phpcs:enable
5316 global $langs;
5317
5318 $tab = array();
5319
5320 $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
5321 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5322 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5323 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5324 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5325 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5326 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5327 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5328 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5329 if (!empty($element)) {
5330 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5331 }
5332 if ($code) {
5333 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5334 }
5335 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5336 $sql .= " AND tc.source = 'external'";
5337 $sql .= " AND tc.active = 1";
5338
5339 $sql .= " ORDER BY t.lastname ASC";
5340
5341 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5342 $resql = $this->db->query($sql);
5343 if ($resql) {
5344 $num = $this->db->num_rows($resql);
5345 $i = 0;
5346 while ($i < $num) {
5347 $obj = $this->db->fetch_object($resql);
5348
5349 if (!$list) {
5350 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5351 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5352 $tab[$i] = array(
5353 'source' => $obj->source,
5354 'socid' => $obj->socid,
5355 'id' => $obj->id,
5356 'nom' => $obj->lastname, // For backward compatibility
5357 'civility' => $obj->civility,
5358 'lastname' => $obj->lastname,
5359 'firstname' => $obj->firstname,
5360 'email' => $obj->email,
5361 'login' => (empty($obj->login) ? '' : $obj->login),
5362 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5363 'statuscontact' => $obj->statuscontact,
5364 'rowid' => $obj->rowid,
5365 'code' => $obj->code,
5366 'element' => $obj->element,
5367 'libelle' => $libelle_type,
5368 'status' => $obj->statuslink,
5369 'fk_c_type_contact' => $obj->fk_c_type_contact
5370 );
5371 } else {
5372 $tab[$i] = $obj->id;
5373 }
5374
5375 $i++;
5376 }
5377
5378 return $tab;
5379 } else {
5380 $this->error = $this->db->lasterror();
5381 dol_print_error($this->db);
5382 return -1;
5383 }
5384 }
5385
5396 public function mergeCompany($soc_origin_id)
5397 {
5398 global $conf, $langs, $hookmanager, $user, $action;
5399
5400 $error = 0;
5401 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5402
5403 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5404
5405 if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5406 $this->error = $langs->trans('ErrorRecordNotFound');
5407 $error++;
5408 }
5409
5410 if (!$error) {
5411 $this->db->begin();
5412
5413 // Recopy some data
5414 $this->client |= $soc_origin->client;
5415 $this->fournisseur |= $soc_origin->fournisseur;
5416 $listofproperties = array(
5417 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_mobile', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5418 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5419 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5420 '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',
5421 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5422 'model_pdf', 'webservices_url', 'webservices_key', 'accountancy_code_sell', 'accountancy_code_buy', 'typent_id'
5423 );
5424 foreach ($listofproperties as $property) {
5425 if (empty($this->$property)) {
5426 $this->$property = $soc_origin->$property;
5427 }
5428 }
5429
5430 if ($this->typent_id == -1) {
5431 $this->typent_id = $soc_origin->typent_id;
5432 }
5433
5434 // Concat some data
5435 $listofproperties = array(
5436 'note_public', 'note_private'
5437 );
5438 foreach ($listofproperties as $property) {
5439 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5440 }
5441
5442 // Merge extrafields
5443 if (is_array($soc_origin->array_options)) {
5444 foreach ($soc_origin->array_options as $key => $val) {
5445 if (empty($this->array_options[$key])) {
5446 $this->array_options[$key] = $val;
5447 }
5448 }
5449 }
5450
5451 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5452 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5453 $this->name_bis = $this->name;
5454 }
5455
5456 // Merge categories
5457 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5458 $static_cat = new Categorie($this->db);
5459
5460 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5461 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5462 $custcats = array_merge($custcats, $custcats_ori);
5463 $this->setCategories($custcats, 'customer');
5464
5465 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5466 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5467 $suppcats = array_merge($suppcats, $suppcats_ori);
5468 $this->setCategories($suppcats, 'supplier');
5469
5470 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5471 if ($soc_origin->code_client == $this->code_client
5472 || $soc_origin->code_fournisseur == $this->code_fournisseur
5473 || $soc_origin->barcode == $this->barcode) {
5474 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5475 $soc_origin->code_client = '';
5476 $soc_origin->code_fournisseur = '';
5477 $soc_origin->barcode = '';
5478 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5479 }
5480
5481 // Update
5482 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5483
5484 if ($result < 0) {
5485 $error++;
5486 }
5487
5488 // Move links
5489 if (!$error) {
5490 $objects = array(
5491 'Adherent' => '/adherents/class/adherent.class.php',
5492 //'Categorie' => '/categories/class/categorie.class.php', // Already processed previously
5493 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5494 'Propal' => '/comm/propal/class/propal.class.php',
5495 'Commande' => '/commande/class/commande.class.php',
5496 'Facture' => '/compta/facture/class/facture.class.php',
5497 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5498 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5499 'Contact' => '/contact/class/contact.class.php',
5500 'Contrat' => '/contrat/class/contrat.class.php',
5501 'Expedition' => '/expedition/class/expedition.class.php',
5502 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5503 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5504 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5505 'Reception' => '/reception/class/reception.class.php',
5506 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5507 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5508 'Product' => '/product/class/product.class.php',
5509 //'ProductThirparty' => '...', // for llx_product_thirdparty
5510 'Project' => '/projet/class/project.class.php',
5511 'User' => '/user/class/user.class.php',
5512 'Account' => '/compta/bank/class/account.class.php',
5513 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php',
5514 'Societe' => '/societe/class/societe.class.php',
5515 //'SocieteAccount', 'SocietePrice', 'SocieteRib',... are processed into the replaceThirparty of Societe.
5516 );
5517 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'delivery')) {
5518 $objects['Delivery'] = '/delivery/class/delivery.class.php';
5519 }
5520 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'mrp_mo')) {
5521 $objects['Mo'] = '/mrp/class/mo.class.php';
5522 }
5523 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'don')) {
5524 $objects['Don'] = '/don/class/don.class.php';
5525 }
5526 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'partnership')) {
5527 $objects['PartnerShip'] = '/partnership/class/partnership.class.php';
5528 }
5529 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'fichinter')) {
5530 $objects['Fichinter'] = '/fichinter/class/fichinter.class.php';
5531 }
5532 if ($this->db->DDLListTables($conf->db->name, $this->db->prefix().'ticket')) {
5533 $objects['Ticket'] = '/ticket/class/ticket.class.php';
5534 }
5535
5536 //First, all core objects must update their tables
5537 foreach ($objects as $object_name => $object_file) {
5538 if (is_array($object_file)) {
5539 if (empty($object_file['enabled'])) {
5540 continue;
5541 }
5542 $object_file = $object_file['file'];
5543 }
5544
5545 require_once DOL_DOCUMENT_ROOT.$object_file;
5546
5547 if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5548 $error++;
5549 $this->error = $this->db->lasterror();
5550 break;
5551 }
5552 }
5553 }
5554
5555 // External modules should update their ones too
5556 if (!$error) {
5557 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5558 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5559
5560 if ($reshook < 0) {
5561 $this->error = $hookmanager->error;
5562 $this->errors = $hookmanager->errors;
5563 $error++;
5564 }
5565 }
5566
5567
5568 if (!$error) {
5569 $this->context = array('merge' => 1, 'mergefromid' => $soc_origin->id, 'mergefromname' => $soc_origin->name);
5570
5571 // Call trigger
5572 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5573 if ($result < 0) {
5574 $error++;
5575 }
5576 // End call triggers
5577 }
5578
5579 if (!$error) {
5580 // Move files from the dir of the third party to delete into the dir of the third party to keep
5581 if (!empty($conf->societe->multidir_output[$this->entity])) {
5582 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5583 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5584
5585 if (dol_is_dir($srcdir)) {
5586 $dirlist = dol_dir_list($srcdir, 'files', 1);
5587 foreach ($dirlist as $filetomove) {
5588 $destfile = $destdir.'/'.$filetomove['relativename'];
5589 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5590 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5591 }
5592 //exit;
5593 }
5594 }
5595 }
5596
5597
5598 if (!$error) {
5599 // We finally remove the old thirdparty
5600 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5601 $this->error = $soc_origin->error;
5602 $this->errors = $soc_origin->errors;
5603 $error++;
5604 }
5605 }
5606
5607 if (!$error) {
5608 $this->db->commit();
5609 return 0;
5610 } else {
5611 $langs->load("errors");
5612 $this->error = $langs->trans('ErrorsThirdpartyMerge');
5613 $this->db->rollback();
5614 return -1;
5615 }
5616 }
5617
5618 return -1;
5619 }
5620}
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:637
$object ref
Definition info.php:79
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.
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.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate 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()
Returns 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.
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 clicable link of object (with eventually picto)
const SUPPLIER
Third party supplier flag is a supplier.
check_codefournisseur()
Check supplier code.
contact_array()
Returns 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.
trait CommonIncoterm
Superclass for incoterm classes.
trait CommonPeople
Support class for thirdparties, contacts, members, users or resources.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
trait CommonSocialNetworks
Superclass for social networks.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:655
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='')
Format phone numbers according to country.
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_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)
Set event message in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
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 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...
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
isValidSiren($siren)
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:140