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