dolibarr 19.0.4
societe.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5 * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2013-2023 Alexandre Spangaro <aspangaro@open-dsi.fr>
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-2023 Frédéric France <frederic.france@netlogic.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 *
23 * This program is free software; you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation; either version 3 of the License, or
26 * (at your option) any later version.
27 *
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
32 *
33 * You should have received a copy of the GNU General Public License
34 * along with this program. If not, see <https://www.gnu.org/licenses/>.
35 */
36
42require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
43require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
46require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
47
48
52class Societe extends CommonObject
53{
56 use CommonPeople;
57
61 public $module = 'societe';
62
66 public $element = 'societe';
67
71 public $table_element = 'societe';
72
76 public $fk_element = 'fk_soc';
77
81 public $fieldsforcombobox = 'nom,name_alias';
82
86 protected $childtables = array(
87 'supplier_proposal' => array('name' => 'SupplierProposal'),
88 'propal' => array('name' => 'Proposal'),
89 'commande' => array('name' => 'Order'),
90 'facture' => array('name' => 'Invoice'),
91 'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
92 'contrat' => array('name' => 'Contract'),
93 'fichinter' => array('name' => 'Fichinter'),
94 'facture_fourn' => array('name' => 'SupplierInvoice'),
95 'commande_fournisseur' => array('name' => 'SupplierOrder'),
96 'projet' => array('name' => 'Project'),
97 'expedition' => array('name' => 'Shipment'),
98 'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
99 );
100
105 protected $childtablesoncascade = array(
106 'societe_prices',
107 'product_fournisseur_price',
108 'product_customer_price_log',
109 'product_customer_price',
110 '@Contact:/contact/class/contact.class.php:fk_soc',
111 'adherent',
112 'societe_account',
113 'societe_rib',
114 'societe_remise',
115 'societe_remise_except',
116 'societe_commerciaux',
117 'categorie',
118 'notify',
119 'notify_def',
120 'actioncomm',
121 );
122
126 public $picto = 'company';
127
132 public $ismultientitymanaged = 1;
133
137 public $isextrafieldmanaged = 1;
138
143 public $restrictiononfksoc = 1;
144
148 public $oldcopy;
149
154 public $SupplierCategories = array();
155
160 public $prefixCustomerIsRequired;
161
191 public $fields = array(
192 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'),
193 'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
194 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
195 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
196 'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35, 'showoncombobox'=>1),
197 'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36, 'showoncombobox'=>2),
198 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1),
199 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>45),
200 'code_client' =>array('type'=>'varchar(24)', 'label'=>'CustomerCode', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
201 'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierCode', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
202 'code_compta' =>array('type'=>'varchar(24)', 'label'=>'CustomerAccountancyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
203 'code_compta_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierAccountancyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
204 'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
205 'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
206 'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
207 'fk_departement' =>array('type'=>'integer', 'label'=>'State', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
208 'fk_pays' =>array('type'=>'integer:Ccountry:core/class/ccountry.class.php', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
209 'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
210 'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
211 'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
212 'email' =>array('type'=>'varchar(128)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
213 'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
214 'fk_effectif' =>array('type'=>'integer', 'label'=>'Workforce', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
215 'fk_typent' =>array('type'=>'integer', 'label'=>'TypeOfCompany', 'enabled'=>1, 'visible'=>-1, 'position'=>175, 'csslist'=>'minwidth200'),
216 'fk_forme_juridique' =>array('type'=>'integer', 'label'=>'JuridicalStatus', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
217 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
218 'siren' =>array('type'=>'varchar(128)', 'label'=>'Idprof1', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
219 'siret' =>array('type'=>'varchar(128)', 'label'=>'Idprof2', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
220 'ape' =>array('type'=>'varchar(128)', 'label'=>'Idprof3', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
221 'idprof4' =>array('type'=>'varchar(128)', 'label'=>'Idprof4', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
222 'idprof5' =>array('type'=>'varchar(128)', 'label'=>'Idprof5', 'enabled'=>1, 'visible'=>-1, 'position'=>206),
223 'idprof6' =>array('type'=>'varchar(128)', 'label'=>'Idprof6', 'enabled'=>1, 'visible'=>-1, 'position'=>207),
224 'tva_intra' =>array('type'=>'varchar(20)', 'label'=>'Tva intra', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
225 'capital' =>array('type'=>'double(24,8)', 'label'=>'Capital', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
226 'fk_stcomm' =>array('type'=>'integer', 'label'=>'CommercialStatus', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
227 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>225),
228 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>230),
229 'prefix_comm' =>array('type'=>'varchar(5)', 'label'=>'Prefix comm', 'enabled'=>"getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible'=>-1, 'position'=>235),
230 'client' =>array('type'=>'tinyint(4)', 'label'=>'Client', 'enabled'=>1, 'visible'=>-1, 'position'=>240),
231 'fournisseur' =>array('type'=>'tinyint(4)', 'label'=>'Fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>245),
232 'supplier_account' =>array('type'=>'varchar(32)', 'label'=>'Supplier account', 'enabled'=>1, 'visible'=>-1, 'position'=>250),
233 'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
234 'customer_bad' =>array('type'=>'tinyint(4)', 'label'=>'Customer bad', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
235 'customer_rate' =>array('type'=>'double', 'label'=>'Customer rate', 'enabled'=>1, 'visible'=>-1, 'position'=>265),
236 'supplier_rate' =>array('type'=>'double', 'label'=>'Supplier rate', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
237 'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>275),
238 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>280),
239 //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
240 //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
241 'mode_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>295),
242 'cond_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
243 'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>301),
244 'mode_reglement_supplier' =>array('type'=>'integer', 'label'=>'Mode reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
245 'cond_reglement_supplier' =>array('type'=>'integer', 'label'=>'Cond reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>308),
246 'outstanding_limit' =>array('type'=>'double(24,8)', 'label'=>'OutstandingBill', 'enabled'=>1, 'visible'=>-1, 'position'=>310, 'isameasure'=>1),
247 'order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Order min amount', 'enabled'=>'isModEnabled("commande") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>315, 'isameasure'=>1),
248 'supplier_order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Supplier order min amount', 'enabled'=>'isModEnabled("commande") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>320, 'isameasure'=>1),
249 'fk_shipping_method' =>array('type'=>'integer', 'label'=>'Fk shipping method', 'enabled'=>1, 'visible'=>-1, 'position'=>330),
250 'tva_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Tva assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
251 'localtax1_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax1 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>340),
252 'localtax1_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax1 value', 'enabled'=>1, 'visible'=>-1, 'position'=>345),
253 'localtax2_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax2 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>350),
254 'localtax2_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax2 value', 'enabled'=>1, 'visible'=>-1, 'position'=>355),
255 'vat_reverse_charge' =>array('type'=>'tinyint(4)', 'label'=>'Vat reverse charge', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
256 'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>1, 'visible'=>-1, 'position'=>360),
257 'price_level' =>array('type'=>'integer', 'label'=>'Price level', 'enabled'=>'$conf->global->PRODUIT_MULTIPRICES || $conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES', 'visible'=>-1, 'position'=>365),
258 'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>370),
259 'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>375),
260 'fk_barcode_type' =>array('type'=>'integer', 'label'=>'Fk barcode type', 'enabled'=>1, 'visible'=>-1, 'position'=>405),
261 'webservices_url' =>array('type'=>'varchar(255)', 'label'=>'Webservices url', 'enabled'=>1, 'visible'=>-1, 'position'=>410),
262 'webservices_key' =>array('type'=>'varchar(128)', 'label'=>'Webservices key', 'enabled'=>1, 'visible'=>-1, 'position'=>415),
263 'fk_incoterms' =>array('type'=>'integer', 'label'=>'Fk incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>425),
264 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'Location incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>430),
265 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>435),
266 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
267 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>440),
268 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>445),
269 'fk_account' =>array('type'=>'integer', 'label'=>'PaymentBankAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>450),
270 'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>455),
271 'logo' =>array('type'=>'varchar(255)', 'label'=>'Logo', 'enabled'=>1, 'visible'=>-1, 'position'=>400),
272 'logo_squarred' =>array('type'=>'varchar(255)', 'label'=>'Logo squarred', 'enabled'=>1, 'visible'=>-1, 'position'=>401),
273 'status' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
274 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
275 );
276
280 public $entity;
281
288 public $nom;
289
293 public $name;
294
299 public $name_alias;
300
304 public $particulier;
305
310 public $status = 1;
311
316 public $region_code;
317
321 public $region;
322
326 public $country_id;
327
333 public $departement_code;
334
340 public $departement;
341
347 public $pays;
348
353 public $phone;
358 public $fax;
359
364 public $email;
365
370 public $no_email;
371
377 public $skype;
378
384 public $twitter;
385
391 public $facebook;
392
398 public $linkedin;
399
404 public $url;
405
410 public $barcode;
411
412 // 6 professional id (usage depends on country)
413
418 public $idprof1;
419
425 public $siren;
426
427
432 public $idprof2;
433
439 public $siret;
440
445 public $idprof3;
446
452 public $ape;
453
458 public $idprof4;
459
464 public $idprof5;
465
470 public $idprof6;
471
476 public $socialobject;
477
481 public $prefix_comm;
482
486 public $tva_assuj = 1;
487
492 public $tva_intra;
493
497 public $vat_reverse_charge = 0;
498
499 // Local taxes
500 public $localtax1_assuj;
501 public $localtax1_value;
502 public $localtax2_assuj;
503 public $localtax2_value;
504
508 public $managers;
509
513 public $capital;
514
518 public $typent_id = 0;
519 public $typent_code;
520 public $effectif;
521 public $effectif_id = 0;
522 public $forme_juridique_code;
523 public $forme_juridique = 0;
524
525 public $remise_percent;
526 public $remise_supplier_percent;
527
528 public $mode_reglement_id;
529 public $cond_reglement_id;
530 public $deposit_percent;
531 public $mode_reglement_supplier_id;
532 public $cond_reglement_supplier_id;
533 public $transport_mode_supplier_id;
534
538 public $fk_prospectlevel;
539
543 public $name_bis;
544
545 //Log data
546
551 public $date_modification;
552
558 public $user_modification;
559
564 public $date_creation;
565
571 public $user_creation;
572
577 public $client = 0;
578
583 public $prospect = 0;
584
589 public $fournisseur;
590
595 public $code_client;
596
601 public $code_fournisseur;
602
607 public $code_compta_client;
608
615 public $code_compta;
616
621 public $accountancy_code_customer;
622
627 public $code_compta_fournisseur;
628
633 public $accountancy_code_supplier;
634
639 public $code_compta_product;
640
646 public $note;
647
652 public $note_private;
653
658 public $note_public;
659
664 public $stcomm_id;
665
670 public $stcomm_picto;
671
676 public $status_prospect_label;
677
682 public $price_level;
683
687 public $outstanding_limit;
688
692 public $order_min_amount;
693
697 public $supplier_order_min_amount;
698
703 public $commercial_id;
704
709 public $parent;
710
715 public $default_lang;
716
720 public $ref;
721
727 public $ref_ext;
728
735 public $import_key;
736
741 public $webservices_url;
742
747 public $webservices_key;
748
752 public $logo;
753
757 public $logo_small;
758
762 public $logo_mini;
763
767 public $logo_squarred;
768
772 public $logo_squarred_small;
773
777 public $logo_squarred_mini;
778
782 public $accountancy_code_sell;
783
787 public $accountancy_code_buy;
788
789 // Multicurrency
793 public $fk_multicurrency;
794
795 // Warehouse
799 public $fk_warehouse;
800
804 public $multicurrency_code;
805
806 // Fields loaded by fetchPartnerships()
807
808 public $partnerships = array();
809
810
814 public $bank_account;
815
816
817 const STATUS_CEASED = 0;
818 const STATUS_INACTIVITY = 1;
819
823 const NO_CUSTOMER = 0;
824
828 const CUSTOMER = 1;
829
833 const PROSPECT = 2;
834
839
843 const NO_SUPPLIER = 0;
844
848 const SUPPLIER = 1;
849
850
856 public function __construct($db)
857 {
858 global $conf;
859
860 $this->db = $db;
861
862 $this->client = 0;
863 $this->prospect = 0;
864 $this->fournisseur = 0;
865 $this->typent_id = 0;
866 $this->effectif_id = 0;
867 $this->forme_juridique_code = 0;
868 $this->tva_assuj = 1;
869 $this->vat_reverse_charge = 0;
870 $this->status = 1;
871
872 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
873 $this->fields['address']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
874 $this->fields['zip']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
875 $this->fields['town']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
876 //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
877 }
878 }
879
880
889 public function create(User $user, $notrigger = 0)
890 {
891 global $langs, $conf;
892
893 $error = 0;
894
895 // Clean parameters
896 if (empty($this->status)) {
897 $this->status = 0;
898 }
899 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
900 $this->setUpperOrLowerCase();
901 $this->nom = $this->name; // For backward compatibility
902
903 if (empty($this->client)) {
904 $this->client = 0;
905 }
906 if (empty($this->fournisseur)) {
907 $this->fournisseur = 0;
908 }
909 $this->import_key = trim((string) $this->import_key);
910
911 $this->accountancy_code_customer = trim((string) $this->code_compta);
912 $this->accountancy_code_supplier = trim((string) $this->code_compta_fournisseur);
913 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
914 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
915
916 if (!empty($this->multicurrency_code)) {
917 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
918 }
919 if (empty($this->fk_multicurrency)) {
920 $this->multicurrency_code = '';
921 $this->fk_multicurrency = 0;
922 }
923
924 dol_syslog(get_class($this)."::create ".$this->name);
925
926 $now = dol_now();
927
928 $this->db->begin();
929
930 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
931 if ($this->code_client == -1 || $this->code_client === 'auto') {
932 $this->get_codeclient($this, 0);
933 }
934 if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
935 $this->get_codefournisseur($this, 1);
936 }
937
938 // Check more parameters (including mandatory setup
939 // If error, this->errors[] is filled
940 $result = $this->verify();
941
942 if ($result >= 0) {
943 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
944
945 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
946 $sql .= "nom";
947 $sql .= ", name_alias";
948 $sql .= ", entity";
949 $sql .= ", datec";
950 $sql .= ", fk_user_creat";
951 $sql .= ", fk_typent";
952 $sql .= ", canvas";
953 $sql .= ", status";
954 $sql .= ", ref_ext";
955 $sql .= ", fk_stcomm";
956 $sql .= ", fk_incoterms";
957 $sql .= ", location_incoterms";
958 $sql .= ", import_key";
959 $sql .= ", fk_multicurrency";
960 $sql .= ", multicurrency_code";
961 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
962 $sql .= ", vat_reverse_charge";
963 $sql .= ", accountancy_code_buy";
964 $sql .= ", accountancy_code_sell";
965 }
966 $sql .= ") VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".((int) $this->entity).", '".$this->db->idate($now)."'";
967 $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
968 $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
969 $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
970 $sql .= ", ".((int) $this->status);
971 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
972 $sql .= ", 0";
973 $sql .= ", ".(int) $this->fk_incoterms;
974 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
975 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
976 $sql .= ", ".(int) $this->fk_multicurrency;
977 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
978 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
979 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
980 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
981 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
982 }
983 $sql .= ")";
984
985 dol_syslog(get_class($this)."::create", LOG_DEBUG);
986 $result = $this->db->query($sql);
987 if ($result) {
988 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
989
990 $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
991
992 // update accountancy for this entity
993 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
994 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
995
996 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
997 $sql .= " fk_soc";
998 $sql .= ", entity";
999 $sql .= ", vat_reverse_charge";
1000 $sql .= ", accountancy_code_customer";
1001 $sql .= ", accountancy_code_supplier";
1002 $sql .= ", accountancy_code_buy";
1003 $sql .= ", accountancy_code_sell";
1004 $sql .= ") VALUES (";
1005 $sql .= $this->id;
1006 $sql .= ", ".((int) $conf->entity);
1007 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1008 $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
1009 $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
1010 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1011 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1012 $sql .= ")";
1013 $result = $this->db->query($sql);
1014 if (!$result) {
1015 $error++;
1016 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1017 }
1018 }
1019
1020 // Ajout du commercial affecte
1021 if ($this->commercial_id != '' && $this->commercial_id != -1) {
1022 $this->add_commercial($user, $this->commercial_id);
1023 } elseif (!$user->hasRight('societe', 'client', 'voir')) {
1024 // si un commercial cree un client il lui est affecte automatiquement
1025 $this->add_commercial($user, $user->id);
1026 }
1027
1028 if ($ret >= 0) {
1029 if (! $notrigger) {
1030 // Call trigger
1031 $result = $this->call_trigger('COMPANY_CREATE', $user);
1032 if ($result < 0) {
1033 $error++;
1034 }
1035 // End call triggers
1036 }
1037 } else {
1038 $error++;
1039 }
1040
1041 if (!$error) {
1042 dol_syslog(get_class($this)."::Create success id=".$this->id);
1043 $this->db->commit();
1044 return $this->id;
1045 } else {
1046 dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
1047 $this->db->rollback();
1048 return -4;
1049 }
1050 } else {
1051 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1052 $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1053 $result = -1;
1054 } else {
1055 $this->error = $this->db->lasterror();
1056 $result = -2;
1057 }
1058 $this->db->rollback();
1059 return $result;
1060 }
1061 } else {
1062 $this->db->rollback();
1063 dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
1064 return -3;
1065 }
1066 }
1067
1068
1069 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1079 public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
1080 {
1081 global $conf;
1082
1083 $error = 0;
1084
1085 $this->db->begin();
1086
1087 // phpcs:enable
1088 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1089 $contact = new Contact($this->db);
1090
1091 $contact->name = $this->name_bis;
1092 $contact->firstname = $this->firstname;
1093 $contact->civility_id = $this->civility_id;
1094 $contact->socid = $this->id; // fk_soc
1095 $contact->statut = 1; // deprecated
1096 $contact->status = 1;
1097 $contact->priv = 0;
1098 $contact->country_id = $this->country_id;
1099 $contact->state_id = $this->state_id;
1100 $contact->address = $this->address;
1101 $contact->email = $this->email;
1102 $contact->zip = $this->zip;
1103 $contact->town = $this->town;
1104 $this->setUpperOrLowerCase();
1105 $contact->phone_pro = $this->phone;
1106
1107 $contactId = $contact->create($user, $notrigger);
1108 if ($contactId < 0) {
1109 $error++;
1110 $this->error = $contact->error;
1111 $this->errors = $contact->errors;
1112 dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1113 }
1114
1115 if (empty($error) && is_array($tags) && !empty($tags)) {
1116 $result = $contact->setCategories($tags);
1117 if ($result < 0) {
1118 $error++;
1119 $this->error = $contact->error;
1120 $this->errors = array_merge($this->errors, $contact->errors);
1121 dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1122 $contactId = $result;
1123 }
1124 }
1125
1126 if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
1127 $result = $contact->setNoEmail($no_email);
1128 if ($result < 0) {
1129 $this->error = $contact->error;
1130 $this->errors = array_merge($this->errors, $contact->errors);
1131 dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1132 $contactId = $result;
1133 }
1134 }
1135
1136 if (empty($error)) {
1137 dol_syslog(get_class($this)."::create_individual success");
1138 $this->db->commit();
1139 } else {
1140 $this->db->rollback();
1141 }
1142
1143 return $contactId;
1144 }
1145
1152 public function verify()
1153 {
1154 global $conf, $langs, $mysoc;
1155
1156 $error = 0;
1157 $this->errors = array();
1158
1159 $result = 0;
1160 $this->name = trim($this->name);
1161 $this->nom = $this->name; // For backward compatibility
1162
1163 if (!$this->name) {
1164 $this->errors[] = 'ErrorBadThirdPartyName';
1165 $result = -2;
1166 }
1167
1168 if ($this->client) {
1169 $rescode = $this->check_codeclient();
1170 if ($rescode != 0 && $rescode != -5) {
1171 if ($rescode == -1) {
1172 $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1173 } elseif ($rescode == -2) {
1174 $this->errors[] = 'ErrorCustomerCodeRequired';
1175 } elseif ($rescode == -3) {
1176 $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1177 } elseif ($rescode == -4) {
1178 $this->errors[] = 'ErrorPrefixRequired';
1179 } else {
1180 $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1181 }
1182
1183 $result = -3;
1184 }
1185 }
1186
1187 if ($this->fournisseur) {
1188 $rescode = $this->check_codefournisseur();
1189 if ($rescode != 0 && $rescode != -5) {
1190 if ($rescode == -1) {
1191 $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1192 } elseif ($rescode == -2) {
1193 $this->errors[] = 'ErrorSupplierCodeRequired';
1194 } elseif ($rescode == -3) {
1195 $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1196 } elseif ($rescode == -4) {
1197 $this->errors[] = 'ErrorPrefixRequired';
1198 } else {
1199 $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1200 }
1201 $result = -3;
1202 }
1203 }
1204
1205 // Check for duplicate or mandatory fields defined into setup
1206 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
1207 foreach ($array_to_check as $key) {
1208 $keymin = strtolower($key);
1209 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
1210 $keymin = 'code_compta';
1211 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1212 $keymin = 'code_compta_fournisseur';
1213 }
1214 $i = (int) preg_replace('/[^0-9]/', '', $key);
1215 $vallabel = $this->$keymin;
1216
1217 if ($i > 0) {
1218 if ($this->isACompany()) {
1219 // Check for mandatory prof id (but only if country is same than ours)
1220 if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1221 $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1222 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1223 $langs->load("errors");
1224 $error++;
1225 $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1226 }
1227 }
1228 }
1229
1230 // Check for unicity on profid
1231 if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1232 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1233 $langs->load("errors");
1234 $error++;
1235 $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1236 }
1237 }
1238 } else {
1239 //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1240 //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1241 if ($key == 'EMAIL') {
1242 // Check for mandatory
1243 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY') && !isValidEMail($this->email)) {
1244 $langs->load("errors");
1245 $error++;
1246 $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1247 }
1248
1249 // Check for unicity
1250 if (!$error && $vallabel && getDolGlobalString('SOCIETE_EMAIL_UNIQUE')) {
1251 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1252 $langs->load("errors");
1253 $error++;
1254 $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1255 }
1256 }
1257 } elseif ($key == 'TVA_INTRA') {
1258 // Check for unicity
1259 if ($vallabel && getDolGlobalString('SOCIETE_VAT_INTRA_UNIQUE')) {
1260 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1261 $langs->load("errors");
1262 $error++;
1263 $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1264 }
1265 }
1266 } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
1267 // Check for unicity
1268 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE')) {
1269 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1270 $langs->loadLangs(array("errors", 'compta'));
1271 $error++;
1272 $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1273 }
1274 }
1275
1276 // Check for mandatory
1277 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1278 $langs->loadLangs(array("errors", 'compta'));
1279 $error++;
1280 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1281 }
1282 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
1283 // Check for unicity
1284 if ($vallabel && getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE')) {
1285 if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1286 $langs->loadLangs(array("errors", 'compta'));
1287 $error++;
1288 $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1289 }
1290 }
1291
1292 // Check for mandatory
1293 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY') && (!isset($vallabel) || trim($vallabel) === '')) {
1294 $langs->loadLangs(array("errors", 'compta'));
1295 $error++;
1296 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
1297 }
1298 }
1299 }
1300 }
1301
1302 if ($error) {
1303 $result = -4;
1304 }
1305
1306 return $result;
1307 }
1308
1321 public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1322 {
1323 global $langs, $conf, $hookmanager;
1324
1325 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1326
1327 if (empty($id)) {
1328 $id = $this->id;
1329 }
1330
1331 $error = 0;
1332
1333 dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1334
1335 $now = dol_now();
1336
1337 // Clean parameters
1338 $this->id = $id;
1339 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1340 $this->name = $this->name ? trim($this->name) : trim((string) $this->nom);
1341 $this->nom = $this->name; // For backward compatibility
1342 $this->name_alias = trim((string) $this->name_alias);
1343 $this->ref_ext = (empty($this->ref_ext) ? '' : trim($this->ref_ext));
1344 $this->address = trim((string) $this->address);
1345 $this->zip = trim((string) $this->zip);
1346 $this->town = trim((string) $this->town);
1347 $this->state_id = (is_numeric($this->state_id)) ? (int) trim($this->state_id) : 0;
1348 $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1349 $this->phone = trim((string) $this->phone);
1350 $this->phone = preg_replace("/\s/", "", $this->phone);
1351 $this->phone = preg_replace("/\./", "", $this->phone);
1352 $this->fax = trim((string) $this->fax);
1353 $this->fax = preg_replace("/\s/", "", $this->fax);
1354 $this->fax = preg_replace("/\./", "", $this->fax);
1355 $this->email = trim($this->email);
1356 $this->url = $this->url ? clean_url($this->url, 0) : '';
1357 $this->note_private = trim($this->note_private);
1358 $this->note_public = trim($this->note_public);
1359 $this->idprof1 = trim($this->idprof1);
1360 $this->idprof2 = trim($this->idprof2);
1361 $this->idprof3 = trim($this->idprof3);
1362 $this->idprof4 = trim($this->idprof4);
1363 $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
1364 $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
1365 $this->prefix_comm = trim($this->prefix_comm);
1366 $this->outstanding_limit = price2num($this->outstanding_limit);
1367 $this->order_min_amount = price2num($this->order_min_amount);
1368 $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1369
1370 $this->tva_assuj = trim($this->tva_assuj);
1371 $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1372 $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? '0' : '1';
1373 if (empty($this->status)) {
1374 $this->status = 0;
1375 }
1376
1377 if (!empty($this->multicurrency_code)) {
1378 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1379 }
1380 if (empty($this->fk_multicurrency)) {
1381 $this->multicurrency_code = '';
1382 $this->fk_multicurrency = 0;
1383 }
1384
1385 // Local taxes
1386 $this->localtax1_assuj = trim($this->localtax1_assuj);
1387 $this->localtax2_assuj = trim($this->localtax2_assuj);
1388
1389 $this->localtax1_value = trim($this->localtax1_value);
1390 $this->localtax2_value = trim($this->localtax2_value);
1391
1392 if ($this->capital != '') {
1393 $this->capital = price2num(trim($this->capital));
1394 }
1395 if (!is_numeric($this->capital)) {
1396 $this->capital = ''; // '' = undef
1397 }
1398
1399 $this->effectif_id = trim($this->effectif_id);
1400 $this->forme_juridique_code = trim($this->forme_juridique_code);
1401
1402 //Gencod
1403 $this->barcode = trim($this->barcode);
1404
1405 // For automatic creation
1406 if ($this->code_client == -1 || $this->code_client === 'auto') {
1407 $this->get_codeclient($this, 0);
1408 }
1409 if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1410 $this->get_codefournisseur($this, 1);
1411 }
1412
1413 $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1414 $this->code_compta = $this->code_compta_client; // for backward compatibility
1415 $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1416
1417 // Check parameters. More tests are done later in the ->verify()
1418 if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1419 $langs->load("errors");
1420 $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1421 return -1;
1422 }
1423
1424 $customer = false;
1425 if (!empty($allowmodcodeclient) && !empty($this->client)) {
1426 // If $allowmodcodeclient is set and value is not set, we generate it
1427 if (empty($this->code_compta_client)) {
1428 $ret = $this->get_codecompta('customer');
1429 if ($ret < 0) {
1430 return -1;
1431 }
1432 }
1433
1434 $customer = true;
1435 }
1436
1437 $supplier = false;
1438 if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1439 // If $allowmodcodefournisseur is set and value is not set, we generate it
1440 if (empty($this->code_compta_fournisseur)) {
1441 $ret = $this->get_codecompta('supplier');
1442 if ($ret < 0) {
1443 return -1;
1444 }
1445 }
1446
1447 $supplier = true;
1448 }
1449
1450 //Web services
1451 $this->webservices_url = $this->webservices_url ? clean_url($this->webservices_url, 0) : '';
1452 $this->webservices_key = trim($this->webservices_key);
1453
1454 $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1455 $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1456
1457 //Incoterms
1458 $this->fk_incoterms = (int) $this->fk_incoterms;
1459 $this->location_incoterms = trim($this->location_incoterms);
1460
1461 $this->db->begin();
1462
1463 // Check name is required and codes are ok or unique.
1464 // If error, this->errors[] is filled
1465 $result = 0;
1466 if ($action != 'add' && $action != 'merge') {
1467 // We don't check when update called during a create because verify was already done.
1468 // 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
1469 $result = $this->verify();
1470
1471 // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1472 // So we can update record that were using and old numbering rule.
1473 if (is_array($this->errors)) {
1474 if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1475 if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1476 unset($this->errors[$key]); // Remove error message
1477 }
1478 }
1479 if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1480 if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1481 unset($this->errors[$key]); // Remove error message
1482 }
1483 }
1484 if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1485 $result = 0;
1486 }
1487 }
1488 }
1489 $this->setUpperOrLowerCase();
1490 if ($result >= 0) {
1491 dol_syslog(get_class($this)."::update verify ok or not done");
1492
1493 $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1494 $sql .= "entity = ".$this->db->escape($this->entity);
1495 $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1496 $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1497 $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1498 $sql .= ",address = '".$this->db->escape($this->address)."'";
1499
1500 $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1501 $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1502
1503 $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1504 $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1505
1506 $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1507 $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1508 $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1509 $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1510 $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1511
1512 $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1513
1514 $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1515 $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1516
1517 $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1518 $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1519 $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1520 $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1521 $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1522 $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1523
1524 $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1525 $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1526 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1527 $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
1528 }
1529 $sql .= ",status = ".((int) $this->status);
1530
1531 // Local taxes
1532 $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1533 $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1534 if ($this->localtax1_assuj == 1) {
1535 if ($this->localtax1_value != '') {
1536 $sql .= ",localtax1_value =".$this->localtax1_value;
1537 } else {
1538 $sql .= ",localtax1_value =0.000";
1539 }
1540 } else {
1541 $sql .= ",localtax1_value =0.000";
1542 }
1543
1544 if ($this->localtax2_assuj == 1) {
1545 if ($this->localtax2_value != '') {
1546 $sql .= ",localtax2_value =".$this->localtax2_value;
1547 } else {
1548 $sql .= ",localtax2_value =0.000";
1549 }
1550 } else {
1551 $sql .= ",localtax2_value =0.000";
1552 }
1553
1554 $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1555
1556 $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1557
1558 $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1559 if (isset($this->stcomm_id)) {
1560 $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1561 }
1562 if (isset($this->typent_id)) {
1563 $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1564 }
1565
1566 $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1567
1568 $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1569 $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1570 $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1571 $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1572 $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1573 $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1574 $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1575 $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1576
1577 $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1578 $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1579 $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1580 $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1581 $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1582 $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1583 $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1584 $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1585 $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1586 $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1587 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1588 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1589 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1590 if ($customer) {
1591 $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1592 }
1593
1594 if ($supplier) {
1595 $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1596 }
1597 }
1598 $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1599 $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1600
1601 //Incoterms
1602 $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1603 $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1604
1605 if ($customer) {
1606 $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1607 }
1608
1609 if ($supplier) {
1610 $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1611 }
1612 $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1613 $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1614 $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1615 $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1616 $sql .= " WHERE rowid = ".(int) $id;
1617
1618 $resql = $this->db->query($sql);
1619 if ($resql) {
1620 if (is_object($this->oldcopy)) { // If we have information on old values
1621 if ($this->oldcopy->country_id != $this->country_id) {
1622 unset($this->country_code);
1623 unset($this->country);
1624 }
1625 if ($this->oldcopy->state_id != $this->state_id) {
1626 unset($this->state_code);
1627 unset($this->state);
1628 }
1629 } else {
1630 unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1631 unset($this->country);
1632 unset($this->state_code);
1633 unset($this->state);
1634 }
1635
1636 $nbrowsaffected = $this->db->affected_rows($resql);
1637
1638 if (!$error && $nbrowsaffected) {
1639 // Update information on linked member if it is an update
1640 if (!$nosyncmember && isModEnabled('adherent')) {
1641 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1642
1643 dol_syslog(get_class($this)."::update update linked member");
1644
1645 $lmember = new Adherent($this->db);
1646 $result = $lmember->fetch(0, 0, $this->id);
1647
1648 if ($result > 0) {
1649 $lmember->company = $this->name;
1650 //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1651 //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1652 $lmember->address = $this->address;
1653 $lmember->zip = $this->zip;
1654 $lmember->town = $this->town;
1655 $lmember->email = $this->email;
1656 $lmember->socialnetworks = $this->socialnetworks;
1657 $lmember->phone = $this->phone;
1658 $lmember->state_id = $this->state_id;
1659 $lmember->country_id = $this->country_id;
1660 $lmember->default_lang = $this->default_lang;
1661
1662 $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1663 if ($result < 0) {
1664 $this->error = $lmember->error;
1665 $this->errors = array_merge($this->errors, $lmember->errors);
1666 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1667 $error++;
1668 }
1669 } elseif ($result < 0) {
1670 $this->error = $lmember->error;
1671 $error++;
1672 }
1673 }
1674 }
1675
1676 $action = 'update';
1677
1678 // update accountancy for this entity
1679 if (!$error && getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1680 $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1681
1682 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1683 $sql .= " fk_soc";
1684 $sql .= ", entity";
1685 $sql .= ", vat_reverse_charge";
1686 $sql .= ", accountancy_code_customer";
1687 $sql .= ", accountancy_code_supplier";
1688 $sql .= ", accountancy_code_buy";
1689 $sql .= ", accountancy_code_sell";
1690 $sql .= ") VALUES (";
1691 $sql .= $this->id;
1692 $sql .= ", ".$conf->entity;
1693 $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
1694 $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1695 $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1696 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1697 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1698 $sql .= ")";
1699 $result = $this->db->query($sql);
1700 if (!$result) {
1701 $error++;
1702 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1703 }
1704 }
1705
1706 // Actions on extra fields
1707 if (!$error) {
1708 $result = $this->insertExtraFields();
1709 if ($result < 0) {
1710 $error++;
1711 }
1712 }
1713 // Actions on extra languages
1714 if (!$error && !getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { // For avoid conflicts if trigger used
1715 $result = $this->insertExtraLanguages();
1716 if ($result < 0) {
1717 $error++;
1718 }
1719 }
1720
1721 if (!$error && $call_trigger) {
1722 // Call trigger
1723 $result = $this->call_trigger('COMPANY_MODIFY', $user);
1724 if ($result < 0) {
1725 $error++;
1726 }
1727 // End call triggers
1728 }
1729
1730 if (!$error) {
1731 dol_syslog(get_class($this)."::Update success");
1732 $this->db->commit();
1733 return 1;
1734 } else {
1735 $this->db->rollback();
1736 return -1;
1737 }
1738 } else {
1739 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1740 // Doublon
1741 $this->error = $langs->trans("ErrorDuplicateField");
1742 $result = -1;
1743 } else {
1744 $this->error = $this->db->lasterror();
1745 $result = -2;
1746 }
1747 $this->db->rollback();
1748 return $result;
1749 }
1750 } else {
1751 $this->db->rollback();
1752 dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1753 return -3;
1754 }
1755 }
1756
1774 public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1775 {
1776 global $langs;
1777 global $conf;
1778
1779 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)) {
1780 return -1;
1781 }
1782
1783 $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';
1784 $sql .= ', s.status, s.fk_warehouse';
1785 $sql .= ', s.price_level';
1786 $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1787 $sql .= ', s.phone, s.fax, s.email';
1788 $sql .= ', s.socialnetworks';
1789 $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
1790 $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1791 $sql .= ', s.capital, s.tva_intra';
1792 $sql .= ', s.fk_typent as typent_id';
1793 $sql .= ', s.fk_effectif as effectif_id';
1794 $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1795 $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
1796 if (!getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1797 $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1798 $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
1799 } else {
1800 $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1801 $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
1802 }
1803 $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1804 $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';
1805 $sql .= ', s.fk_account, s.tva_assuj';
1806 $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1807 $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1808 $sql .= ', s.fk_shipping_method';
1809 $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1810 $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1811 $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1812 $sql .= ', fj.libelle as forme_juridique';
1813 $sql .= ', e.libelle as effectif';
1814 $sql .= ', c.code as country_code, c.label as country';
1815 $sql .= ', d.code_departement as state_code, d.nom as state';
1816 $sql .= ', r.rowid as region_id, r.code_region as region_code';
1817 $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1818 $sql .= ', te.code as typent_code';
1819 $sql .= ', i.libelle as label_incoterms';
1820 if (!isModEnabled('multicompany')) {
1821 $sql .= ', s.remise_client, s.remise_supplier';
1822 } else {
1823 $sql .= ', sr.remise_client, sr2.remise_supplier';
1824 }
1825 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1826 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1827 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1828 }
1829 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1830 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1831 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1832 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1833 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1834 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1835 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1836 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1837 // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1838 // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1839 if (isModEnabled('multicompany')) {
1840 $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').'))';
1841 $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').'))';
1842 }
1843 $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1844 if ($rowid) {
1845 $sql .= ' AND s.rowid = '.((int) $rowid);
1846 }
1847 if ($ref) {
1848 $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1849 }
1850 if ($ref_alias) {
1851 $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1852 }
1853 if ($ref_ext) {
1854 $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1855 }
1856 if ($barcode) {
1857 $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1858 }
1859 if ($idprof1) {
1860 $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1861 }
1862 if ($idprof2) {
1863 $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1864 }
1865 if ($idprof3) {
1866 $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1867 }
1868 if ($idprof4) {
1869 $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1870 }
1871 if ($idprof5) {
1872 $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1873 }
1874 if ($idprof6) {
1875 $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1876 }
1877 if ($email) {
1878 $sql .= " AND s.email = '".$this->db->escape($email)."'";
1879 }
1880
1881 $resql = $this->db->query($sql);
1882 if ($resql) {
1883 $num = $this->db->num_rows($resql);
1884 if ($num > 1) {
1885 $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1886 dol_syslog($this->error, LOG_ERR);
1887 $result = -2;
1888 } elseif ($num) { // $num = 1
1889 $obj = $this->db->fetch_object($resql);
1890
1891 $this->id = $obj->rowid;
1892 $this->entity = $obj->entity;
1893 $this->canvas = $obj->canvas;
1894
1895 $this->ref = $obj->rowid;
1896 $this->name = $obj->name;
1897 $this->nom = $obj->name; // deprecated
1898 $this->name_alias = $obj->name_alias;
1899 $this->ref_ext = $obj->ref_ext;
1900
1901 $this->date_creation = $this->db->jdate($obj->date_creation);
1902 $this->date_modification = $this->db->jdate($obj->date_modification);
1903 $this->user_creation_id = $obj->fk_user_creat;
1904 $this->user_modification_id = $obj->fk_user_modif;
1905
1906 $this->address = $obj->address;
1907 $this->zip = $obj->zip;
1908 $this->town = $obj->town;
1909
1910 $this->country_id = $obj->country_id;
1911 $this->country_code = $obj->country_id ? $obj->country_code : '';
1912 $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1913
1914 $this->state_id = $obj->state_id;
1915 $this->state_code = $obj->state_code;
1916 $this->region_id = $obj->region_id;
1917 $this->region_code = $obj->region_code;
1918 $this->state = ($obj->state != '-' ? $obj->state : '');
1919
1920 $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1921 $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1922 $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1923 $this->status_prospect_label = $label; // label status prospect
1924 $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1925
1926 $this->email = $obj->email;
1927 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1928
1929 $this->url = $obj->url;
1930 $this->phone = $obj->phone;
1931 $this->fax = $obj->fax;
1932
1933 $this->parent = $obj->parent;
1934
1935 $this->idprof1 = $obj->idprof1;
1936 $this->idprof2 = $obj->idprof2;
1937 $this->idprof3 = $obj->idprof3;
1938 $this->idprof4 = $obj->idprof4;
1939 $this->idprof5 = $obj->idprof5;
1940 $this->idprof6 = $obj->idprof6;
1941
1942 $this->capital = $obj->capital;
1943
1944 $this->code_client = $obj->code_client;
1945 $this->code_fournisseur = $obj->code_fournisseur;
1946
1947 $this->code_compta = $obj->code_compta; // For backward compatibility
1948 $this->code_compta_client = $obj->code_compta;
1949 $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1950
1951 $this->barcode = $obj->barcode;
1952
1953 $this->tva_assuj = $obj->tva_assuj;
1954 $this->tva_intra = $obj->tva_intra;
1955
1956 if (!empty($obj->spe_vat_reverse_charge)) {
1957 $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
1958 } elseif (!empty($obj->soc_vat_reverse_charge)) {
1959 $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
1960 } else {
1961 $this->vat_reverse_charge = 0;
1962 }
1963
1964 $this->status = $obj->status;
1965
1966 // Local Taxes
1967 $this->localtax1_assuj = $obj->localtax1_assuj;
1968 $this->localtax2_assuj = $obj->localtax2_assuj;
1969
1970 $this->localtax1_value = $obj->localtax1_value;
1971 $this->localtax2_value = $obj->localtax2_value;
1972
1973 $this->typent_id = $obj->typent_id;
1974 $this->typent_code = $obj->typent_code;
1975
1976 $this->effectif_id = $obj->effectif_id;
1977 $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1978
1979 $this->forme_juridique_code = $obj->forme_juridique_code;
1980 $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1981
1982 $this->fk_prospectlevel = $obj->fk_prospectlevel;
1983
1984 $this->prefix_comm = $obj->prefix_comm;
1985
1986 $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1987 $this->remise_supplier_percent = $obj->remise_supplier;
1988
1989 $this->mode_reglement_id = $obj->mode_reglement;
1990 $this->cond_reglement_id = $obj->cond_reglement;
1991 $this->deposit_percent = $obj->deposit_percent;
1992 $this->transport_mode_id = $obj->transport_mode;
1993 $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1994 $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1995 $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1996 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1997 $this->fk_account = $obj->fk_account;
1998
1999 $this->client = $obj->client;
2000 $this->fournisseur = $obj->fournisseur;
2001
2002 $this->note = $obj->note_private; // TODO Deprecated for backward comtability
2003 $this->note_private = $obj->note_private;
2004 $this->note_public = $obj->note_public;
2005 $this->model_pdf = $obj->model_pdf;
2006 $this->default_lang = $obj->default_lang;
2007 $this->logo = $obj->logo;
2008 $this->logo_squarred = $obj->logo_squarred;
2009
2010 $this->webservices_url = $obj->webservices_url;
2011 $this->webservices_key = $obj->webservices_key;
2012
2013 $this->accountancy_code_buy = $obj->accountancy_code_buy;
2014 $this->accountancy_code_sell = $obj->accountancy_code_sell;
2015
2016 $this->outstanding_limit = $obj->outstanding_limit;
2017 $this->order_min_amount = $obj->order_min_amount;
2018 $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
2019
2020 // multiprix
2021 $this->price_level = $obj->price_level;
2022
2023 // warehouse
2024 $this->fk_warehouse = $obj->fk_warehouse;
2025
2026 $this->import_key = $obj->import_key;
2027
2028 //Incoterms
2029 $this->fk_incoterms = $obj->fk_incoterms;
2030 $this->location_incoterms = $obj->location_incoterms;
2031 $this->label_incoterms = $obj->label_incoterms;
2032
2033 // multicurrency
2034 $this->fk_multicurrency = $obj->fk_multicurrency;
2035 $this->multicurrency_code = $obj->multicurrency_code;
2036
2037 // pdf
2038 $this->model_pdf = $obj->model_pdf;
2039 $this->last_main_doc = $obj->last_main_doc;
2040
2041 $result = 1;
2042
2043 // fetch optionals attributes and labels
2044 $this->fetch_optionals();
2045 } else {
2046 $result = 0;
2047 }
2048
2049 $this->db->free($resql);
2050 } else {
2051 $this->error = $this->db->lasterror();
2052 $this->errors[] = $this->db->lasterror();
2053 $result = -3;
2054 }
2055
2056 // Use first price level if level not defined for third party
2057 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && empty($this->price_level)) {
2058 $this->price_level = 1;
2059 }
2060
2061 return $result;
2062 }
2063
2072 public function delete($id, User $fuser = null, $call_trigger = 1)
2073 {
2074 global $langs, $conf, $user;
2075
2076 if (empty($fuser)) {
2077 $fuser = $user;
2078 }
2079
2080 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2081
2082 $entity = isset($this->entity) ? $this->entity : $conf->entity;
2083
2084 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2085 $error = 0;
2086
2087 // Test if child exists
2088 $objectisused = $this->isObjectUsed($id);
2089 if (empty($objectisused)) {
2090 $this->db->begin();
2091
2092 // User is mandatory for trigger call
2093 if (!$error && $call_trigger) {
2094 // Call trigger
2095 $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2096 if ($result < 0) {
2097 $error++;
2098 }
2099 // End call triggers
2100 }
2101
2102 if (!$error) {
2103 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2104 $static_cat = new Categorie($this->db);
2105 $toute_categs = array();
2106
2107 // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2108 if ($this->client || $this->prospect) {
2109 $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2110 }
2111 if ($this->fournisseur) {
2112 $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2113 }
2114
2115 // Remove each "Categorie"
2116 foreach ($toute_categs as $type => $categs_type) {
2117 foreach ($categs_type as $cat) {
2118 $cat->del_type($this, $type);
2119 }
2120 }
2121 }
2122
2123 if (!$error) {
2124 foreach ($this->childtablesoncascade as $tabletodelete) {
2125 $deleteFromObject = explode(':', $tabletodelete);
2126 if (count($deleteFromObject) >= 2) {
2127 $className = str_replace('@', '', $deleteFromObject[0]);
2128 $filepath = $deleteFromObject[1];
2129 $columnName = $deleteFromObject[2];
2130 if (dol_include_once($filepath)) {
2131 $child_object = new $className($this->db);
2132 $result = $child_object->deleteByParentField($id, $columnName);
2133 if ($result < 0) {
2134 $error++;
2135 $this->errors[] = $child_object->error;
2136 break;
2137 }
2138 } else {
2139 $error++;
2140 $this->errors[] = 'Cannot include child class file '.$filepath;
2141 break;
2142 }
2143 } else {
2144 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2145 $sql .= " WHERE fk_soc = ".((int) $id);
2146 if (!$this->db->query($sql)) {
2147 $error++;
2148 $this->errors[] = $this->db->lasterror();
2149 break;
2150 }
2151 }
2152 }
2153 }
2154
2155 // Removed extrafields
2156 if (!$error) {
2157 $result = $this->deleteExtraFields();
2158 if ($result < 0) {
2159 $error++;
2160 dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2161 }
2162 }
2163
2164 // Remove links to subsidiaries companies
2165 if (!$error) {
2166 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2167 $sql .= " SET parent = NULL";
2168 $sql .= " WHERE parent = ".((int) $id);
2169 if (!$this->db->query($sql)) {
2170 $error++;
2171 $this->errors[] = $this->db->lasterror();
2172 }
2173 }
2174
2175 // Remove third party
2176 if (!$error) {
2177 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
2178 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2179 $sql .= " WHERE fk_soc = ".((int) $id);
2180 if (!$this->db->query($sql)) {
2181 $error++;
2182 $this->errors[] = $this->db->lasterror();
2183 }
2184 }
2185
2186 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2187 $sql .= " WHERE rowid = ".((int) $id);
2188 if (!$this->db->query($sql)) {
2189 $error++;
2190 $this->errors[] = $this->db->lasterror();
2191 }
2192 }
2193
2194 if (!$error) {
2195 $this->db->commit();
2196
2197 // Delete directory
2198 if (!empty($conf->societe->multidir_output[$entity])) {
2199 $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2200 if (dol_is_dir($docdir)) {
2201 dol_delete_dir_recursive($docdir);
2202 }
2203 }
2204
2205 return 1;
2206 } else {
2207 dol_syslog($this->error, LOG_ERR);
2208 $this->db->rollback();
2209 return -1;
2210 }
2211 } else {
2212 dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
2213 }
2214 return 0;
2215 }
2216
2217 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2225 public function set_as_client()
2226 {
2227 global $conf;
2228 // phpcs:enable
2229 dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
2230 return $this->setAsCustomer();
2231 }
2232
2239 public function setAsCustomer()
2240 {
2241 if ($this->id) {
2242 $newclient = 1;
2243 if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
2244 $newclient = 3; //If prospect, we keep prospect tag
2245 }
2246 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2247 $sql .= " SET client = ".((int) $newclient);
2248 $sql .= " WHERE rowid = ".((int) $this->id);
2249
2250 $resql = $this->db->query($sql);
2251 if ($resql) {
2252 $this->client = $newclient;
2253 return 1;
2254 } else {
2255 return -1;
2256 }
2257 }
2258 return 0;
2259 }
2260
2261 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2270 public function set_remise_client($remise, $note, User $user)
2271 {
2272 // phpcs:enable
2273 global $conf, $langs;
2274
2275 // Parameter cleaning
2276 $note = trim($note);
2277 if (!$note) {
2278 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2279 return -2;
2280 }
2281
2282 dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2283
2284 if ($this->id) {
2285 $this->db->begin();
2286
2287 $now = dol_now();
2288
2289 // Position current discount
2290 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2291 $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2292 $sql .= " WHERE rowid = ".((int) $this->id);
2293 $resql = $this->db->query($sql);
2294 if (!$resql) {
2295 $this->db->rollback();
2296 $this->error = $this->db->error();
2297 return -1;
2298 }
2299
2300 // Writes trace in discount history
2301 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2302 $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2303 $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2304 $sql .= " '".$this->db->escape($note)."',";
2305 $sql .= " ".((int) $user->id);
2306 $sql .= ")";
2307
2308 $resql = $this->db->query($sql);
2309 if (!$resql) {
2310 $this->db->rollback();
2311 $this->error = $this->db->lasterror();
2312 return -1;
2313 }
2314
2315 $this->db->commit();
2316
2317 return 1;
2318 }
2319 return -1;
2320 }
2321
2322 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2331 public function set_remise_supplier($remise, $note, User $user)
2332 {
2333 // phpcs:enable
2334 global $conf, $langs;
2335
2336 // Parameter cleaning
2337 $note = trim($note);
2338 if (!$note) {
2339 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2340 return -2;
2341 }
2342
2343 dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2344
2345 if ($this->id) {
2346 $this->db->begin();
2347
2348 $now = dol_now();
2349
2350 // Position current discount
2351 $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2352 $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2353 $sql .= " WHERE rowid = ".((int) $this->id);
2354 $resql = $this->db->query($sql);
2355 if (!$resql) {
2356 $this->db->rollback();
2357 $this->error = $this->db->error();
2358 return -1;
2359 }
2360
2361 // Writes trace in discount history
2362 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2363 $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2364 $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2365 $sql .= " '".$this->db->escape($note)."',";
2366 $sql .= " ".((int) $user->id);
2367 $sql .= ")";
2368
2369 $resql = $this->db->query($sql);
2370 if (!$resql) {
2371 $this->db->rollback();
2372 $this->error = $this->db->lasterror();
2373 return -1;
2374 }
2375
2376 $this->db->commit();
2377 return 1;
2378 }
2379
2380 return -1;
2381 }
2382
2383 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2395 public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
2396 {
2397 // phpcs:enable
2398 global $langs;
2399
2400 // Clean parameters
2401 $remise = price2num($remise);
2402 $desc = trim($desc);
2403
2404 // Check parameters
2405 if (!($remise > 0)) {
2406 $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2407 return -1;
2408 }
2409 if (!$desc) {
2410 $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2411 return -2;
2412 }
2413
2414 if ($this->id > 0) {
2415 // Clean vat code
2416 $reg = array();
2417 $vat_src_code = '';
2418 if (preg_match('/\‍((.*)\‍)/', $vatrate, $reg)) {
2419 $vat_src_code = $reg[1];
2420 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2421 }
2422
2423 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2424
2425 $discount = new DiscountAbsolute($this->db);
2426 $discount->fk_soc = $this->id;
2427
2428 $discount->discount_type = $discount_type;
2429
2430 if ($price_base_type == 'TTC') {
2431 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
2432 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise / (1 + $vatrate / 100), 'MT');
2433 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($discount->amount_ttc - $discount->amount_ht, 'MT');
2434 } else {
2435 $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2436 $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2437 $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2438 }
2439
2440 $discount->tva_tx = price2num($vatrate);
2441 $discount->vat_src_code = $vat_src_code;
2442
2443 $discount->description = $desc;
2444
2445 $result = $discount->create($user);
2446 if ($result > 0) {
2447 return $result;
2448 } else {
2449 $this->error = $discount->error;
2450 return -3;
2451 }
2452 } else {
2453 return 0;
2454 }
2455 }
2456
2466 public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2467 {
2468 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2469
2470 $discountstatic = new DiscountAbsolute($this->db);
2471 $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2472 if ($result >= 0) {
2473 return $result;
2474 } else {
2475 $this->error = $discountstatic->error;
2476 return -1;
2477 }
2478 }
2479
2489 public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2490 {
2491 global $conf;
2492
2493 $reparray = array();
2494
2495 $sql = "SELECT DISTINCT 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";
2496 $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2497 $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2498 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2499 $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2500 $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2501 $sql .= " AND ug.entity = ".$conf->entity.")";
2502 $sql .= " OR u.admin = 1)";
2503 } else {
2504 $sql .= " WHERE entity in (0, ".$conf->entity.")";
2505 }
2506
2507 $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2508 if (empty($sortfield) && empty($sortorder)) {
2509 $sortfield = 'u.lastname,u.firstname';
2510 $sortorder = 'ASC,ASC';
2511 }
2512 $sql .= $this->db->order($sortfield, $sortorder);
2513
2514 $resql = $this->db->query($sql);
2515 if ($resql) {
2516 $num = $this->db->num_rows($resql);
2517 $i = 0;
2518 while ($i < $num) {
2519 $obj = $this->db->fetch_object($resql);
2520
2521 if (empty($mode)) {
2522 $reparray[$i]['id'] = $obj->rowid;
2523 $reparray[$i]['lastname'] = $obj->lastname;
2524 $reparray[$i]['firstname'] = $obj->firstname;
2525 $reparray[$i]['email'] = $obj->email;
2526 $reparray[$i]['phone'] = $obj->office_phone;
2527 $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
2528 $reparray[$i]['office_fax'] = $obj->office_fax;
2529 $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
2530 $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
2531 $reparray[$i]['job'] = $obj->job;
2532 $reparray[$i]['statut'] = $obj->status; // deprecated
2533 $reparray[$i]['status'] = $obj->status;
2534 $reparray[$i]['entity'] = $obj->entity;
2535 $reparray[$i]['login'] = $obj->login;
2536 $reparray[$i]['photo'] = $obj->photo;
2537 $reparray[$i]['gender'] = $obj->gender;
2538 } else {
2539 $reparray[] = $obj->rowid;
2540 }
2541 $i++;
2542 }
2543 return $reparray;
2544 } else {
2545 dol_print_error($this->db);
2546 return -1;
2547 }
2548 }
2549
2557 public function setPriceLevel($price_level, User $user)
2558 {
2559 if ($this->id) {
2560 $now = dol_now();
2561
2562 $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2563 $sql .= " SET price_level = ".((int) $price_level);
2564 $sql .= " WHERE rowid = ".((int) $this->id);
2565
2566 if (!$this->db->query($sql)) {
2567 dol_print_error($this->db);
2568 return -1;
2569 }
2570
2571 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2572 $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2573 $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2574
2575 if (!$this->db->query($sql)) {
2576 dol_print_error($this->db);
2577 return -1;
2578 }
2579 return 1;
2580 }
2581 return -1;
2582 }
2583
2584 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2592 public function add_commercial(User $user, $commid)
2593 {
2594 // phpcs:enable
2595 $error = 0;
2596
2597 if ($this->id > 0 && $commid > 0) {
2598 $this->db->begin();
2599
2600 if (!$error) {
2601 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2602 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2603
2604 $resql = $this->db->query($sql);
2605 if (!$resql) {
2606 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2607 $error++;
2608 }
2609 }
2610
2611 if (!$error) {
2612 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2613 $sql .= " (fk_soc, fk_user)";
2614 $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2615
2616 $resql = $this->db->query($sql);
2617 if (!$resql) {
2618 dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2619 $error++;
2620 }
2621 }
2622
2623 if (!$error) {
2624 $this->context = array('commercial_modified' => $commid);
2625
2626 $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2627 if ($result < 0) {
2628 $error++;
2629 }
2630 }
2631
2632 if (!$error) {
2633 $this->db->commit();
2634 return 1;
2635 } else {
2636 $this->db->rollback();
2637 return -1;
2638 }
2639 }
2640
2641 return 0;
2642 }
2643
2644 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2652 public function del_commercial(User $user, $commid)
2653 {
2654 // phpcs:enable
2655 $error = 0;
2656 $this->context = array('commercial_modified'=>$commid);
2657
2658 $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2659 if ($result < 0) {
2660 $error++;
2661 }
2662
2663 if ($this->id > 0 && $commid > 0) {
2664 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2665 $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2666
2667 if (!$this->db->query($sql)) {
2668 dol_syslog(get_class($this)."::del_commercial Erreur");
2669 }
2670 }
2671 }
2672
2680 public function getTooltipContentArray($params)
2681 {
2682 global $conf, $langs, $user;
2683
2684 $langs->loadLangs(['companies', 'commercial']);
2685
2686 $datas = array();
2687
2688 $option = $params['option'] ?? '';
2689 $nofetch = !empty($params['nofetch']);
2690
2691 $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
2692
2693 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2694 return ['optimize' => $langs->trans("ShowCompany")];
2695 }
2696
2697 if (!empty($this->logo) && class_exists('Form')) {
2698 $photo = '<div class="photointooltip floatright">';
2699 $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.
2700 $photo .= '</div>';
2701 $datas['photo'] = $photo;
2702 } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2703 /*$label.= '<div class="photointooltip">';
2704 $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.
2705 $label.= '</div><div style="clear: both;"></div>';*/
2706 }
2707
2708 $datas['divopen'] = '<div class="centpercent">';
2709
2710 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2711 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2712 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2713 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2714 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2715 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2716 } elseif ($option == 'agenda') {
2717 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2718 } elseif ($option == 'project') {
2719 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2720 } elseif ($option == 'margin') {
2721 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2722 } elseif ($option == 'contact') {
2723 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2724 } elseif ($option == 'ban') {
2725 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2726 }
2727
2728 // By default
2729 if (empty($datas['picto'])) {
2730 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2731 }
2732 if (isset($this->status)) {
2733 $datas['status'] = ' '.$this->getLibStatut(5);
2734 }
2735 if (isset($this->client) && isset($this->fournisseur)) {
2736 $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
2737 }
2738 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
2739 if (!empty($this->name_alias) && empty($noaliasinname)) {
2740 $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
2741 }
2742 if (!empty($this->email)) {
2743 $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2744 }
2745 if (!empty($this->url)) {
2746 $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
2747 }
2748 if (!empty($this->phone) || !empty($this->fax)) {
2749 $phonelist = array();
2750 if ($this->phone) {
2751 $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2752 }
2753 if ($this->fax) {
2754 $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2755 }
2756 $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
2757 }
2758
2759 if (!empty($this->address)) {
2760 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2761 } elseif (!empty($this->country_code)) {
2762 $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2763 }
2764 if (!empty($this->tva_intra) || (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP') && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2765 $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2766 }
2767
2768 if (getDolGlobalString('SOCIETE_SHOW_FIELD_IN_TOOLTIP')) {
2769 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2770 $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2771 }
2772 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2773 $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2774 }
2775 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2776 $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2777 }
2778 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2779 $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2780 }
2781 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2782 $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2783 }
2784 if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2785 $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2786 }
2787 }
2788
2789 $datas['separator'] = '<br>';
2790
2791 if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2792 $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2793 }
2794 if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
2795 $langs->load('compta');
2796 $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2797 }
2798 // show categories for this record only in ajax to not overload lists
2799 if (!$nofetch && isModEnabled('categorie') && $this->client) {
2800 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2801 $form = new Form($this->db);
2802 $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
2803 }
2804 if (!empty($this->code_fournisseur) && $this->fournisseur) {
2805 $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2806 }
2807 if (isModEnabled('accounting') && $this->fournisseur) {
2808 $langs->load('compta');
2809 $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2810 }
2811 // show categories for this record only in ajax to not overload lists
2812 if (!$nofetch && isModEnabled('categorie') && $this->fournisseur) {
2813 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2814 $form = new Form($this->db);
2815 $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
2816 }
2817
2818 $datas['divclose'] = '</div>';
2819
2820 return $datas;
2821 }
2822
2835 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
2836 {
2837 global $conf, $langs, $hookmanager;
2838
2839 if (!empty($conf->dol_no_mouse_hover)) {
2840 $notooltip = 1; // Force disable tooltips
2841 }
2842
2843 $name = $this->name ? $this->name : $this->nom;
2844
2845 if (getDolGlobalString('SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD')) {
2846 if (empty($option) && $this->client > 0) {
2847 $option = 'customer';
2848 }
2849 if (empty($option) && $this->fournisseur > 0) {
2850 $option = 'supplier';
2851 }
2852 }
2853
2854 if (getDolGlobalString('SOCIETE_ADD_REF_IN_LIST') && (!empty($withpicto))) {
2855 $code = '';
2856 if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
2857 $code = $this->code_client.' - ';
2858 }
2859
2860 if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
2861 $code .= $this->code_fournisseur.' - ';
2862 }
2863
2864 if ($code) {
2865 if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
2866 $name = $code.' '.$name;
2867 } else {
2868 $name = $code;
2869 }
2870 }
2871 }
2872
2873 if (!empty($this->name_alias) && empty($noaliasinname)) {
2874 $name .= ' ('.$this->name_alias.')';
2875 }
2876
2877 $result = '';
2878 $params = [
2879 'id' => $this->id,
2880 'objecttype' => $this->element,
2881 'option' => $option,
2882 'nofetch' => 1,
2883 ];
2884 $classfortooltip = 'classfortooltip';
2885 $dataparams = '';
2886 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2887 $classfortooltip = 'classforajaxtooltip';
2888 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2889 $label = '';
2890 } else {
2891 $label = implode($this->getTooltipContentArray($params));
2892 }
2893
2894 $linkstart = '';
2895 $linkend = '';
2896
2897 if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2898 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2899 } elseif ($option == 'prospect' && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
2900 $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2901 } elseif ($option == 'supplier' || $option == 'category_supplier') {
2902 $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2903 } elseif ($option == 'agenda') {
2904 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2905 } elseif ($option == 'project') {
2906 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2907 } elseif ($option == 'margin') {
2908 $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2909 } elseif ($option == 'contact') {
2910 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2911 } elseif ($option == 'ban') {
2912 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2913 }
2914
2915 // By default
2916 if (empty($linkstart)) {
2917 $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2918 }
2919
2920 // Add type of canvas
2921 $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2922 // Add param to save lastsearch_values or not
2923 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2924 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2925 $add_save_lastsearch_values = 1;
2926 }
2927 if ($add_save_lastsearch_values) {
2928 $linkstart .= '&save_lastsearch_values=1';
2929 }
2930 $linkstart .= '"';
2931
2932 $linkclose = '';
2933 if (empty($notooltip)) {
2934 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2935 $label = $langs->trans("ShowCompany");
2936 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2937 }
2938 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2939 $linkclose .= $dataparams.' class="'.$classfortooltip.' refurl valignmiddle"';
2940 $target_value = array('_self', '_blank', '_parent', '_top');
2941 if (in_array($target, $target_value)) {
2942 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2943 }
2944 } else {
2945 $linkclose .= ' class="valignmiddle"';
2946 }
2947 $linkstart .= $linkclose.'>';
2948 $linkend = '</a>';
2949
2950 global $user;
2951 if (!$user->hasRight('societe', 'client', 'voir') && $user->socid > 0 && $this->id != $user->socid) {
2952 $linkstart = '';
2953 $linkend = '';
2954 }
2955
2956 $result .= $linkstart;
2957 if ($withpicto) {
2958 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2959 }
2960 if ($withpicto != 2) {
2961 $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2962 }
2963 $result .= $linkend;
2964
2965 global $action;
2966 $hookmanager->initHooks(array('thirdpartydao'));
2967 $parameters = array(
2968 'id'=>$this->id,
2969 'getnomurl' => &$result,
2970 'withpicto '=> $withpicto,
2971 'option'=> $option,
2972 'maxlen'=> $maxlen,
2973 'notooltip'=> $notooltip,
2974 'save_lastsearch_value'=> $save_lastsearch_value
2975 );
2976 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2977 if ($reshook > 0) {
2978 $result = $hookmanager->resPrint;
2979 } else {
2980 $result .= $hookmanager->resPrint;
2981 }
2982
2983 return $result;
2984 }
2985
2995 public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
2996 {
2997 global $conf, $langs;
2998
2999 $s = '';
3000 if (empty($option) || preg_match('/prospect/', $option)) {
3001 if (($this->client == 2 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_PROSPECTS')) {
3002 $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.'>';
3003 }
3004 }
3005 if (empty($option) || preg_match('/customer/', $option)) {
3006 if (($this->client == 1 || $this->client == 3) && !getDolGlobalString('SOCIETE_DISABLE_CUSTOMERS')) {
3007 $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.'>';
3008 }
3009 }
3010 if (empty($option) || preg_match('/supplier/', $option)) {
3011 if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
3012 $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.'>';
3013 }
3014 }
3015 return $s;
3016 }
3017
3018
3025 public function getLibStatut($mode = 0)
3026 {
3027 return $this->LibStatut($this->status, $mode);
3028 }
3029
3030 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3038 public function LibStatut($status, $mode = 0)
3039 {
3040 // phpcs:enable
3041 global $langs;
3042 $langs->load('companies');
3043
3044 $statusType = 'status4';
3045 if ($status == 0) {
3046 $statusType = 'status6';
3047 }
3048
3049 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3050 $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3051 $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
3052 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
3053 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
3054 }
3055
3056 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3057 }
3058
3059 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3066 public function thirdparty_and_contact_email_array($addthirdparty = 0)
3067 {
3068 // phpcs:enable
3069 global $langs;
3070
3071 $contact_emails = $this->contact_property_array('email', 1);
3072 if ($this->email && $addthirdparty) {
3073 if (empty($this->name)) {
3074 $this->name = $this->nom;
3075 }
3076 $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
3077 }
3078 //var_dump($contact_emails)
3079 return $contact_emails;
3080 }
3081
3082 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3089 {
3090 // phpcs:enable
3091 global $langs;
3092
3093 $contact_phone = $this->contact_property_array('mobile');
3094
3095 if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
3096 if (empty($this->name)) {
3097 $this->name = $this->nom;
3098 }
3099 // TODO: Tester si tel non deja present dans tableau contact
3100 $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
3101 }
3102 return $contact_phone;
3103 }
3104
3105 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3113 public function contact_property_array($mode = 'email', $hidedisabled = 0)
3114 {
3115 // phpcs:enable
3116 global $langs;
3117
3118 $contact_property = array();
3119
3120
3121 $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
3122 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3123 $sql .= " WHERE fk_soc = ".((int) $this->id);
3124 $sql .= " AND entity IN (".getEntity($this->element).")";
3125 $sql .= " ORDER BY lastname, firstname";
3126
3127 $resql = $this->db->query($sql);
3128 if ($resql) {
3129 $nump = $this->db->num_rows($resql);
3130 if ($nump) {
3131 $sepa = "(";
3132 $sepb = ")";
3133 if ($mode == 'email') {
3134 //$sepa="&lt;"; $sepb="&gt;";
3135 $sepa = "<";
3136 $sepb = ">";
3137 }
3138 $i = 0;
3139 while ($i < $nump) {
3140 $obj = $this->db->fetch_object($resql);
3141 if ($mode == 'email') {
3142 $property = $obj->email;
3143 } elseif ($mode == 'mobile') {
3144 $property = $obj->phone_mobile;
3145 } else {
3146 $property = $obj->$mode;
3147 }
3148
3149 // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
3150 if ($obj->status == 1 || empty($hidedisabled)) {
3151 if (empty($property)) {
3152 if ($mode == 'email') {
3153 $property = $langs->transnoentitiesnoconv("NoEMail");
3154 } elseif ($mode == 'mobile') {
3155 $property = $langs->transnoentitiesnoconv("NoMobilePhone");
3156 }
3157 }
3158
3159 if (!empty($obj->poste)) {
3160 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3161 } else {
3162 $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
3163 }
3164 }
3165 $i++;
3166 }
3167 }
3168 } else {
3169 dol_print_error($this->db);
3170 }
3171 return $contact_property;
3172 }
3173
3174
3175 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3181 public function contact_array()
3182 {
3183 // phpcs:enable
3184 $contacts = array();
3185
3186 $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3187 $resql = $this->db->query($sql);
3188 if ($resql) {
3189 $nump = $this->db->num_rows($resql);
3190 if ($nump) {
3191 $i = 0;
3192 while ($i < $nump) {
3193 $obj = $this->db->fetch_object($resql);
3194 $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
3195 $i++;
3196 }
3197 }
3198 } else {
3199 dol_print_error($this->db);
3200 }
3201 return $contacts;
3202 }
3203
3204 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3210 public function contact_array_objects()
3211 {
3212 // phpcs:enable
3213 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3214 $contacts = array();
3215
3216 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3217 $resql = $this->db->query($sql);
3218 if ($resql) {
3219 $nump = $this->db->num_rows($resql);
3220 if ($nump) {
3221 $i = 0;
3222 while ($i < $nump) {
3223 $obj = $this->db->fetch_object($resql);
3224 $contact = new Contact($this->db);
3225 $contact->fetch($obj->rowid);
3226 $contacts[] = $contact;
3227 $i++;
3228 }
3229 }
3230 } else {
3231 dol_print_error($this->db);
3232 }
3233 return $contacts;
3234 }
3235
3236 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3244 public function contact_get_property($rowid, $mode)
3245 {
3246 // phpcs:enable
3247 $contact_property = '';
3248
3249 if (empty($rowid)) {
3250 return '';
3251 }
3252
3253 $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3254 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3255 $sql .= " WHERE rowid = ".((int) $rowid);
3256
3257 $resql = $this->db->query($sql);
3258 if ($resql) {
3259 $nump = $this->db->num_rows($resql);
3260
3261 if ($nump) {
3262 $obj = $this->db->fetch_object($resql);
3263
3264 if ($mode == 'email') {
3265 $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3266 } elseif ($mode == 'mobile') {
3267 $contact_property = $obj->phone_mobile;
3268 }
3269 }
3270 return $contact_property;
3271 } else {
3272 dol_print_error($this->db);
3273 }
3274
3275 return '';
3276 }
3277
3278
3279 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3286 public function display_rib($mode = 'label')
3287 {
3288 // phpcs:enable
3289 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3290
3291 $bac = new CompanyBankAccount($this->db);
3292 $bac->fetch(0, $this->id);
3293
3294 if ($bac->id > 0) { // If a bank account has been found for company $this->id
3295 if ($mode == 'label') {
3296 return $bac->getRibLabel(true);
3297 } elseif ($mode == 'rum') {
3298 if (empty($bac->rum)) {
3299 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3300 $prelevement = new BonPrelevement($this->db);
3301 $bac->fetch_thirdparty();
3302 $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3303 }
3304 return $bac->rum;
3305 } elseif ($mode == 'format') {
3306 return $bac->frstrecur;
3307 } else {
3308 return 'BadParameterToFunctionDisplayRib';
3309 }
3310 } else {
3311 return '';
3312 }
3313 }
3314
3315 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3321 public function get_all_rib()
3322 {
3323 // phpcs:enable
3324 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3325 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3326 $result = $this->db->query($sql);
3327 if (!$result) {
3328 $this->error++;
3329 $this->errors[] = $this->db->lasterror;
3330 return 0;
3331 } else {
3332 $num_rows = $this->db->num_rows($result);
3333 $rib_array = array();
3334 if ($num_rows) {
3335 while ($obj = $this->db->fetch_object($result)) {
3336 $rib = new CompanyBankAccount($this->db);
3337 $rib->fetch($obj->rowid);
3338 $rib_array[] = $rib;
3339 }
3340 }
3341 return $rib_array;
3342 }
3343 }
3344
3345 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3354 public function get_codeclient($objsoc = 0, $type = 0)
3355 {
3356 // phpcs:enable
3357 global $conf;
3358 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3359 $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3360
3361 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3362 foreach ($dirsociete as $dirroot) {
3363 $res = dol_include_once($dirroot.$module.'.php');
3364 if ($res) {
3365 break;
3366 }
3367 }
3368 $mod = new $module();
3369
3370 $this->code_client = $mod->getNextValue($objsoc, $type);
3371 $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3372
3373 dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3374 }
3375 }
3376
3377 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3386 public function get_codefournisseur($objsoc = 0, $type = 1)
3387 {
3388 // phpcs:enable
3389 global $conf;
3390 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3391 $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3392
3393 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3394 foreach ($dirsociete as $dirroot) {
3395 $res = dol_include_once($dirroot.$module.'.php');
3396 if ($res) {
3397 break;
3398 }
3399 }
3400 $mod = new $module();
3401
3402 $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3403
3404 dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3405 }
3406 }
3407
3408 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3415 public function codeclient_modifiable()
3416 {
3417 // phpcs:enable
3418 global $conf;
3419 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3420 $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3421
3422 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3423 foreach ($dirsociete as $dirroot) {
3424 $res = dol_include_once($dirroot.$module.'.php');
3425 if ($res) {
3426 break;
3427 }
3428 }
3429
3430 $mod = new $module();
3431
3432 dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3433 if ($mod->code_modifiable_null && !$this->code_client) {
3434 return 1;
3435 }
3436 if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3437 return 1;
3438 }
3439 if ($mod->code_modifiable) {
3440 return 1; // A mettre en dernier
3441 }
3442 return 0;
3443 } else {
3444 return 0;
3445 }
3446 }
3447
3448
3449 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3456 {
3457 // phpcs:enable
3458 global $conf;
3459 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3460 $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3461
3462 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3463 foreach ($dirsociete as $dirroot) {
3464 $res = dol_include_once($dirroot.$module.'.php');
3465 if ($res) {
3466 break;
3467 }
3468 }
3469
3470 $mod = new $module();
3471
3472 dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3473 if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3474 return 1;
3475 }
3476 if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3477 return 1;
3478 }
3479 if ($mod->code_modifiable) {
3480 return 1; // A mettre en dernier
3481 }
3482 return 0;
3483 } else {
3484 return 0;
3485 }
3486 }
3487
3488
3489 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3501 public function check_codeclient()
3502 {
3503 // phpcs:enable
3504 global $conf;
3505 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3506 $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3507
3508 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3509 foreach ($dirsociete as $dirroot) {
3510 $res = dol_include_once($dirroot.$module.'.php');
3511 if ($res) {
3512 break;
3513 }
3514 }
3515
3516 $mod = new $module();
3517
3518 dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3519 $result = $mod->verif($this->db, $this->code_client, $this, 0);
3520 if ($result) { // If error
3521 $this->error = $mod->error;
3522 $this->errors = $mod->errors;
3523 }
3524 return $result;
3525 } else {
3526 return 0;
3527 }
3528 }
3529
3530 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3542 public function check_codefournisseur()
3543 {
3544 // phpcs:enable
3545 global $conf;
3546 if (getDolGlobalString('SOCIETE_CODECLIENT_ADDON')) {
3547 $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3548
3549 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3550 foreach ($dirsociete as $dirroot) {
3551 $res = dol_include_once($dirroot.$module.'.php');
3552 if ($res) {
3553 break;
3554 }
3555 }
3556
3557 $mod = new $module();
3558
3559 dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3560 $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3561 if ($result) { // If error
3562 $this->error = $mod->error;
3563 $this->errors = $mod->errors;
3564 }
3565 return $result;
3566 } else {
3567 return 0;
3568 }
3569 }
3570
3571 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3580 public function get_codecompta($type)
3581 {
3582 // phpcs:enable
3583 global $conf;
3584
3585 if (getDolGlobalString('SOCIETE_CODECOMPTA_ADDON')) {
3586 $module=$conf->global->SOCIETE_CODECOMPTA_ADDON;
3587 $res = false;
3588 $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3589 foreach ($dirsociete as $dirroot) {
3590 $res = dol_include_once($dirroot.$module.'.php');
3591 if ($res) {
3592 break;
3593 }
3594 }
3595
3596 if ($res) {
3597 $mod = new $module();
3598
3599 // Set code count in $mod->code
3600 $result = $mod->get_code($this->db, $this, $type);
3601
3602 if ($type == 'customer') {
3603 $this->code_compta_client = $mod->code;
3604 $this->code_compta = $this->code_compta_client; // For backward compatibility
3605 } elseif ($type == 'supplier') {
3606 $this->code_compta_fournisseur = $mod->code;
3607 }
3608
3609 return $result;
3610 } else {
3611 $this->error = 'ErrorAccountancyCodeNotDefined';
3612 return -1;
3613 }
3614 } else {
3615 if ($type == 'customer') {
3616 $this->code_compta_client = '';
3617 $this->code_compta = '';
3618 } elseif ($type == 'supplier') {
3619 $this->code_compta_fournisseur = '';
3620 }
3621
3622 return 0;
3623 }
3624 }
3625
3632 public function setParent($id)
3633 {
3634 dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3635
3636 if ($this->id) {
3637 // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3638 if ($id > 0) {
3639 $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3640 if ($sameparent < 0) {
3641 return -1;
3642 }
3643 if ($sameparent == 1) {
3644 setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3645 return -1;
3646 }
3647 }
3648
3649 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3650
3651 $resql = $this->db->query($sql);
3652 if ($resql) {
3653 $this->parent = $id;
3654 return 1;
3655 } else {
3656 return -1;
3657 }
3658 }
3659
3660 return -1;
3661 }
3662
3671 public function validateFamilyTree($idparent, $idchild, $counter = 0)
3672 {
3673 if ($counter > 100) {
3674 dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3675 }
3676
3677 $sql = 'SELECT s.parent';
3678 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3679 $sql .= ' WHERE rowid = '.((int) $idparent);
3680 $resql = $this->db->query($sql);
3681 if ($resql) {
3682 $obj = $this->db->fetch_object($resql);
3683
3684 if ($obj->parent == '') {
3685 return 0;
3686 } elseif ($obj->parent == $idchild) {
3687 return 1;
3688 } else {
3689 $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3690 }
3691 return $sameparent;
3692 } else {
3693 return -1;
3694 }
3695 }
3696
3704 public function getParentsForCompany($company_id, $parents = array())
3705 {
3706 global $langs;
3707
3708 if ($company_id > 0) {
3709 $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
3710 $resql = $this->db->query($sql);
3711 if ($resql) {
3712 if ($obj = $this->db->fetch_object($resql)) {
3713 $parent = $obj->parent;
3714 if ($parent > 0 && !in_array($parent, $parents)) {
3715 $parents[] = $parent;
3716 return $this->getParentsForCompany($parent, $parents);
3717 } else {
3718 return $parents;
3719 }
3720 }
3721 $this->db->free($resql);
3722 } else {
3723 setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3724 }
3725 }
3726 // Return a default value when $company_id is not greater than 0
3727 return array();
3728 }
3729
3730 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3737 public function id_prof_verifiable($idprof)
3738 {
3739 // phpcs:enable
3740 global $conf;
3741
3742 switch ($idprof) {
3743 case 1:
3744 $ret = (!getDolGlobalString('SOCIETE_IDPROF1_UNIQUE') ? false : true);
3745 break;
3746 case 2:
3747 $ret = (!getDolGlobalString('SOCIETE_IDPROF2_UNIQUE') ? false : true);
3748 break;
3749 case 3:
3750 $ret = (!getDolGlobalString('SOCIETE_IDPROF3_UNIQUE') ? false : true);
3751 break;
3752 case 4:
3753 $ret = (!getDolGlobalString('SOCIETE_IDPROF4_UNIQUE') ? false : true);
3754 break;
3755 case 5:
3756 $ret = (!getDolGlobalString('SOCIETE_IDPROF5_UNIQUE') ? false : true);
3757 break;
3758 case 6:
3759 $ret = (!getDolGlobalString('SOCIETE_IDPROF6_UNIQUE') ? false : true);
3760 break;
3761 default:
3762 $ret = false;
3763 }
3764
3765 return $ret;
3766 }
3767
3768 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3777 public function id_prof_exists($idprof, $value, $socid = 0)
3778 {
3779 // phpcs:enable
3780 $field = $idprof;
3781
3782 switch ($idprof) { // For backward compatibility
3783 case '1':
3784 case 'idprof1':
3785 $field = "siren";
3786 break;
3787 case '2':
3788 case 'idprof2':
3789 $field = "siret";
3790 break;
3791 case '3':
3792 case 'idprof3':
3793 $field = "ape";
3794 break;
3795 case '4':
3796 case 'idprof4':
3797 $field = "idprof4";
3798 break;
3799 case '5':
3800 $field = "idprof5";
3801 break;
3802 case '6':
3803 $field = "idprof6";
3804 break;
3805 }
3806
3807 //Verify duplicate entries
3808 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3809 if ($socid) {
3810 $sql .= " AND rowid <> ".$socid;
3811 }
3812 $resql = $this->db->query($sql);
3813 if ($resql) {
3814 $obj = $this->db->fetch_object($resql);
3815 $count = $obj->nb;
3816 } else {
3817 $count = 0;
3818 print $this->db->error();
3819 }
3820 $this->db->free($resql);
3821
3822 if ($count > 0) {
3823 return true;
3824 } else {
3825 return false;
3826 }
3827 }
3828
3829 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3838 public function id_prof_check($idprof, $soc)
3839 {
3840 // phpcs:enable
3841 global $conf;
3842
3843 $ok = 1;
3844
3845 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
3846 return 1;
3847 }
3848
3849 // Check SIREN if country FR
3850 if ($idprof == 1 && $soc->country_code == 'FR') {
3851 $chaine = trim($this->idprof1);
3852 $chaine = preg_replace('/(\s)/', '', $chaine);
3853
3854 if (!is_numeric($chaine)) {
3855 return -1;
3856 }
3857 if (dol_strlen($chaine) != 9) {
3858 return -1;
3859 }
3860
3861 // on prend chaque chiffre un par un
3862 // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3863 // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3864 // on ajoute cette valeur à la somme totale
3865 $sum = 0;
3866 for ($index = 0; $index < 9; $index++) {
3867 $number = (int) $chaine[$index];
3868 if ($index % 2 != 0) {
3869 if (($number *= 2) > 9) {
3870 $number -= 9;
3871 }
3872 }
3873 $sum += $number;
3874 }
3875
3876 // le numéro est valide si la somme des chiffres est multiple de 10
3877 if ($sum % 10 != 0) {
3878 return -1;
3879 }
3880 }
3881
3882 // Verifie SIRET si pays FR
3883 if ($idprof == 2 && $soc->country_code == 'FR') {
3884 $chaine = trim($this->idprof2);
3885 $chaine = preg_replace('/(\s)/', '', $chaine);
3886
3887 if (!is_numeric($chaine)) {
3888 return -1;
3889 }
3890 if (dol_strlen($chaine) != 14) {
3891 return -1;
3892 }
3893
3894 // on prend chaque chiffre un par un
3895 // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3896 // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3897 // on ajoute cette valeur à la somme totale
3898 $sum = 0;
3899 for ($index = 0; $index < 14; $index++) {
3900 $number = (int) $chaine[$index];
3901 if (($index % 2) == 0) {
3902 if (($number *= 2) > 9) {
3903 $number -= 9;
3904 }
3905 }
3906 $sum += $number;
3907 }
3908
3909 // le numéro est valide si la somme des chiffres est multiple de 10
3910 if ($sum % 10 != 0) {
3911 return -1;
3912 }
3913 }
3914
3915 //Verify CIF/NIF/NIE if pays ES
3916 //Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
3917 if ($idprof == 1 && $soc->country_code == 'ES') {
3918 $string = trim($this->idprof1);
3919 $string = preg_replace('/(\s)/', '', $string);
3920 $string = strtoupper($string);
3921
3922 //Check format
3923 if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string)) {
3924 return 0;
3925 }
3926
3927 $num = array();
3928 for ($i = 0; $i < 9; $i++) {
3929 $num[$i] = substr($string, $i, 1);
3930 }
3931
3932 //Check NIF
3933 if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3934 if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3935 return 1;
3936 } else {
3937 return -1;
3938 }
3939 }
3940
3941 //algorithm checking type code CIF
3942 $sum = $num[2] + $num[4] + $num[6];
3943 for ($i = 1; $i < 8; $i += 2) {
3944 $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3945 }
3946 $n = 10 - substr($sum, strlen($sum) - 1, 1);
3947
3948 //Chek special NIF
3949 if (preg_match('/^[KLM]{1}/', $string)) {
3950 if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3951 return 1;
3952 } else {
3953 return -1;
3954 }
3955 }
3956
3957 //Check CIF
3958 if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3959 if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3960 return 2;
3961 } else {
3962 return -2;
3963 }
3964 }
3965
3966 //Check NIE T
3967 if (preg_match('/^[T]{1}/', $string)) {
3968 if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3969 return 3;
3970 } else {
3971 return -3;
3972 }
3973 }
3974
3975 //Check NIE XYZ
3976 if (preg_match('/^[XYZ]{1}/', $string)) {
3977 if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3978 return 3;
3979 } else {
3980 return -3;
3981 }
3982 }
3983
3984 //Can not be verified
3985 return -4;
3986 }
3987
3988 //Verify NIF if country is PT
3989 //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3990 if ($idprof == 1 && $soc->country_code == 'PT') {
3991 $string = trim($this->idprof1);
3992 $string = preg_replace('/(\s)/', '', $string);
3993
3994 //Check NIF
3995 if (preg_match('/(^[0-9]{9}$)/', $string)) {
3996 return 1;
3997 } else {
3998 return -1;
3999 }
4000 }
4001
4002 //Verify NIF if country is DZ
4003 //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
4004 if ($idprof == 1 && $soc->country_code == 'DZ') {
4005 $string = trim($this->idprof1);
4006 $string = preg_replace('/(\s)/', '', $string);
4007
4008 //Check NIF
4009 if (preg_match('/(^[0-9]{15}$)/', $string)) {
4010 return 1;
4011 } else {
4012 return -1;
4013 }
4014 }
4015
4016 //Verify ID Prof 1 if country is BE (xxxx.xxx.xxx) (https://economie.fgov.be/fr/themes/entreprises/banque-carrefour-des/actualites/structure-du-numero)
4017 //Returns: 1 if ok, -1 if bad, 0 if unexpected bad
4018 if ($idprof == 1 && $soc->country_code == 'BE') {
4019 $string = trim($this->idprof1);
4020 $string = preg_replace('/(\s)/', '', $string);
4021
4022 //Check
4023 if (preg_match('/(^[0-9]{4}\.[0-9]{3}\.[0-9]{3}$)/', $string)) {
4024 return 1;
4025 } else {
4026 return -1;
4027 }
4028 }
4029
4030 return $ok;
4031 }
4032
4033 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4042 public function id_prof_url($idprof, $thirdparty)
4043 {
4044 // phpcs:enable
4045 global $conf, $langs, $hookmanager;
4046
4047 $url = '';
4048 $action = '';
4049
4050 $hookmanager->initHooks(array('idprofurl'));
4051 $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
4052 $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4053 if (empty($reshook)) {
4054 if (getDolGlobalString('MAIN_DISABLEPROFIDRULES')) {
4055 return '';
4056 }
4057
4058 // TODO Move links to validate professional ID into a dictionary table "country" + "link"
4059 $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
4060 if ($idprof == 1 && $thirdparty->country_code == 'FR') {
4061 $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
4062 }
4063 if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
4064 $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
4065 }
4066 if ($idprof == 1 && $thirdparty->country_code == 'ES') {
4067 $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
4068 }
4069 if ($idprof == 1 && $thirdparty->country_code == 'IN') {
4070 $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
4071 }
4072 if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
4073 $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
4074 }
4075 if ($idprof == 1 && $thirdparty->country_code == 'PT') {
4076 $url = 'http://www.nif.pt/'.$strippedIdProf1;
4077 }
4078
4079 if ($url) {
4080 return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
4081 }
4082 } else {
4083 return $hookmanager->resPrint;
4084 }
4085
4086 return '';
4087 }
4088
4089 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4095 public function has_projects()
4096 {
4097 // phpcs:enable
4098 $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
4099 $resql = $this->db->query($sql);
4100 if ($resql) {
4101 $obj = $this->db->fetch_object($resql);
4102 $count = $obj->numproj;
4103 } else {
4104 $count = 0;
4105 print $this->db->error();
4106 }
4107 $this->db->free($resql);
4108 return ($count > 0);
4109 }
4110
4111
4118 public function info($id)
4119 {
4120 $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
4121 $sql .= " fk_user_creat, fk_user_modif";
4122 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
4123 $sql .= " WHERE s.rowid = ".((int) $id);
4124
4125 $result = $this->db->query($sql);
4126 if ($result) {
4127 if ($this->db->num_rows($result)) {
4128 $obj = $this->db->fetch_object($result);
4129
4130 $this->id = $obj->rowid;
4131
4132 $this->user_creation_id = $obj->fk_user_creat;
4133 $this->user_modification_id = $obj->fk_user_modif;
4134 $this->date_creation = $this->db->jdate($obj->datec);
4135 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
4136
4137 $this->ref = $obj->name;
4138 }
4139
4140 $this->db->free($result);
4141 } else {
4142 dol_print_error($this->db);
4143 }
4144 }
4145
4151 public function isACompany()
4152 {
4153 global $conf;
4154
4155 // Define if third party is treated as company (or not) when nature is unknown
4156 $isacompany = !getDolGlobalString('MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES') ? 0 : 1; // 0 by default
4157 if (!empty($this->tva_intra)) {
4158 $isacompany = 1;
4159 } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
4160 $isacompany = 1;
4161 } else {
4162 if (getDolGlobalString('DEFINE_CUSTOMERS_ARE_COMPANIES_BY_TYPE_COMPANY')) {
4163 // TODO Add a field is_a_company into dictionary
4164 if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
4165 $isacompany = 0;
4166 } else {
4167 $isacompany = 1;
4168 }
4169 } else {
4170 $isacompany = 0;
4171 }
4172 }
4173
4174 return $isacompany;
4175 }
4176
4182 public function isInEEC()
4183 {
4184 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4185 return isInEEC($this);
4186 }
4187
4188 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4194 public function LoadSupplierCateg()
4195 {
4196 // phpcs:enable
4197 $this->SupplierCategories = array();
4198 $sql = "SELECT rowid, label";
4199 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
4200 $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
4201
4202 $resql = $this->db->query($sql);
4203 if ($resql) {
4204 while ($obj = $this->db->fetch_object($resql)) {
4205 $this->SupplierCategories[$obj->rowid] = $obj->label;
4206 }
4207 return 0;
4208 } else {
4209 return -1;
4210 }
4211 }
4212
4213 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4220 public function AddFournisseurInCategory($categorie_id)
4221 {
4222 // phpcs:enable
4223 if ($categorie_id > 0 && $this->id > 0) {
4224 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
4225 $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
4226
4227 if ($resql = $this->db->query($sql)) {
4228 return 0;
4229 }
4230 } else {
4231 return 0;
4232 }
4233 return -1;
4234 }
4235
4241 public function getNbOfEMailings()
4242 {
4243 $sql = "SELECT count(mc.email) as nb";
4244 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
4245 $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
4246 $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
4247
4248 $resql = $this->db->query($sql);
4249 if ($resql) {
4250 $obj = $this->db->fetch_object($resql);
4251 $nb = $obj->nb;
4252
4253 $this->db->free($resql);
4254 return $nb;
4255 } else {
4256 $this->error = $this->db->error();
4257 return -1;
4258 }
4259 }
4260
4267 public function setNoEmail($no_email)
4268 {
4269 $error = 0;
4270
4271 // Update mass emailing flag into table mailing_unsubscribe
4272 if ($this->email) {
4273 $this->db->begin();
4274
4275 if ($no_email) {
4276 $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)."'";
4277 $resql = $this->db->query($sql);
4278 if ($resql) {
4279 $obj = $this->db->fetch_object($resql);
4280 $noemail = $obj->nb;
4281 if (empty($noemail)) {
4282 $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())."')";
4283 $resql = $this->db->query($sql);
4284 if (!$resql) {
4285 $error++;
4286 $this->error = $this->db->lasterror();
4287 $this->errors[] = $this->error;
4288 }
4289 }
4290 } else {
4291 $error++;
4292 $this->error = $this->db->lasterror();
4293 $this->errors[] = $this->error;
4294 }
4295 } else {
4296 $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
4297 $resql = $this->db->query($sql);
4298 if (!$resql) {
4299 $error++;
4300 $this->error = $this->db->lasterror();
4301 $this->errors[] = $this->error;
4302 }
4303 }
4304
4305 if (empty($error)) {
4306 $this->no_email = $no_email;
4307 $this->db->commit();
4308 return 1;
4309 } else {
4310 $this->db->rollback();
4311 return $error * -1;
4312 }
4313 }
4314
4315 return 0;
4316 }
4317
4324 public function getNoEmail()
4325 {
4326 if ($this->email) {
4327 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
4328 $resql = $this->db->query($sql);
4329 if ($resql) {
4330 $obj = $this->db->fetch_object($resql);
4331 $this->no_email = $obj->nb;
4332 return 1;
4333 } else {
4334 $this->error = $this->db->lasterror();
4335 $this->errors[] = $this->error;
4336 return -1;
4337 }
4338 }
4339 return 0;
4340 }
4341
4342 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4352 public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4353 {
4354 // phpcs:enable
4355 global $conf, $user, $langs;
4356
4357 dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4358 $fullname = $member->getFullName($langs);
4359
4360 if ($member->morphy == 'mor') {
4361 if (empty($socname)) {
4362 $socname = $member->company ? $member->company : $member->societe;
4363 }
4364 if (!empty($fullname) && empty($socalias)) {
4365 $socalias = $fullname;
4366 }
4367 } elseif (empty($socname) && $member->morphy == 'phy') {
4368 if (empty($socname)) {
4369 $socname = $fullname;
4370 }
4371 if (!empty($member->company) && empty($socalias)) {
4372 $socalias = $member->company;
4373 }
4374 }
4375
4376 $name = $socname;
4377 $alias = $socalias ? $socalias : '';
4378
4379 // Positionne parametres
4380 $this->nom = $name; // TODO deprecated
4381 $this->name = $name;
4382 $this->name_alias = $alias;
4383 $this->address = $member->address;
4384 $this->zip = $member->zip;
4385 $this->town = $member->town;
4386 $this->country_code = $member->country_code;
4387 $this->country_id = $member->country_id;
4388 $this->phone = $member->phone; // Prof phone
4389 $this->email = $member->email;
4390 $this->socialnetworks = $member->socialnetworks;
4391 $this->entity = $member->entity;
4392
4393 $this->client = 1; // A member is a customer by default
4394 $this->code_client = ($customercode ? $customercode : -1);
4395 $this->code_fournisseur = -1;
4396 $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4397 $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4398
4399 $this->db->begin();
4400
4401 // Cree et positionne $this->id
4402 $result = $this->create($user);
4403
4404 if ($result >= 0) {
4405 // Auto-create contact on thirdparty creation
4406 if (getDolGlobalString('THIRDPARTY_DEFAULT_CREATE_CONTACT')) {
4407 // Fill fields needed by contact
4408 $this->name_bis = $member->lastname;
4409 $this->firstname = $member->firstname;
4410 $this->civility_id = $member->civility_id;
4411
4412 dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4413 $result = $this->create_individual($user);
4414
4415 if ($result < 0) {
4416 setEventMessages($this->error, $this->errors, 'errors');
4417 $this->db->rollback();
4418 return -1;
4419 }
4420 }
4421
4422 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4423 $sql .= " SET fk_soc = ".((int) $this->id);
4424 $sql .= " WHERE rowid = ".((int) $member->id);
4425
4426 $resql = $this->db->query($sql);
4427 if ($resql) {
4428 $this->db->commit();
4429 return $this->id;
4430 } else {
4431 $this->error = $this->db->error();
4432
4433 $this->db->rollback();
4434 return -1;
4435 }
4436 } else {
4437 // $this->error deja positionne
4438 dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
4439
4440 $this->db->rollback();
4441 return $result;
4442 }
4443 }
4444
4451 public function setMysoc(Conf $conf)
4452 {
4453 global $langs;
4454
4455 $this->id = 0;
4456 $this->entity = $conf->entity;
4457 $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
4458 $this->nom = $this->name; // deprecated
4459 $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
4460 $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
4461 $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
4462 $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
4463
4464 $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
4465
4466 $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
4467
4468 // We define country_id, country_code and country
4469 $country_id = $country_code = $country_label = '';
4470 if (getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')) {
4471 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY'));
4472 $country_id = $tmp[0];
4473 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4474 $country_code = $tmp[1];
4475 $country_label = $tmp[2];
4476 } else {
4477 // For backward compatibility
4478 dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4479 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4480 $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
4481 $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
4482 }
4483 }
4484 $this->country_id = $country_id;
4485 $this->country_code = $country_code;
4486 $this->country = $country_label;
4487 if (is_object($langs)) {
4488 $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4489 }
4490
4491 //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4492 // We define state_id, state_code and state
4493 $state_id = 0;
4494 $state_code = $state_label = '';
4495 if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) {
4496 $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE'));
4497 $state_id = $tmp[0];
4498 if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4499 $state_code = $tmp[1];
4500 $state_label = $tmp[2];
4501 } else { // For backward compatibility
4502 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);
4503 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4504 $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
4505 $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
4506 }
4507 }
4508 $this->state_id = $state_id;
4509 $this->state_code = $state_code;
4510 $this->state = $state_label;
4511 if (is_object($langs)) {
4512 $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4513 }
4514
4515 $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
4516 $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
4517 $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
4518
4519 // Social networks
4520 $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
4521 $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
4522 $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
4523 $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
4524 $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
4525 $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
4526 $this->socialnetworks = array();
4527 if (!empty($facebook_url)) {
4528 $this->socialnetworks['facebook'] = $facebook_url;
4529 }
4530 if (!empty($twitter_url)) {
4531 $this->socialnetworks['twitter'] = $twitter_url;
4532 }
4533 if (!empty($linkedin_url)) {
4534 $this->socialnetworks['linkedin'] = $linkedin_url;
4535 }
4536 if (!empty($instagram_url)) {
4537 $this->socialnetworks['instagram'] = $instagram_url;
4538 }
4539 if (!empty($youtube_url)) {
4540 $this->socialnetworks['youtube'] = $youtube_url;
4541 }
4542 if (!empty($github_url)) {
4543 $this->socialnetworks['github'] = $github_url;
4544 }
4545
4546 // Id prof generiques
4547 $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
4548 $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
4549 $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
4550 $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
4551 $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
4552 $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
4553 $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarly INTRA.
4554 $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
4555 $this->capital = getDolGlobalString('MAIN_INFO_CAPITAL');
4556 $this->forme_juridique_code = getDolGlobalString('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
4557 $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
4558 $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
4559 $this->logo =getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
4560 $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
4561 $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
4562 $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
4563 $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
4564 $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
4565
4566 // Define if company use vat or not
4567 $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
4568
4569 // Define if company use local taxes
4570 $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
4571 $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
4572 }
4573
4581 public function initAsSpecimen()
4582 {
4583 $now = dol_now();
4584
4585 // Initialize parameters
4586 $this->id = 0;
4587 $this->entity = 1;
4588 $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4589 $this->nom = $this->name; // For backward compatibility
4590 $this->ref_ext = 'Ref ext';
4591 $this->specimen = 1;
4592 $this->address = '21 jump street';
4593 $this->zip = '99999';
4594 $this->town = 'MyTown';
4595 $this->state_id = 1;
4596 $this->state_code = 'AA';
4597 $this->state = 'MyState';
4598 $this->country_id = 1;
4599 $this->country_code = 'FR';
4600 $this->email = 'specimen@specimen.com';
4601 $this->socialnetworks = array(
4602 'skype' => 'skypepseudo',
4603 'twitter' => 'twitterpseudo',
4604 'facebook' => 'facebookpseudo',
4605 'linkedin' => 'linkedinpseudo',
4606 );
4607 $this->url = 'http://www.specimen.com';
4608
4609 $this->phone = '0909090901';
4610 $this->fax = '0909090909';
4611
4612 $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4613 $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4614 $this->capital = 10000;
4615 $this->client = 1;
4616 $this->prospect = 1;
4617 $this->fournisseur = 1;
4618 $this->tva_assuj = 1;
4619 $this->tva_intra = 'EU1234567';
4620 $this->note_public = 'This is a comment (public)';
4621 $this->note_private = 'This is a comment (private)';
4622
4623 $this->idprof1 = 'idprof1';
4624 $this->idprof2 = 'idprof2';
4625 $this->idprof3 = 'idprof3';
4626 $this->idprof4 = 'idprof4';
4627 $this->idprof5 = 'idprof5';
4628 $this->idprof6 = 'idprof6';
4629 return 1;
4630 }
4631
4638 public function useLocalTax($localTaxNum = 0)
4639 {
4640 $sql = "SELECT t.localtax1, t.localtax2";
4641 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4642 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4643 $sql .= " AND t.active = 1";
4644 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4645 if (empty($localTaxNum)) {
4646 $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4647 } elseif ($localTaxNum == 1) {
4648 $sql .= " AND t.localtax1_type <> '0'";
4649 } elseif ($localTaxNum == 2) {
4650 $sql .= " AND t.localtax2_type <> '0'";
4651 }
4652
4653 $resql = $this->db->query($sql);
4654 if ($resql) {
4655 return ($this->db->num_rows($resql) > 0);
4656 } else {
4657 return false;
4658 }
4659 }
4660
4666 public function useNPR()
4667 {
4668 $sql = "SELECT t.rowid";
4669 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4670 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4671 $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4672 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
4673
4674 dol_syslog("useNPR", LOG_DEBUG);
4675 $resql = $this->db->query($sql);
4676 if ($resql) {
4677 return ($this->db->num_rows($resql) > 0);
4678 } else {
4679 return false;
4680 }
4681 }
4682
4689 public function useRevenueStamp()
4690 {
4691 $sql = "SELECT COUNT(*) as nb";
4692 $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4693 $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4694 $sql .= " AND r.active = 1";
4695
4696 dol_syslog("useRevenueStamp", LOG_DEBUG);
4697 $resql = $this->db->query($sql);
4698 if ($resql) {
4699 $obj = $this->db->fetch_object($resql);
4700 return (($obj->nb > 0) ? true : false);
4701 } else {
4702 $this->error = $this->db->lasterror();
4703 return false;
4704 }
4705 }
4706
4712 public function getLibProspLevel()
4713 {
4714 return $this->LibProspLevel($this->fk_prospectlevel);
4715 }
4716
4717 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4724 public function LibProspLevel($fk_prospectlevel)
4725 {
4726 // phpcs:enable
4727 global $langs;
4728 if ($fk_prospectlevel != '') {
4729 $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
4730 // If lib not found in language file, we get label from cache/database
4731 if ($lib == "ProspectLevel".$fk_prospectlevel) {
4732 $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4733 }
4734 }
4735 return $lib ?? '';
4736 }
4737
4745 public function getLibProspCommStatut($mode = 0, $label = '')
4746 {
4747 return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4748 }
4749
4750 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4764 public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4765 {
4766 // phpcs:enable
4767 global $langs;
4768
4769 $langs->load('customers');
4770
4771 if ($mode == 2) {
4772 if ($status == '-1' || $status == 'ST_NO') {
4773 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4774 } elseif ($status == '0' || $status == 'ST_NEVER') {
4775 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4776 } elseif ($status == '1' || $status == 'ST_TODO') {
4777 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4778 } elseif ($status == '2' || $status == 'ST_PEND') {
4779 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4780 } elseif ($status == '3' || $status == 'ST_DONE') {
4781 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4782 } else {
4783 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);
4784 }
4785 } elseif ($mode == 3) {
4786 if ($status == '-1' || $status == 'ST_NO') {
4787 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"');
4788 } elseif ($status == '0' || $status == 'ST_NEVER') {
4789 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"');
4790 } elseif ($status == '1' || $status == 'ST_TODO') {
4791 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"');
4792 } elseif ($status == '2' || $status == 'ST_PEND') {
4793 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"');
4794 } elseif ($status == '3' || $status == 'ST_DONE') {
4795 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"');
4796 } else {
4797 return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"');
4798 }
4799 } elseif ($mode == 4) {
4800 if ($status == '-1' || $status == 'ST_NO') {
4801 return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
4802 } elseif ($status == '0' || $status == 'ST_NEVER') {
4803 return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
4804 } elseif ($status == '1' || $status == 'ST_TODO') {
4805 return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
4806 } elseif ($status == '2' || $status == 'ST_PEND') {
4807 return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
4808 } elseif ($status == '3' || $status == 'ST_DONE') {
4809 return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
4810 } else {
4811 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);
4812 }
4813 }
4814
4815 return "Error, mode/status not found";
4816 }
4817
4824 public function getOutstandingProposals($mode = 'customer')
4825 {
4826 $table = 'propal';
4827 if ($mode == 'supplier') {
4828 $table = 'supplier_proposal';
4829 }
4830
4831 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4832 $sql .= " WHERE fk_soc = ".((int) $this->id);
4833 if ($mode == 'supplier') {
4834 $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4835 } else {
4836 $sql .= " AND entity IN (".getEntity('propal').")";
4837 }
4838
4839 dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4840
4841 $resql = $this->db->query($sql);
4842 if ($resql) {
4843 $outstandingOpened = 0;
4844 $outstandingTotal = 0;
4845 $outstandingTotalIncTax = 0;
4846 $arrayofref = array();
4847 while ($obj = $this->db->fetch_object($resql)) {
4848 $arrayofref[$obj->rowid] = $obj->ref;
4849 $outstandingTotal += $obj->total_ht;
4850 $outstandingTotalIncTax += $obj->total_ttc;
4851 if ($obj->status != 0) {
4852 // Not a draft
4853 $outstandingOpened += $obj->total_ttc;
4854 }
4855 }
4856 return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4857 } else {
4858 return array();
4859 }
4860 }
4861
4868 public function getOutstandingOrders($mode = 'customer')
4869 {
4870 $table = 'commande';
4871 if ($mode == 'supplier') {
4872 $table = 'commande_fournisseur';
4873 }
4874
4875 $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4876 $sql .= " WHERE fk_soc = ".((int) $this->id);
4877 if ($mode == 'supplier') {
4878 $sql .= " AND entity IN (".getEntity('supplier_order').")";
4879 } else {
4880 $sql .= " AND entity IN (".getEntity('commande').")";
4881 }
4882
4883 dol_syslog("getOutstandingOrders", LOG_DEBUG);
4884 $resql = $this->db->query($sql);
4885 if ($resql) {
4886 $outstandingOpened = 0;
4887 $outstandingTotal = 0;
4888 $outstandingTotalIncTax = 0;
4889 $arrayofref = array();
4890 while ($obj = $this->db->fetch_object($resql)) {
4891 $arrayofref[$obj->rowid] = $obj->ref;
4892 $outstandingTotal += $obj->total_ht;
4893 $outstandingTotalIncTax += $obj->total_ttc;
4894 if ($obj->status != 0) {
4895 // Not a draft
4896 $outstandingOpened += $obj->total_ttc;
4897 }
4898 }
4899 return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4900 } else {
4901 return array();
4902 }
4903 }
4904
4912 public function getOutstandingBills($mode = 'customer', $late = 0)
4913 {
4914 $table = 'facture';
4915 if ($mode == 'supplier') {
4916 $table = 'facture_fourn';
4917 }
4918
4919 /* Accurate value of remain to pay is to sum remaintopay for each invoice
4920 $paiement = $invoice->getSommePaiement();
4921 $creditnotes=$invoice->getSumCreditNotesUsed();
4922 $deposits=$invoice->getSumDepositsUsed();
4923 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4924 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4925 */
4926 $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4927 $sql .= " WHERE fk_soc = ".((int) $this->id);
4928 if (!empty($late)) {
4929 $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4930 }
4931 if ($mode == 'supplier') {
4932 $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4933 } else {
4934 $sql .= " AND entity IN (".getEntity('invoice').")";
4935 }
4936
4937 dol_syslog("getOutstandingBills", LOG_DEBUG);
4938 $resql = $this->db->query($sql);
4939 if ($resql) {
4940 $outstandingOpened = 0;
4941 $outstandingTotal = 0;
4942 $outstandingTotalIncTax = 0;
4943 $arrayofref = array();
4944 $arrayofrefopened = array();
4945 if ($mode == 'supplier') {
4946 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4947 $tmpobject = new FactureFournisseur($this->db);
4948 } else {
4949 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4950 $tmpobject = new Facture($this->db);
4951 }
4952 while ($obj = $this->db->fetch_object($resql)) {
4953 $arrayofref[$obj->rowid] = $obj->ref;
4954 $tmpobject->id = $obj->rowid;
4955
4956 if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4957 && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4958 ) {
4959 $outstandingTotal += $obj->total_ht;
4960 $outstandingTotalIncTax += $obj->total_ttc;
4961 }
4962
4963 $remaintopay = 0;
4964
4965 if ($obj->paye == 0
4966 && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4967 && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4968 && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4969 //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4970 $paiement = $tmpobject->getSommePaiement();
4971 $creditnotes = $tmpobject->getSumCreditNotesUsed();
4972 $deposits = $tmpobject->getSumDepositsUsed();
4973
4974 $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4975 $outstandingOpened += $remaintopay;
4976 }
4977
4978 //if credit note is converted but not used
4979 // TODO Do this also for customer ?
4980 if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4981 $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4982 $remaintopay -= $remainingcreditnote;
4983 $outstandingOpened -= $remainingcreditnote;
4984 }
4985
4986 if ($remaintopay) {
4987 $arrayofrefopened[$obj->rowid] = $obj->ref;
4988 }
4989 }
4990 return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
4991 } else {
4992 dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4993 return array();
4994 }
4995 }
4996
5003 public function getLibCustProspStatut()
5004 {
5005 return $this->LibCustProspStatut($this->client);
5006 }
5007
5008 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5015 public function LibCustProspStatut($status)
5016 {
5017 // phpcs:enable
5018 global $langs;
5019 $langs->load('companies');
5020
5021 if ($status == 0) {
5022 return $langs->trans("NorProspectNorCustomer");
5023 } elseif ($status == 1) {
5024 return $langs->trans("Customer");
5025 } elseif ($status == 2) {
5026 return $langs->trans("Prospect");
5027 } elseif ($status == 3) {
5028 return $langs->trans("ProspectCustomer");
5029 }
5030
5031 return '';
5032 }
5033
5034
5046 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5047 {
5048 global $conf, $user, $langs;
5049
5050 if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
5051 $modelpath = "core/modules/bank/doc/";
5052
5053 include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5054 $companybankaccount = new CompanyBankAccount($this->db);
5055 $result = $companybankaccount->fetch($moreparams['use_companybankid']);
5056 if (!$result) {
5057 dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
5058 }
5059 $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5060 $this->last_main_doc=$companybankaccount->last_main_doc;
5061 } else {
5062 // Positionne le modele sur le nom du modele a utiliser
5063 if (!dol_strlen($modele)) {
5064 if (getDolGlobalString('COMPANY_ADDON_PDF')) {
5065 $modele = $conf->global->COMPANY_ADDON_PDF;
5066 } else {
5067 print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
5068 return 0;
5069 }
5070 }
5071
5072 if (!isset($this->bank_account)) {
5073 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
5074 $bac = new CompanyBankAccount($this->db);
5075 $result = $bac->fetch(0, $this->id);
5076 if ($result > 0) {
5077 $this->bank_account = $bac;
5078 } else {
5079 $this->bank_account = '';
5080 }
5081 }
5082
5083 $modelpath = "core/modules/societe/doc/";
5084
5085 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5086 }
5087
5088 return $result;
5089 }
5090
5091
5103 public function setCategories($categories, $type_categ)
5104 {
5105 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5106
5107 // Decode type
5108 if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
5109 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
5110 return -1;
5111 }
5112
5113 return parent::setCategoriesCommon($categories, $type_categ);
5114 }
5115
5123 public function setSalesRep($salesrep, $onlyAdd = false)
5124 {
5125 global $user;
5126
5127 // Handle single user
5128 if (!is_array($salesrep)) {
5129 $salesrep = array($salesrep);
5130 }
5131
5132 $to_del = array(); // Nothing to delete
5133 $to_add = $salesrep;
5134 if ($onlyAdd === false) {
5135 // Get current users
5136 $existing = $this->getSalesRepresentatives($user, 1);
5137
5138 // Diff
5139 if (is_array($existing)) {
5140 $to_del = array_diff($existing, $salesrep);
5141 $to_add = array_diff($salesrep, $existing);
5142 }
5143 }
5144
5145 $error = 0;
5146
5147 // Process
5148 foreach ($to_del as $del) {
5149 $this->del_commercial($user, $del);
5150 }
5151 foreach ($to_add as $add) {
5152 $result = $this->add_commercial($user, $add);
5153 if ($result < 0) {
5154 $error++;
5155 break;
5156 }
5157 }
5158
5159 return $error ? -1 : 1;
5160 }
5161
5168 public function setThirdpartyType($typent_id)
5169 {
5170 global $user;
5171
5172 dol_syslog(__METHOD__, LOG_DEBUG);
5173
5174 if ($this->id) {
5175 $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
5176
5177 if ($result > 0) {
5178 $this->typent_id = $typent_id;
5179 $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
5180 return 1;
5181 } else {
5182 return -1;
5183 }
5184 } else {
5185 return -1;
5186 }
5187 }
5188
5198 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5199 {
5200 if ($origin_id == $dest_id) {
5201 dol_syslog('Error: Try to merge a thirdparty into itself');
5202 return false;
5203 }
5204
5209 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5210 $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
5211 $sql .= ' SELECT fk_user ';
5212 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
5213 $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
5214
5215 $resql = $dbs->query($sql);
5216 while ($obj = $dbs->fetch_object($resql)) {
5217 $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
5218 }
5219
5224 $tables = array(
5225 'societe_account',
5226 'societe_commerciaux',
5227 'societe_prices',
5228 'societe_remise',
5229 'societe_remise_except',
5230 'societe_rib'
5231 );
5232
5233 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5234 }
5235
5244 public function setAccountancyCode($type, $value)
5245 {
5246 global $user, $langs, $conf;
5247
5248 $this->db->begin();
5249
5250 $field = 'accountancy_code_sell';
5251 if ($type == 'buy') {
5252 $field = 'accountancy_code_buy';
5253 } elseif ($type == 'sell') {
5254 $field = 'accountancy_code_sell';
5255 } else {
5256 return -1;
5257 }
5258
5259 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
5260 $sql .= $field." = '".$this->db->escape($value)."'";
5261 $sql .= " WHERE rowid = ".((int) $this->id);
5262
5263 dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
5264 $resql = $this->db->query($sql);
5265
5266 if ($resql) {
5267 // Call triggers
5268 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5269 $interface = new Interfaces($this->db);
5270 $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
5271 if ($result < 0) {
5272 $this->errors = $interface->errors;
5273 $this->db->rollback();
5274 return -1;
5275 }
5276 // End call triggers
5277
5278 $this->$field = $value;
5279
5280 $this->db->commit();
5281 return 1;
5282 } else {
5283 $this->error = $this->db->lasterror();
5284 $this->db->rollback();
5285 return -1;
5286 }
5287 }
5288
5295 public function fetchPartnerships($mode)
5296 {
5297 global $langs;
5298
5299 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
5300
5301
5302 $this->partnerships[] = array();
5303
5304 return 1;
5305 }
5306
5314 public function getKanbanView($option = '', $arraydata = null)
5315 {
5316 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
5317
5318 $return = '<div class="box-flex-item box-flex-grow-zero">';
5319 $return .= '<div class="info-box info-box-sm">';
5320 $return .= '<span class="info-box-icon bg-infobox-action">';
5321 $return .= img_picto('', $this->picto);
5322 $return .= '</span>';
5323 $return .= '<div class="info-box-content">';
5324 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
5325 if ($selected >= 0) {
5326 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
5327 }
5328 if (property_exists($this, 'code_client')) {
5329 $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
5330 }
5331 if (method_exists($this, 'getLibStatut')) {
5332 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
5333 }
5334 $return .= '</div>';
5335 $return .= '</div>';
5336 $return .= '</div>';
5337
5338 return $return;
5339 }
5340
5350 public function getContacts($list = 0, $code = '', $element = '')
5351 {
5352 // phpcs:enable
5353 global $langs;
5354
5355 $tab = array();
5356
5357 $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
5358
5359 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
5360
5361 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
5362 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
5363 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
5364 $sql .= ", ".$this->db->prefix()."societe_contacts sc";
5365
5366 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
5367
5368 $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
5369 $sql .= " AND sc.fk_c_type_contact = tc.rowid";
5370 if (!empty($element)) {
5371 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
5372 }
5373 if ($code) {
5374 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
5375 }
5376 $sql .= " AND sc.entity IN (".getEntity($this->element).")";
5377 $sql .= " AND tc.source = 'external'";
5378 $sql .= " AND tc.active=1";
5379
5380 $sql .= " ORDER BY t.lastname ASC";
5381
5382 dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
5383 $resql = $this->db->query($sql);
5384 if ($resql) {
5385 $num = $this->db->num_rows($resql);
5386 $i = 0;
5387 while ($i < $num) {
5388 $obj = $this->db->fetch_object($resql);
5389
5390 if (!$list) {
5391 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
5392 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
5393 $tab[$i] = array(
5394 'source' => $obj->source,
5395 'socid' => $obj->socid,
5396 'id' => $obj->id,
5397 'nom' => $obj->lastname, // For backward compatibility
5398 'civility' => $obj->civility,
5399 'lastname' => $obj->lastname,
5400 'firstname' => $obj->firstname,
5401 'email'=>$obj->email,
5402 'login'=> (empty($obj->login) ? '' : $obj->login),
5403 'photo' => (empty($obj->photo) ? '' : $obj->photo),
5404 'statuscontact' => $obj->statuscontact,
5405 'rowid' => $obj->rowid,
5406 'code' => $obj->code,
5407 'element' => $obj->element,
5408 'libelle' => $libelle_type,
5409 'status' => $obj->statuslink,
5410 'fk_c_type_contact' => $obj->fk_c_type_contact
5411 );
5412 } else {
5413 $tab[$i] = $obj->id;
5414 }
5415
5416 $i++;
5417 }
5418
5419 return $tab;
5420 } else {
5421 $this->error = $this->db->lasterror();
5422 dol_print_error($this->db);
5423 return -1;
5424 }
5425 }
5426
5434 public function mergeCompany($soc_origin_id)
5435 {
5436 global $conf, $langs, $hookmanager, $user, $action;
5437
5438 $error = 0;
5439 $soc_origin = new Societe($this->db); // The thirdparty that we will delete
5440
5441 dol_syslog("mergeCompany merge thirdparty id=".$soc_origin_id." (will be deleted) into the thirdparty id=".$this->id);
5442
5443 if (!$error && $soc_origin->fetch($soc_origin_id) < 1) {
5444 $this->error = $langs->trans('ErrorRecordNotFound');
5445 $error++;
5446 }
5447
5448 if (!$error) {
5449 $this->db->begin();
5450
5451 // Recopy some data
5452 $this->client = $this->client | $soc_origin->client;
5453 $this->fournisseur = $this->fournisseur | $soc_origin->fournisseur;
5454 $listofproperties = array(
5455 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'fax', 'email', 'socialnetworks', 'url', 'barcode',
5456 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
5457 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
5458 'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency',
5459 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
5460 'model_pdf',
5461 );
5462 foreach ($listofproperties as $property) {
5463 if (empty($this->$property)) {
5464 $this->$property = $soc_origin->$property;
5465 }
5466 }
5467
5468 // Concat some data
5469 $listofproperties = array(
5470 'note_public', 'note_private'
5471 );
5472 foreach ($listofproperties as $property) {
5473 $this->$property = dol_concatdesc($this->$property, $soc_origin->$property);
5474 }
5475
5476 // Merge extrafields
5477 if (is_array($soc_origin->array_options)) {
5478 foreach ($soc_origin->array_options as $key => $val) {
5479 if (empty($this->array_options[$key])) {
5480 $this->array_options[$key] = $val;
5481 }
5482 }
5483 }
5484
5485 // If alias name is not defined on target thirdparty, we can store in it the old name of company.
5486 if (empty($this->name_bis) && $this->name != $soc_origin->name) {
5487 $this->name_bis = $this->name;
5488 }
5489
5490 // Merge categories
5491 $static_cat = new Categorie($this->db);
5492
5493 $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
5494 $custcats = $static_cat->containing($this->id, 'customer', 'id');
5495 $custcats = array_merge($custcats, $custcats_ori);
5496 $this->setCategories($custcats, 'customer');
5497
5498 $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
5499 $suppcats = $static_cat->containing($this->id, 'supplier', 'id');
5500 $suppcats = array_merge($suppcats, $suppcats_ori);
5501 $this->setCategories($suppcats, 'supplier');
5502
5503 // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
5504 if ($soc_origin->code_client == $this->code_client
5505 || $soc_origin->code_fournisseur == $this->code_fournisseur
5506 || $soc_origin->barcode == $this->barcode) {
5507 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
5508 $soc_origin->code_client = '';
5509 $soc_origin->code_fournisseur = '';
5510 $soc_origin->barcode = '';
5511 $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
5512 }
5513
5514 // Update
5515 $result = $this->update($this->id, $user, 0, 1, 1, 'merge');
5516
5517 if ($result < 0) {
5518 $error++;
5519 }
5520
5521 // Move links
5522 if (!$error) {
5523 $objects = array(
5524 'Adherent' => '/adherents/class/adherent.class.php',
5525 'Don' => array('file' => '/don/class/don.class.php', 'enabled' => isModEnabled('don')),
5526 'Societe' => '/societe/class/societe.class.php',
5527 //'Categorie' => '/categories/class/categorie.class.php',
5528 'ActionComm' => '/comm/action/class/actioncomm.class.php',
5529 'Propal' => '/comm/propal/class/propal.class.php',
5530 'Commande' => '/commande/class/commande.class.php',
5531 'Facture' => '/compta/facture/class/facture.class.php',
5532 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
5533 'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
5534 'Mo' => '/mrp/class/mo.class.php',
5535 'Contact' => '/contact/class/contact.class.php',
5536 'Contrat' => '/contrat/class/contrat.class.php',
5537 'Expedition' => '/expedition/class/expedition.class.php',
5538 'Fichinter' => '/fichinter/class/fichinter.class.php',
5539 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
5540 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
5541 'FactureFournisseurRec' => '/fourn/class/fournisseur.facture-rec.class.php',
5542 'Reception' => '/reception/class/reception.class.php',
5543 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
5544 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
5545 'Delivery' => '/delivery/class/delivery.class.php',
5546 'Product' => '/product/class/product.class.php',
5547 'Project' => '/projet/class/project.class.php',
5548 'Ticket' => array('file' => '/ticket/class/ticket.class.php', 'enabled' => isModEnabled('ticket')),
5549 'User' => '/user/class/user.class.php',
5550 'Account' => '/compta/bank/class/account.class.php',
5551 'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php'
5552 );
5553
5554 //First, all core objects must update their tables
5555 foreach ($objects as $object_name => $object_file) {
5556 if (is_array($object_file)) {
5557 if (empty($object_file['enabled'])) {
5558 continue;
5559 }
5560 $object_file = $object_file['file'];
5561 }
5562
5563 require_once DOL_DOCUMENT_ROOT.$object_file;
5564
5565 if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $this->id)) {
5566 $error++;
5567 $this->error = $this->db->lasterror();
5568 break;
5569 }
5570 }
5571 }
5572
5573 // External modules should update their ones too
5574 if (!$error) {
5575 $parameters = array('soc_origin' => $soc_origin->id, 'soc_dest' => $this->id);
5576 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
5577
5578 if ($reshook < 0) {
5579 $this->error = $hookmanager->error;
5580 $this->errors = $hookmanager->errors;
5581 $error++;
5582 }
5583 }
5584
5585
5586 if (!$error) {
5587 $this->context = array('merge'=>1, 'mergefromid'=>$soc_origin->id, 'mergefromname'=>$soc_origin->name);
5588
5589 // Call trigger
5590 $result = $this->call_trigger('COMPANY_MODIFY', $user);
5591 if ($result < 0) {
5592 $error++;
5593 }
5594 // End call triggers
5595 }
5596
5597 if (!$error) {
5598 // Move files from the dir of the third party to delete into the dir of the third party to keep
5599 if (!empty($conf->societe->multidir_output[$this->entity])) {
5600 $srcdir = $conf->societe->multidir_output[$this->entity]."/".$soc_origin->id;
5601 $destdir = $conf->societe->multidir_output[$this->entity]."/".$this->id;
5602
5603 if (dol_is_dir($srcdir)) {
5604 $dirlist = dol_dir_list($srcdir, 'files', 1);
5605 foreach ($dirlist as $filetomove) {
5606 $destfile = $destdir.'/'.$filetomove['relativename'];
5607 //var_dump('Move file '.$filetomove['relativename'].' into '.$destfile);
5608 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
5609 }
5610 //exit;
5611 }
5612 }
5613 }
5614
5615
5616 if (!$error) {
5617 // We finally remove the old thirdparty
5618 if ($soc_origin->delete($soc_origin->id, $user) < 1) {
5619 $this->error = $soc_origin->error;
5620 $this->errors = $soc_origin->errors;
5621 $error++;
5622 }
5623 }
5624
5625 if (!$error) {
5626 $this->db->commit();
5627 return 0;
5628 } else {
5629 $langs->load("errors");
5630 $this->error = $langs->trans('ErrorsThirdpartyMerge');
5631 $this->db->rollback();
5632 return -1;
5633 }
5634 }
5635
5636 return -1;
5637 }
5638}
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Definition security.php:604
$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 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)
Class to manage triggers.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage third parties objects (customers, suppliers, prospects...)
setParent($id)
Define parent company of current company.
getLibProspLevel()
Return prostect level.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
setAsCustomer()
Define third party as a customer.
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.
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='')
Load a third party from database into memory.
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()
Return 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.
get_codefournisseur($objsoc=0, $type=1)
Assigns a vendor code from the code control module.
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.
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='')
Return a link on thirdparty (with picto)
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 sould 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.
get_codeclient($objsoc=0, $type=0)
Assigns a customer code from the code control module.
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.
update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.
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.
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
LoadSupplierCateg()
Load the list of provider categories.
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
contact_array_objects()
Returns the contact list of this company.
getAvailableDiscounts($user='', $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the 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 another one, deleting the given company.
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.
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 attribut 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.
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
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.
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
Superclass for thirdparties, contacts, members or users.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
trait CommonSocialNetworks
Superclass for social networks.
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
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_dir_list($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:62
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
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_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs='', $mode=0, $extralangcode='')
Return a formated address (part address/zip/town/state) according to country rules.
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_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dol_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_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
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.
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.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:124
Contact()
Old copy.
Definition index.php:572