dolibarr  16.0.5
societe.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5  * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
6  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7  * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8  * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9  * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
10  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11  * Copyright (C) 2013-2021 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-2021 Frédéric France <frederic.france@netlogic.fr>
19  * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
20  *
21  * This program is free software; you can redistribute it and/or modify
22  * it under the terms of the GNU General Public License as published by
23  * the Free Software Foundation; either version 3 of the License, or
24  * (at your option) any later version.
25  *
26  * This program is distributed in the hope that it will be useful,
27  * but WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29  * GNU General Public License for more details.
30  *
31  * You should have received a copy of the GNU General Public License
32  * along with this program. If not, see <https://www.gnu.org/licenses/>.
33  */
34 
40 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
43 
44 
48 class Societe extends CommonObject
49 {
50  use CommonIncoterm;
51 
55  public $element = 'societe';
56 
60  public $table_element = 'societe';
61 
65  public $fk_element = 'fk_soc';
66 
70  public $fieldsforcombobox = 'nom,name_alias';
71 
75  protected $childtables = array(
76  'supplier_proposal' => array('name' => 'SupplierProposal'),
77  'propal' => array('name' => 'Proposal'),
78  'commande' => array('name' => 'Order'),
79  'facture' => array('name' => 'Invoice'),
80  'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
81  'contrat' => array('name' => 'Contract'),
82  'fichinter' => array('name' => 'Fichinter'),
83  'facture_fourn' => array('name' => 'SupplierInvoice'),
84  'commande_fournisseur' => array('name' => 'SupplierOrder'),
85  'projet' => array('name' => 'Project'),
86  'expedition' => array('name' => 'Shipment'),
87  'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
88  );
89 
94  protected $childtablesoncascade = array(
95  'societe_prices',
96  'societe_address',
97  'product_fournisseur_price',
98  'product_customer_price_log',
99  'product_customer_price',
100  '@Contact:/contact/class/contact.class.php:fk_soc',
101  'adherent',
102  'societe_account',
103  'societe_rib',
104  'societe_remise',
105  'societe_remise_except',
106  'societe_commerciaux',
107  'categorie',
108  'notify',
109  'notify_def',
110  'actioncomm',
111  );
112 
116  public $picto = 'company';
117 
122  public $ismultientitymanaged = 1;
123 
128  public $restrictiononfksoc = 1;
129 
130 
160  public $fields = array(
161  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
162  'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
163  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
164  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
165  'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35, 'showoncombobox'=>1),
166  'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36, 'showoncombobox'=>2),
167  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1),
168  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>45),
169  'code_client' =>array('type'=>'varchar(24)', 'label'=>'CustomerCode', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
170  'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierCode', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
171  'code_compta' =>array('type'=>'varchar(24)', 'label'=>'CodeCompta', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
172  'code_compta_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'CodeComptaSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
173  'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
174  'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
175  'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
176  'fk_departement' =>array('type'=>'integer', 'label'=>'State', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
177  'fk_pays' =>array('type'=>'integer:Ccountry:core/class/ccountry.class.php', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
178  'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
179  'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
180  'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
181  'email' =>array('type'=>'varchar(128)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
182  'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
183  'fk_effectif' =>array('type'=>'integer', 'label'=>'Workforce', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
184  'fk_typent' =>array('type'=>'integer', 'label'=>'TypeOfCompany', 'enabled'=>1, 'visible'=>-1, 'position'=>175, 'csslist'=>'minwidth200'),
185  'fk_forme_juridique' =>array('type'=>'integer', 'label'=>'JuridicalStatus', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
186  'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
187  'siren' =>array('type'=>'varchar(128)', 'label'=>'Idprof1', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
188  'siret' =>array('type'=>'varchar(128)', 'label'=>'Idprof2', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
189  'ape' =>array('type'=>'varchar(128)', 'label'=>'Idprof3', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
190  'idprof4' =>array('type'=>'varchar(128)', 'label'=>'Idprof4', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
191  'idprof5' =>array('type'=>'varchar(128)', 'label'=>'Idprof5', 'enabled'=>1, 'visible'=>-1, 'position'=>206),
192  'idprof6' =>array('type'=>'varchar(128)', 'label'=>'Idprof6', 'enabled'=>1, 'visible'=>-1, 'position'=>207),
193  'tva_intra' =>array('type'=>'varchar(20)', 'label'=>'Tva intra', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
194  'capital' =>array('type'=>'double(24,8)', 'label'=>'Capital', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
195  'fk_stcomm' =>array('type'=>'integer', 'label'=>'CommercialStatus', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
196  'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>225),
197  'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>230),
198  'prefix_comm' =>array('type'=>'varchar(5)', 'label'=>'Prefix comm', 'enabled'=>'$conf->global->SOCIETE_USEPREFIX', 'visible'=>-1, 'position'=>235),
199  'client' =>array('type'=>'tinyint(4)', 'label'=>'Client', 'enabled'=>1, 'visible'=>-1, 'position'=>240),
200  'fournisseur' =>array('type'=>'tinyint(4)', 'label'=>'Fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>245),
201  'supplier_account' =>array('type'=>'varchar(32)', 'label'=>'Supplier account', 'enabled'=>1, 'visible'=>-1, 'position'=>250),
202  'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
203  'customer_bad' =>array('type'=>'tinyint(4)', 'label'=>'Customer bad', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
204  'customer_rate' =>array('type'=>'double', 'label'=>'Customer rate', 'enabled'=>1, 'visible'=>-1, 'position'=>265),
205  'supplier_rate' =>array('type'=>'double', 'label'=>'Supplier rate', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
206  'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>275),
207  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>280),
208  //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
209  //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
210  'mode_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>295),
211  'cond_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
212  'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>301),
213  'mode_reglement_supplier' =>array('type'=>'integer', 'label'=>'Mode reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
214  'cond_reglement_supplier' =>array('type'=>'integer', 'label'=>'Cond reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>308),
215  'outstanding_limit' =>array('type'=>'double(24,8)', 'label'=>'OutstandingBill', 'enabled'=>1, 'visible'=>-1, 'position'=>310, 'isameasure'=>1),
216  'order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Order min amount', 'enabled'=>'!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>315, 'isameasure'=>1),
217  'supplier_order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Supplier order min amount', 'enabled'=>'!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>320, 'isameasure'=>1),
218  'fk_shipping_method' =>array('type'=>'integer', 'label'=>'Fk shipping method', 'enabled'=>1, 'visible'=>-1, 'position'=>330),
219  'tva_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Tva assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
220  'localtax1_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax1 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>340),
221  'localtax1_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax1 value', 'enabled'=>1, 'visible'=>-1, 'position'=>345),
222  'localtax2_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax2 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>350),
223  'localtax2_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax2 value', 'enabled'=>1, 'visible'=>-1, 'position'=>355),
224  'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>1, 'visible'=>-1, 'position'=>360),
225  '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),
226  'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>370),
227  'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>375),
228  'fk_barcode_type' =>array('type'=>'integer', 'label'=>'Fk barcode type', 'enabled'=>1, 'visible'=>-1, 'position'=>405),
229  'webservices_url' =>array('type'=>'varchar(255)', 'label'=>'Webservices url', 'enabled'=>1, 'visible'=>-1, 'position'=>410),
230  'webservices_key' =>array('type'=>'varchar(128)', 'label'=>'Webservices key', 'enabled'=>1, 'visible'=>-1, 'position'=>415),
231  'fk_incoterms' =>array('type'=>'integer', 'label'=>'Fk incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>425),
232  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'Location incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>430),
233  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>435),
234  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>440),
235  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>445),
236  'fk_account' =>array('type'=>'integer', 'label'=>'AccountingAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>450),
237  'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>455),
238  'logo' =>array('type'=>'varchar(255)', 'label'=>'Logo', 'enabled'=>1, 'visible'=>-1, 'position'=>400),
239  'logo_squarred' =>array('type'=>'varchar(255)', 'label'=>'Logo squarred', 'enabled'=>1, 'visible'=>-1, 'position'=>401),
240  'status' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
241  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
242  );
243 
247  public $entity;
248 
255  public $nom;
256 
260  public $name;
261 
266  public $name_alias;
267 
271  public $particulier;
272 
276  public $address;
277 
281  public $zip;
282 
286  public $town;
287 
292  public $status = 1;
293 
298  public $state_id;
299 
303  public $state_code;
304 
308  public $state;
309 
314  public $region_code;
315 
319  public $region;
320 
326  public $departement_code;
327 
333  public $departement;
334 
340  public $pays;
341 
346  public $phone;
351  public $fax;
356  public $email;
357 
361  public $socialnetworks;
362 
368  public $skype;
369 
375  public $twitter;
376 
382  public $facebook;
383 
389  public $linkedin;
390 
395  public $url;
396 
401  public $barcode;
402 
403  // 6 professional id (usage depends on country)
404 
409  public $idprof1;
410 
416  public $siren;
417 
418 
423  public $idprof2;
424 
430  public $siret;
431 
436  public $idprof3;
437 
443  public $ape;
444 
449  public $idprof4;
450 
455  public $idprof5;
456 
461  public $idprof6;
462 
466  public $prefix_comm;
467 
471  public $tva_assuj = 1;
472 
477  public $tva_intra;
478 
479  // Local taxes
480  public $localtax1_assuj;
481  public $localtax1_value;
482  public $localtax2_assuj;
483  public $localtax2_value;
484 
488  public $managers;
489 
493  public $capital;
494 
498  public $typent_id = 0;
499  public $typent_code;
500  public $effectif;
501  public $effectif_id = 0;
502  public $forme_juridique_code;
503  public $forme_juridique = 0;
504 
505  public $remise_percent;
506  public $remise_supplier_percent;
507 
508  public $mode_reglement_id;
509  public $cond_reglement_id;
510  public $deposit_percent;
511  public $mode_reglement_supplier_id;
512  public $cond_reglement_supplier_id;
513  public $transport_mode_supplier_id;
514 
518  public $fk_prospectlevel;
519 
523  public $name_bis;
524 
525  //Log data
526 
531  public $date_modification;
532 
537  public $user_modification;
538 
543  public $date_creation;
544 
549  public $user_creation;
550 
555  public $client = 0;
556 
561  public $prospect = 0;
562 
567  public $fournisseur;
568 
573  public $code_client;
574 
579  public $code_fournisseur;
580 
585  public $code_compta_client;
586 
591  public $code_compta;
592 
593 
598  public $accountancy_code_customer;
599 
604  public $code_compta_fournisseur;
605 
610  public $accountancy_code_supplier;
611 
612 
617  public $code_compta_product;
618 
619 
625  public $note;
626 
631  public $note_private;
632 
637  public $note_public;
638 
643  public $stcomm_id;
644 
649  public $stcomm_picto;
650 
655  public $status_prospect_label;
656 
661  public $price_level;
662 
666  public $outstanding_limit;
667 
671  public $order_min_amount;
672 
676  public $supplier_order_min_amount;
677 
682  public $commercial_id;
683 
688  public $parent;
689 
694  public $default_lang;
695 
699  public $ref;
700 
705  public $ref_int;
706 
712  public $ref_ext;
713 
720  public $import_key;
721 
726  public $webservices_url;
727 
732  public $webservices_key;
733 
737  public $logo;
738 
742  public $logo_small;
743 
747  public $logo_mini;
748 
752  public $logo_squarred;
753 
757  public $logo_squarred_small;
758 
762  public $logo_squarred_mini;
763 
767  public $accountancy_code_sell;
768 
772  public $accountancy_code_buy;
773 
774  // Multicurrency
778  public $fk_multicurrency;
779 
780  // Warehouse
784  public $fk_warehouse;
785 
789  public $multicurrency_code;
790 
791 
792  // Fields loaded by fetchPartnerships()
793 
794  public $partnerships = array();
795 
796 
797  const STATUS_CEASED = 0;
798  const STATUS_INACTIVITY = 1;
799 
800 
804  public $bank_account;
805 
809  const NO_CUSTOMER = 0;
810 
814  const CUSTOMER = 1;
815 
819  const PROSPECT = 2;
820 
825 
829  const NO_SUPPLIER = 0;
830 
834  const SUPPLIER = 1;
835 
841  public function __construct($db)
842  {
843  global $conf;
844 
845  $this->db = $db;
846 
847  $this->client = 0;
848  $this->prospect = 0;
849  $this->fournisseur = 0;
850  $this->typent_id = 0;
851  $this->effectif_id = 0;
852  $this->forme_juridique_code = 0;
853  $this->tva_assuj = 1;
854  $this->status = 1;
855 
856  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
857  $this->fields['address']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
858  $this->fields['zip']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
859  $this->fields['town']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
860  //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
861  }
862  }
863 
864 
872  public function create(User $user)
873  {
874  global $langs, $conf, $mysoc;
875 
876  $error = 0;
877 
878  // Clean parameters
879  if (empty($this->status)) {
880  $this->status = 0;
881  }
882  $this->name = $this->name ?trim($this->name) : trim($this->nom);
883  $this->setUpperOrLowerCase();
884  $this->nom = $this->name; // For backward compatibility
885  if (empty($this->client)) {
886  $this->client = 0;
887  }
888  if (empty($this->fournisseur)) {
889  $this->fournisseur = 0;
890  }
891  $this->import_key = trim($this->import_key);
892 
893  $this->accountancy_code_customer = trim($this->code_compta);
894  $this->accountancy_code_supplier = trim($this->code_compta_fournisseur);
895  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
896  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
897 
898  if (!empty($this->multicurrency_code)) {
899  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
900  }
901  if (empty($this->fk_multicurrency)) {
902  $this->multicurrency_code = '';
903  $this->fk_multicurrency = 0;
904  }
905 
906  dol_syslog(get_class($this)."::create ".$this->name);
907 
908  $now = dol_now();
909 
910  $this->db->begin();
911 
912  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
913  if ($this->code_client == -1 || $this->code_client === 'auto') {
914  $this->get_codeclient($this, 0);
915  }
916  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
917  $this->get_codefournisseur($this, 1);
918  }
919 
920  // Check more parameters (including mandatory setup
921  // If error, this->errors[] is filled
922  $result = $this->verify();
923 
924  if ($result >= 0) {
925  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
926 
927  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
928  $sql .= "nom";
929  $sql .= ", name_alias";
930  $sql .= ", entity";
931  $sql .= ", datec";
932  $sql .= ", fk_user_creat";
933  $sql .= ", fk_typent";
934  $sql .= ", canvas";
935  $sql .= ", status";
936  $sql .= ", ref_ext";
937  $sql .= ", fk_stcomm";
938  $sql .= ", fk_incoterms";
939  $sql .= ", location_incoterms";
940  $sql .= ", import_key";
941  $sql .= ", fk_multicurrency";
942  $sql .= ", multicurrency_code";
943  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
944  $sql .= ", accountancy_code_buy";
945  $sql .= ", accountancy_code_sell";
946  }
947  $sql .= ") VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".((int) $this->entity).", '".$this->db->idate($now)."'";
948  $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
949  $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
950  $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
951  $sql .= ", ".((int) $this->status);
952  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
953  $sql .= ", 0";
954  $sql .= ", ".(int) $this->fk_incoterms;
955  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
956  $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
957  $sql .= ", ".(int) $this->fk_multicurrency;
958  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
959  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
960  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
961  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
962  }
963  $sql .= ")";
964 
965  dol_syslog(get_class($this)."::create", LOG_DEBUG);
966  $result = $this->db->query($sql);
967  if ($result) {
968  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
969 
970  $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
971 
972  // update accountancy for this entity
973  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
974  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
975 
976  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
977  $sql .= " fk_soc";
978  $sql .= ", entity";
979  $sql .= ", accountancy_code_customer";
980  $sql .= ", accountancy_code_supplier";
981  $sql .= ", accountancy_code_buy";
982  $sql .= ", accountancy_code_sell";
983  $sql .= ") VALUES (";
984  $sql .= $this->id;
985  $sql .= ", ".((int) $conf->entity);
986  $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
987  $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
988  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
989  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
990  $sql .= ")";
991  $result = $this->db->query($sql);
992  if (!$result) {
993  $error++;
994  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
995  }
996  }
997 
998  // Ajout du commercial affecte
999  if ($this->commercial_id != '' && $this->commercial_id != -1) {
1000  $this->add_commercial($user, $this->commercial_id);
1001  } elseif (empty($user->rights->societe->client->voir)) {
1002  // si un commercial cree un client il lui est affecte automatiquement
1003  $this->add_commercial($user, $user->id);
1004  }
1005 
1006  if ($ret >= 0) {
1007  // Call trigger
1008  $result = $this->call_trigger('COMPANY_CREATE', $user);
1009  if ($result < 0) {
1010  $error++;
1011  }
1012  // End call triggers
1013  } else {
1014  $error++;
1015  }
1016 
1017  if (!$error) {
1018  dol_syslog(get_class($this)."::Create success id=".$this->id);
1019  $this->db->commit();
1020  return $this->id;
1021  } else {
1022  dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
1023  $this->db->rollback();
1024  return -4;
1025  }
1026  } else {
1027  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1028  $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
1029  $result = -1;
1030  } else {
1031  $this->error = $this->db->lasterror();
1032  $result = -2;
1033  }
1034  $this->db->rollback();
1035  return $result;
1036  }
1037  } else {
1038  $this->db->rollback();
1039  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
1040  return -3;
1041  }
1042  }
1043 
1044 
1045  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1054  public function create_individual(User $user, $no_email = 0, $tags = array())
1055  {
1056  global $conf;
1057 
1058  $error = 0;
1059 
1060  $this->db->begin();
1061 
1062  // phpcs:enable
1063  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1064  $contact = new Contact($this->db);
1065 
1066  $contact->name = $this->name_bis;
1067  $contact->firstname = $this->firstname;
1068  $contact->civility_id = $this->civility_id;
1069  $contact->socid = $this->id; // fk_soc
1070  $contact->statut = 1; // deprecated
1071  $contact->status = 1;
1072  $contact->priv = 0;
1073  $contact->country_id = $this->country_id;
1074  $contact->state_id = $this->state_id;
1075  $contact->address = $this->address;
1076  $contact->email = $this->email;
1077  $contact->zip = $this->zip;
1078  $contact->town = $this->town;
1079  $this->setUpperOrLowerCase();
1080  $contact->phone_pro = $this->phone;
1081 
1082  $contactId = $contact->create($user);
1083  if ($contactId < 0) {
1084  $error++;
1085  $this->error = $contact->error;
1086  $this->errors = $contact->errors;
1087  dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
1088  }
1089 
1090  if (empty($error) && is_array($tags) && !empty($tags)) {
1091  $result = $contact->setCategories($tags);
1092  if ($result < 0) {
1093  $error++;
1094  $this->error = $contact->error;
1095  $this->errors = array_merge($this->errors, $contact->errors);
1096  dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
1097  $contactId = $result;
1098  }
1099  }
1100 
1101  if (empty($error) && !empty($conf->mailing->enabled) && !empty($contact->email) && isset($no_email)) {
1102  $result = $contact->setNoEmail($no_email);
1103  if ($result < 0) {
1104  $this->error = $contact->error;
1105  $this->errors = array_merge($this->errors, $contact->errors);
1106  dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
1107  $contactId = $result;
1108  }
1109  }
1110 
1111  if (empty($error)) {
1112  dol_syslog(get_class($this)."::create_individual success");
1113  $this->db->commit();
1114  } else {
1115  $this->db->rollback();
1116  }
1117 
1118  return $contactId;
1119  }
1120 
1127  public function verify()
1128  {
1129  global $conf, $langs, $mysoc;
1130 
1131  $error = 0;
1132  $this->errors = array();
1133 
1134  $result = 0;
1135  $this->name = trim($this->name);
1136  $this->nom = $this->name; // For backward compatibility
1137 
1138  if (!$this->name) {
1139  $this->errors[] = 'ErrorBadThirdPartyName';
1140  $result = -2;
1141  }
1142 
1143  if ($this->client) {
1144  $rescode = $this->check_codeclient();
1145  if ($rescode != 0 && $rescode != -5) {
1146  if ($rescode == -1) {
1147  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
1148  } elseif ($rescode == -2) {
1149  $this->errors[] = 'ErrorCustomerCodeRequired';
1150  } elseif ($rescode == -3) {
1151  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
1152  } elseif ($rescode == -4) {
1153  $this->errors[] = 'ErrorPrefixRequired';
1154  } else {
1155  $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
1156  }
1157 
1158  $result = -3;
1159  }
1160  }
1161 
1162  if ($this->fournisseur) {
1163  $rescode = $this->check_codefournisseur();
1164  if ($rescode != 0 && $rescode != -5) {
1165  if ($rescode == -1) {
1166  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
1167  } elseif ($rescode == -2) {
1168  $this->errors[] = 'ErrorSupplierCodeRequired';
1169  } elseif ($rescode == -3) {
1170  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
1171  } elseif ($rescode == -4) {
1172  $this->errors[] = 'ErrorPrefixRequired';
1173  } else {
1174  $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
1175  }
1176  $result = -3;
1177  }
1178  }
1179 
1180  // Check for duplicate or mandatory fields defined into setup
1181  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL');
1182  foreach ($array_to_check as $key) {
1183  $keymin = strtolower($key);
1184  $i = (int) preg_replace('/[^0-9]/', '', $key);
1185  $vallabel = $this->$keymin;
1186 
1187  if ($i > 0) {
1188  if ($this->isACompany()) {
1189  // Check for mandatory prof id (but only if country is same than ours)
1190  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
1191  $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
1192  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
1193  $langs->load("errors");
1194  $error++;
1195  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
1196  }
1197  }
1198  }
1199 
1200  // Check for unicity on profid
1201  if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
1202  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1203  $langs->load("errors");
1204  $error++;
1205  $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1206  }
1207  }
1208  } else {
1209  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
1210  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
1211  if ($key == 'EMAIL') {
1212  // Check for mandatory
1213  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
1214  $langs->load("errors");
1215  $error++;
1216  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
1217  }
1218 
1219  // Check for unicity
1220  if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
1221  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
1222  $langs->load("errors");
1223  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
1224  }
1225  }
1226  }
1227  }
1228  }
1229 
1230  if ($error) {
1231  $result = -4;
1232  }
1233 
1234  return $result;
1235  }
1236 
1249  public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
1250  {
1251  global $langs, $conf, $hookmanager;
1252 
1253  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1254 
1255  if (empty($id)) {
1256  $id = $this->id;
1257  }
1258 
1259  $error = 0;
1260 
1261  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
1262 
1263  $now = dol_now();
1264 
1265  // Clean parameters
1266  $this->id = $id;
1267  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
1268  $this->name = $this->name ?trim($this->name) : trim($this->nom);
1269  $this->nom = $this->name; // For backward compatibility
1270  $this->name_alias = trim($this->name_alias);
1271  $this->ref_ext = trim($this->ref_ext);
1272  $this->address = $this->address ?trim($this->address) : trim($this->address);
1273  $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
1274  $this->town = $this->town ?trim($this->town) : trim($this->town);
1275  $this->setUpperOrLowerCase();
1276  $this->state_id = trim($this->state_id);
1277  $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
1278  $this->phone = trim($this->phone);
1279  $this->phone = preg_replace("/\s/", "", $this->phone);
1280  $this->phone = preg_replace("/\./", "", $this->phone);
1281  $this->fax = trim($this->fax);
1282  $this->fax = preg_replace("/\s/", "", $this->fax);
1283  $this->fax = preg_replace("/\./", "", $this->fax);
1284  $this->email = trim($this->email);
1285  $this->url = $this->url ?clean_url($this->url, 0) : '';
1286  $this->note_private = trim($this->note_private);
1287  $this->note_public = trim($this->note_public);
1288  $this->idprof1 = trim($this->idprof1);
1289  $this->idprof2 = trim($this->idprof2);
1290  $this->idprof3 = trim($this->idprof3);
1291  $this->idprof4 = trim($this->idprof4);
1292  $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
1293  $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
1294  $this->prefix_comm = trim($this->prefix_comm);
1295  $this->outstanding_limit = price2num($this->outstanding_limit);
1296  $this->order_min_amount = price2num($this->order_min_amount);
1297  $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
1298 
1299  $this->tva_assuj = trim($this->tva_assuj);
1300  $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
1301  if (empty($this->status)) {
1302  $this->status = 0;
1303  }
1304 
1305  if (!empty($this->multicurrency_code)) {
1306  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1307  }
1308  if (empty($this->fk_multicurrency)) {
1309  $this->multicurrency_code = '';
1310  $this->fk_multicurrency = 0;
1311  }
1312 
1313  // Local taxes
1314  $this->localtax1_assuj = trim($this->localtax1_assuj);
1315  $this->localtax2_assuj = trim($this->localtax2_assuj);
1316 
1317  $this->localtax1_value = trim($this->localtax1_value);
1318  $this->localtax2_value = trim($this->localtax2_value);
1319 
1320  if ($this->capital != '') {
1321  $this->capital = price2num(trim($this->capital));
1322  }
1323  if (!is_numeric($this->capital)) {
1324  $this->capital = ''; // '' = undef
1325  }
1326 
1327  $this->effectif_id = trim($this->effectif_id);
1328  $this->forme_juridique_code = trim($this->forme_juridique_code);
1329 
1330  //Gencod
1331  $this->barcode = trim($this->barcode);
1332 
1333  // For automatic creation
1334  if ($this->code_client == -1 || $this->code_client === 'auto') {
1335  $this->get_codeclient($this, 0);
1336  }
1337  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
1338  $this->get_codefournisseur($this, 1);
1339  }
1340 
1341  $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
1342  $this->code_compta = $this->code_compta_client; // for backward compatibility
1343  $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
1344 
1345  // Check parameters. More tests are done later in the ->verify()
1346  if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
1347  $langs->load("errors");
1348  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
1349  return -1;
1350  }
1351 
1352  $customer = false;
1353  if (!empty($allowmodcodeclient) && !empty($this->client)) {
1354  // If $allowmodcodeclient is set and value is not set, we generate it
1355  if (empty($this->code_compta_client)) {
1356  $ret = $this->get_codecompta('customer');
1357  if ($ret < 0) {
1358  return -1;
1359  }
1360  }
1361 
1362  $customer = true;
1363  }
1364 
1365  $supplier = false;
1366  if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
1367  // If $allowmodcodefournisseur is set and value is not set, we generate it
1368  if (empty($this->code_compta_fournisseur)) {
1369  $ret = $this->get_codecompta('supplier');
1370  if ($ret < 0) {
1371  return -1;
1372  }
1373  }
1374 
1375  $supplier = true;
1376  }
1377 
1378  //Web services
1379  $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
1380  $this->webservices_key = trim($this->webservices_key);
1381 
1382  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1383  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1384 
1385  //Incoterms
1386  $this->fk_incoterms = (int) $this->fk_incoterms;
1387  $this->location_incoterms = trim($this->location_incoterms);
1388 
1389  $this->db->begin();
1390 
1391  // Check name is required and codes are ok or unique.
1392  // If error, this->errors[] is filled
1393  $result = 0;
1394  if ($action != 'add' && $action != 'merge') {
1395  // We don't check when update called during a create because verify was already done.
1396  // 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
1397  $result = $this->verify();
1398 
1399  // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
1400  // So we can update record that were using and old numbering rule.
1401  if (is_array($this->errors)) {
1402  if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
1403  if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
1404  unset($this->errors[$key]); // Remove error message
1405  }
1406  }
1407  if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
1408  if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
1409  unset($this->errors[$key]); // Remove error message
1410  }
1411  }
1412  if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
1413  $result = 0;
1414  }
1415  }
1416  }
1417 
1418  if ($result >= 0) {
1419  dol_syslog(get_class($this)."::update verify ok or not done");
1420 
1421  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
1422  $sql .= "entity = ".$this->db->escape($this->entity);
1423  $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
1424  $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
1425  $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1426  $sql .= ",address = '".$this->db->escape($this->address)."'";
1427 
1428  $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
1429  $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
1430 
1431  $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
1432  $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
1433 
1434  $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
1435  $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
1436  $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
1437  $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
1438  $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
1439 
1440  $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
1441 
1442  $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1443  $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1444 
1445  $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
1446  $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
1447  $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
1448  $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
1449  $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
1450  $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
1451 
1452  $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
1453  $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
1454  $sql .= ",status = ".((int) $this->status);
1455 
1456  // Local taxes
1457  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
1458  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
1459  if ($this->localtax1_assuj == 1) {
1460  if ($this->localtax1_value != '') {
1461  $sql .= ",localtax1_value =".$this->localtax1_value;
1462  } else {
1463  $sql .= ",localtax1_value =0.000";
1464  }
1465  } else {
1466  $sql .= ",localtax1_value =0.000";
1467  }
1468 
1469  if ($this->localtax2_assuj == 1) {
1470  if ($this->localtax2_value != '') {
1471  $sql .= ",localtax2_value =".$this->localtax2_value;
1472  } else {
1473  $sql .= ",localtax2_value =0.000";
1474  }
1475  } else {
1476  $sql .= ",localtax2_value =0.000";
1477  }
1478 
1479  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1480 
1481  $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
1482 
1483  $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
1484  if (isset($this->stcomm_id)) {
1485  $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
1486  }
1487  if (isset($this->typent_id)) {
1488  $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
1489  }
1490 
1491  $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
1492 
1493  $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
1494  $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
1495  $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1496  $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
1497  $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
1498  $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
1499  $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
1500  $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
1501 
1502  $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
1503  $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
1504  $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
1505  $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
1506  $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
1507  $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
1508  $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
1509  $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
1510  $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
1511  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1512  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1513  $sql .= ", accountancy_code_buy = '".$this->db->escape($this->accountancy_code_buy)."'";
1514  $sql .= ", accountancy_code_sell= '".$this->db->escape($this->accountancy_code_sell)."'";
1515 
1516  if ($customer) {
1517  $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
1518  }
1519 
1520  if ($supplier) {
1521  $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
1522  }
1523  }
1524  $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
1525  $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
1526 
1527  //Incoterms
1528  $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
1529  $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
1530 
1531  if ($customer) {
1532  $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
1533  }
1534 
1535  if ($supplier) {
1536  $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
1537  }
1538  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
1539  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1540  $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1541  $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
1542  $sql .= " WHERE rowid = ".(int) $id;
1543 
1544  $resql = $this->db->query($sql);
1545  if ($resql) {
1546  if (is_object($this->oldcopy)) { // If we have information on old values
1547  if ($this->oldcopy->country_id != $this->country_id) {
1548  unset($this->country_code);
1549  unset($this->country);
1550  }
1551  if ($this->oldcopy->state_id != $this->state_id) {
1552  unset($this->state_code);
1553  unset($this->state);
1554  }
1555  } else {
1556  unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
1557  unset($this->country);
1558  unset($this->state_code);
1559  unset($this->state);
1560  }
1561 
1562  $nbrowsaffected = $this->db->affected_rows($resql);
1563 
1564  if (!$error && $nbrowsaffected) {
1565  // Update information on linked member if it is an update
1566  if (!$nosyncmember && !empty($conf->adherent->enabled)) {
1567  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1568 
1569  dol_syslog(get_class($this)."::update update linked member");
1570 
1571  $lmember = new Adherent($this->db);
1572  $result = $lmember->fetch(0, 0, $this->id);
1573 
1574  if ($result > 0) {
1575  $lmember->company = $this->name;
1576  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1577  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1578  $lmember->address = $this->address;
1579  $lmember->zip = $this->zip;
1580  $lmember->town = $this->town;
1581  $lmember->email = $this->email;
1582  $lmember->socialnetworks = $this->socialnetworks;
1583  $lmember->phone = $this->phone;
1584  $lmember->state_id = $this->state_id;
1585  $lmember->country_id = $this->country_id;
1586 
1587  $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
1588  if ($result < 0) {
1589  $this->error = $lmember->error;
1590  $this->errors = array_merge($this->errors, $lmember->errors);
1591  dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1592  $error++;
1593  }
1594  } elseif ($result < 0) {
1595  $this->error = $lmember->error;
1596  $error++;
1597  }
1598  }
1599  }
1600 
1601  $action = 'update';
1602 
1603  // update accountancy for this entity
1604  if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1605  $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
1606 
1607  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
1608  $sql .= " fk_soc";
1609  $sql .= ", entity";
1610  $sql .= ", accountancy_code_customer";
1611  $sql .= ", accountancy_code_supplier";
1612  $sql .= ", accountancy_code_buy";
1613  $sql .= ", accountancy_code_sell";
1614  $sql .= ") VALUES (";
1615  $sql .= $this->id;
1616  $sql .= ", ".$conf->entity;
1617  $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
1618  $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
1619  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1620  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1621  $sql .= ")";
1622  $result = $this->db->query($sql);
1623  if (!$result) {
1624  $error++;
1625  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1626  }
1627  }
1628 
1629  // Actions on extra fields
1630  if (!$error) {
1631  $result = $this->insertExtraFields();
1632  if ($result < 0) {
1633  $error++;
1634  }
1635  }
1636  // Actions on extra languages
1637  if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
1638  $result = $this->insertExtraLanguages();
1639  if ($result < 0) {
1640  $error++;
1641  }
1642  }
1643 
1644  if (!$error && $call_trigger) {
1645  // Call trigger
1646  $result = $this->call_trigger('COMPANY_MODIFY', $user);
1647  if ($result < 0) {
1648  $error++;
1649  }
1650  // End call triggers
1651  }
1652 
1653  if (!$error) {
1654  dol_syslog(get_class($this)."::Update success");
1655  $this->db->commit();
1656  return 1;
1657  } else {
1658  $this->db->rollback();
1659  return -1;
1660  }
1661  } else {
1662  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1663  // Doublon
1664  $this->error = $langs->trans("ErrorDuplicateField");
1665  $result = -1;
1666  } else {
1667  $this->error = $this->db->lasterror();
1668  $result = -2;
1669  }
1670  $this->db->rollback();
1671  return $result;
1672  }
1673  } else {
1674  $this->db->rollback();
1675  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1676  return -3;
1677  }
1678  }
1679 
1697  public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1698  {
1699  global $langs;
1700  global $conf;
1701 
1702  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
1703  return -1;
1704  }
1705 
1706  $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';
1707  $sql .= ', s.status, s.fk_warehouse';
1708  $sql .= ', s.price_level';
1709  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1710  $sql .= ', s.phone, s.fax, s.email';
1711  $sql .= ', s.socialnetworks';
1712  $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
1713  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1714  $sql .= ', s.capital, s.tva_intra';
1715  $sql .= ', s.fk_typent as typent_id';
1716  $sql .= ', s.fk_effectif as effectif_id';
1717  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1718  $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf';
1719  if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1720  $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
1721  } else {
1722  $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
1723  }
1724  $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
1725  $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';
1726  $sql .= ', s.fk_account, s.tva_assuj';
1727  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
1728  $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
1729  $sql .= ', s.fk_shipping_method';
1730  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1731  $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1732  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1733  $sql .= ', fj.libelle as forme_juridique';
1734  $sql .= ', e.libelle as effectif';
1735  $sql .= ', c.code as country_code, c.label as country';
1736  $sql .= ', d.code_departement as state_code, d.nom as state';
1737  $sql .= ', r.rowid as region_id, r.code_region as region_code';
1738  $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
1739  $sql .= ', te.code as typent_code';
1740  $sql .= ', i.libelle as label_incoterms';
1741  if (empty($conf->multicompany->enabled)) {
1742  $sql .= ', s.remise_client, s.remise_supplier';
1743  } else {
1744  $sql .= ', sr.remise_client, sr2.remise_supplier';
1745  }
1746  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1747  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
1748  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
1749  }
1750  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1751  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1752  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1753  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1754  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1755  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
1756  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1757  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1758  // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
1759  // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
1760  if (!empty($conf->multicompany->enabled)) {
1761  $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').'))';
1762  $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').'))';
1763  }
1764  $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1765  if ($rowid) {
1766  $sql .= ' AND s.rowid = '.((int) $rowid);
1767  }
1768  if ($ref) {
1769  $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1770  }
1771  if ($ref_alias) {
1772  $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
1773  }
1774  if ($ref_ext) {
1775  $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1776  }
1777  if ($barcode) {
1778  $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
1779  }
1780  if ($idprof1) {
1781  $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1782  }
1783  if ($idprof2) {
1784  $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1785  }
1786  if ($idprof3) {
1787  $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1788  }
1789  if ($idprof4) {
1790  $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1791  }
1792  if ($idprof5) {
1793  $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1794  }
1795  if ($idprof6) {
1796  $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1797  }
1798  if ($email) {
1799  $sql .= " AND s.email = '".$this->db->escape($email)."'";
1800  }
1801 
1802  $resql = $this->db->query($sql);
1803  if ($resql) {
1804  $num = $this->db->num_rows($resql);
1805  if ($num > 1) {
1806  $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
1807  dol_syslog($this->error, LOG_ERR);
1808  $result = -2;
1809  } elseif ($num) { // $num = 1
1810  $obj = $this->db->fetch_object($resql);
1811 
1812  $this->id = $obj->rowid;
1813  $this->entity = $obj->entity;
1814  $this->canvas = $obj->canvas;
1815 
1816  $this->ref = $obj->rowid;
1817  $this->name = $obj->name;
1818  $this->nom = $obj->name; // deprecated
1819  $this->name_alias = $obj->name_alias;
1820  $this->ref_ext = $obj->ref_ext;
1821 
1822  $this->date_creation = $this->db->jdate($obj->date_creation);
1823  $this->date_modification = $this->db->jdate($obj->date_modification);
1824  $this->user_creation = $obj->fk_user_creat;
1825  $this->user_modification = $obj->fk_user_modif;
1826 
1827  $this->address = $obj->address;
1828  $this->zip = $obj->zip;
1829  $this->town = $obj->town;
1830 
1831  $this->country_id = $obj->country_id;
1832  $this->country_code = $obj->country_id ? $obj->country_code : '';
1833  $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1834 
1835  $this->state_id = $obj->state_id;
1836  $this->state_code = $obj->state_code;
1837  $this->region_id = $obj->region_id;
1838  $this->region_code = $obj->region_code;
1839  $this->state = ($obj->state != '-' ? $obj->state : '');
1840 
1841  $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1842  $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1843  $this->stcomm_id = $obj->fk_stcomm; // id status prospect
1844  $this->status_prospect_label = $label; // label status prospect
1845  $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
1846 
1847  $this->email = $obj->email;
1848  $this->socialnetworks = (array) json_decode($obj->socialnetworks, true);
1849 
1850  $this->url = $obj->url;
1851  $this->phone = $obj->phone;
1852  $this->fax = $obj->fax;
1853 
1854  $this->parent = $obj->parent;
1855 
1856  $this->idprof1 = $obj->idprof1;
1857  $this->idprof2 = $obj->idprof2;
1858  $this->idprof3 = $obj->idprof3;
1859  $this->idprof4 = $obj->idprof4;
1860  $this->idprof5 = $obj->idprof5;
1861  $this->idprof6 = $obj->idprof6;
1862 
1863  $this->capital = $obj->capital;
1864 
1865  $this->code_client = $obj->code_client;
1866  $this->code_fournisseur = $obj->code_fournisseur;
1867 
1868  $this->code_compta = $obj->code_compta; // For backward compatibility
1869  $this->code_compta_client = $obj->code_compta;
1870  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1871 
1872  $this->barcode = $obj->barcode;
1873 
1874  $this->tva_assuj = $obj->tva_assuj;
1875  $this->tva_intra = $obj->tva_intra;
1876  $this->status = $obj->status;
1877 
1878  // Local Taxes
1879  $this->localtax1_assuj = $obj->localtax1_assuj;
1880  $this->localtax2_assuj = $obj->localtax2_assuj;
1881 
1882  $this->localtax1_value = $obj->localtax1_value;
1883  $this->localtax2_value = $obj->localtax2_value;
1884 
1885  $this->typent_id = $obj->typent_id;
1886  $this->typent_code = $obj->typent_code;
1887 
1888  $this->effectif_id = $obj->effectif_id;
1889  $this->effectif = $obj->effectif_id ? $obj->effectif : '';
1890 
1891  $this->forme_juridique_code = $obj->forme_juridique_code;
1892  $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1893 
1894  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1895 
1896  $this->prefix_comm = $obj->prefix_comm;
1897 
1898  $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
1899  $this->remise_supplier_percent = $obj->remise_supplier;
1900 
1901  $this->mode_reglement_id = $obj->mode_reglement;
1902  $this->cond_reglement_id = $obj->cond_reglement;
1903  $this->deposit_percent = $obj->deposit_percent;
1904  $this->transport_mode_id = $obj->transport_mode;
1905  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1906  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1907  $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
1908  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1909  $this->fk_account = $obj->fk_account;
1910 
1911  $this->client = $obj->client;
1912  $this->fournisseur = $obj->fournisseur;
1913 
1914  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1915  $this->note_private = $obj->note_private;
1916  $this->note_public = $obj->note_public;
1917  $this->model_pdf = $obj->model_pdf;
1918  $this->modelpdf = $obj->model_pdf; // deprecated
1919  $this->default_lang = $obj->default_lang;
1920  $this->logo = $obj->logo;
1921  $this->logo_squarred = $obj->logo_squarred;
1922 
1923  $this->webservices_url = $obj->webservices_url;
1924  $this->webservices_key = $obj->webservices_key;
1925 
1926  $this->accountancy_code_buy = $obj->accountancy_code_buy;
1927  $this->accountancy_code_sell = $obj->accountancy_code_sell;
1928 
1929  $this->outstanding_limit = $obj->outstanding_limit;
1930  $this->order_min_amount = $obj->order_min_amount;
1931  $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
1932 
1933  // multiprix
1934  $this->price_level = $obj->price_level;
1935 
1936  // warehouse
1937  $this->fk_warehouse = $obj->fk_warehouse;
1938 
1939  $this->import_key = $obj->import_key;
1940 
1941  //Incoterms
1942  $this->fk_incoterms = $obj->fk_incoterms;
1943  $this->location_incoterms = $obj->location_incoterms;
1944  $this->label_incoterms = $obj->label_incoterms;
1945 
1946  // multicurrency
1947  $this->fk_multicurrency = $obj->fk_multicurrency;
1948  $this->multicurrency_code = $obj->multicurrency_code;
1949  $this->model_pdf = $obj->model_pdf;
1950 
1951  $result = 1;
1952 
1953  // fetch optionals attributes and labels
1954  $this->fetch_optionals();
1955  } else {
1956  $result = 0;
1957  }
1958 
1959  $this->db->free($resql);
1960  } else {
1961  $this->error = $this->db->lasterror();
1962  $this->errors[] = $this->db->lasterror();
1963  $result = -3;
1964  }
1965 
1966  // Use first price level if level not defined for third party
1967  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
1968  $this->price_level = 1;
1969  }
1970 
1971  return $result;
1972  }
1973 
1982  public function delete($id, User $fuser = null, $call_trigger = 1)
1983  {
1984  global $langs, $conf, $user;
1985 
1986  if (empty($fuser)) {
1987  $fuser = $user;
1988  }
1989 
1990  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1991 
1992  $entity = isset($this->entity) ? $this->entity : $conf->entity;
1993 
1994  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1995  $error = 0;
1996 
1997  // Test if child exists
1998  $objectisused = $this->isObjectUsed($id);
1999  if (empty($objectisused)) {
2000  $this->db->begin();
2001 
2002  // User is mandatory for trigger call
2003  if (!$error && $call_trigger) {
2004  // Call trigger
2005  $result = $this->call_trigger('COMPANY_DELETE', $fuser);
2006  if ($result < 0) {
2007  $error++;
2008  }
2009  // End call triggers
2010  }
2011 
2012  if (!$error) {
2013  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2014  $static_cat = new Categorie($this->db);
2015  $toute_categs = array();
2016 
2017  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
2018  if ($this->client || $this->prospect) {
2019  $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
2020  }
2021  if ($this->fournisseur) {
2022  $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
2023  }
2024 
2025  // Remove each "Categorie"
2026  foreach ($toute_categs as $type => $categs_type) {
2027  foreach ($categs_type as $cat) {
2028  $cat->del_type($this, $type);
2029  }
2030  }
2031  }
2032 
2033  if (!$error) {
2034  foreach ($this->childtablesoncascade as $tabletodelete) {
2035  $deleteFromObject = explode(':', $tabletodelete);
2036  if (count($deleteFromObject) >= 2) {
2037  $className = str_replace('@', '', $deleteFromObject[0]);
2038  $filepath = $deleteFromObject[1];
2039  $columnName = $deleteFromObject[2];
2040  if (dol_include_once($filepath)) {
2041  $child_object = new $className($this->db);
2042  $result = $child_object->deleteByParentField($id, $columnName);
2043  if ($result < 0) {
2044  $error++;
2045  $this->errors[] = $child_object->error;
2046  break;
2047  }
2048  } else {
2049  $error++;
2050  $this->errors[] = 'Cannot include child class file '.$filepath;
2051  break;
2052  }
2053  } else {
2054  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
2055  $sql .= " WHERE fk_soc = ".((int) $id);
2056  if (!$this->db->query($sql)) {
2057  $error++;
2058  $this->errors[] = $this->db->lasterror();
2059  break;
2060  }
2061  }
2062  }
2063  }
2064 
2065  // Removed extrafields
2066  if (!$error) {
2067  $result = $this->deleteExtraFields();
2068  if ($result < 0) {
2069  $error++;
2070  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
2071  }
2072  }
2073 
2074  // Remove links to subsidiaries companies
2075  if (!$error) {
2076  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2077  $sql .= " SET parent = NULL";
2078  $sql .= " WHERE parent = ".((int) $id);
2079  if (!$this->db->query($sql)) {
2080  $error++;
2081  $this->errors[] = $this->db->lasterror();
2082  }
2083  }
2084 
2085  // Remove third party
2086  if (!$error) {
2087  if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
2088  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
2089  $sql .= " WHERE fk_soc = ".((int) $id);
2090  if (!$this->db->query($sql)) {
2091  $error++;
2092  $this->errors[] = $this->db->lasterror();
2093  }
2094  }
2095 
2096  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
2097  $sql .= " WHERE rowid = ".((int) $id);
2098  if (!$this->db->query($sql)) {
2099  $error++;
2100  $this->errors[] = $this->db->lasterror();
2101  }
2102  }
2103 
2104  if (!$error) {
2105  $this->db->commit();
2106 
2107  // Delete directory
2108  if (!empty($conf->societe->multidir_output[$entity])) {
2109  $docdir = $conf->societe->multidir_output[$entity]."/".$id;
2110  if (dol_is_dir($docdir)) {
2111  dol_delete_dir_recursive($docdir);
2112  }
2113  }
2114 
2115  return 1;
2116  } else {
2117  dol_syslog($this->error, LOG_ERR);
2118  $this->db->rollback();
2119  return -1;
2120  }
2121  } else {
2122  dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
2123  }
2124  return 0;
2125  }
2126 
2127  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2133  public function set_as_client()
2134  {
2135  global $conf;
2136  // phpcs:enable
2137  if ($this->id) {
2138  $newclient = 1;
2139  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) {
2140  $newclient = 3; //If prospect, we keep prospect tag
2141  }
2142  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2143  $sql .= " SET client = ".((int) $newclient);
2144  $sql .= " WHERE rowid = ".((int) $this->id);
2145 
2146  $resql = $this->db->query($sql);
2147  if ($resql) {
2148  $this->client = $newclient;
2149  return 1;
2150  } else {
2151  return -1;
2152  }
2153  }
2154  return 0;
2155  }
2156 
2157  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2166  public function set_remise_client($remise, $note, User $user)
2167  {
2168  // phpcs:enable
2169  global $conf, $langs;
2170 
2171  // Parameter cleaning
2172  $note = trim($note);
2173  if (!$note) {
2174  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2175  return -2;
2176  }
2177 
2178  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
2179 
2180  if ($this->id) {
2181  $this->db->begin();
2182 
2183  $now = dol_now();
2184 
2185  // Position current discount
2186  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2187  $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
2188  $sql .= " WHERE rowid = ".((int) $this->id);
2189  $resql = $this->db->query($sql);
2190  if (!$resql) {
2191  $this->db->rollback();
2192  $this->error = $this->db->error();
2193  return -1;
2194  }
2195 
2196  // Writes trace in discount history
2197  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
2198  $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
2199  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2200  $sql .= " '".$this->db->escape($note)."',";
2201  $sql .= " ".((int) $user->id);
2202  $sql .= ")";
2203 
2204  $resql = $this->db->query($sql);
2205  if (!$resql) {
2206  $this->db->rollback();
2207  $this->error = $this->db->lasterror();
2208  return -1;
2209  }
2210 
2211  $this->db->commit();
2212  return 1;
2213  }
2214  }
2215 
2216  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2225  public function set_remise_supplier($remise, $note, User $user)
2226  {
2227  // phpcs:enable
2228  global $conf, $langs;
2229 
2230  // Parameter cleaning
2231  $note = trim($note);
2232  if (!$note) {
2233  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
2234  return -2;
2235  }
2236 
2237  dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
2238 
2239  if ($this->id) {
2240  $this->db->begin();
2241 
2242  $now = dol_now();
2243 
2244  // Position current discount
2245  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
2246  $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
2247  $sql .= " WHERE rowid = ".((int) $this->id);
2248  $resql = $this->db->query($sql);
2249  if (!$resql) {
2250  $this->db->rollback();
2251  $this->error = $this->db->error();
2252  return -1;
2253  }
2254 
2255  // Writes trace in discount history
2256  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
2257  $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
2258  $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
2259  $sql .= " '".$this->db->escape($note)."',";
2260  $sql .= " ".((int) $user->id);
2261  $sql .= ")";
2262 
2263  $resql = $this->db->query($sql);
2264  if (!$resql) {
2265  $this->db->rollback();
2266  $this->error = $this->db->lasterror();
2267  return -1;
2268  }
2269 
2270  $this->db->commit();
2271  return 1;
2272  }
2273  }
2274 
2275  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2286  public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0)
2287  {
2288  // phpcs:enable
2289  global $langs;
2290 
2291  // Clean parameters
2292  $remise = price2num($remise);
2293  $desc = trim($desc);
2294 
2295  // Check parameters
2296  if (!($remise > 0)) {
2297  $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
2298  return -1;
2299  }
2300  if (!$desc) {
2301  $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
2302  return -2;
2303  }
2304 
2305  if ($this->id > 0) {
2306  // Clean vat code
2307  $reg = array();
2308  $vat_src_code = '';
2309  if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
2310  $vat_src_code = $reg[1];
2311  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
2312  }
2313 
2314  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2315 
2316  $discount = new DiscountAbsolute($this->db);
2317  $discount->fk_soc = $this->id;
2318 
2319  $discount->discount_type = $discount_type;
2320 
2321  $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
2322  $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
2323  $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
2324 
2325  $discount->tva_tx = price2num($vatrate);
2326  $discount->vat_src_code = $vat_src_code;
2327 
2328  $discount->description = $desc;
2329 
2330  $result = $discount->create($user);
2331  if ($result > 0) {
2332  return $result;
2333  } else {
2334  $this->error = $discount->error;
2335  return -3;
2336  }
2337  } else {
2338  return 0;
2339  }
2340  }
2341 
2351  public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
2352  {
2353  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2354 
2355  $discountstatic = new DiscountAbsolute($this->db);
2356  $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
2357  if ($result >= 0) {
2358  return $result;
2359  } else {
2360  $this->error = $discountstatic->error;
2361  return -1;
2362  }
2363  }
2364 
2374  public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
2375  {
2376  global $conf;
2377 
2378  $reparray = array();
2379 
2380  $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";
2381  $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
2382  $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
2383  if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2384  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2385  $sql .= " WHERE ((ug.fk_user = sc.fk_user";
2386  $sql .= " AND ug.entity = ".$conf->entity.")";
2387  $sql .= " OR u.admin = 1)";
2388  } else {
2389  $sql .= " WHERE entity in (0, ".$conf->entity.")";
2390  }
2391 
2392  $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
2393  if (empty($sortfield) && empty($sortorder)) {
2394  $sortfield = 'u.lastname,u.firstname';
2395  $sortorder = 'ASC,ASC';
2396  }
2397  $sql .= $this->db->order($sortfield, $sortorder);
2398 
2399  $resql = $this->db->query($sql);
2400  if ($resql) {
2401  $num = $this->db->num_rows($resql);
2402  $i = 0;
2403  while ($i < $num) {
2404  $obj = $this->db->fetch_object($resql);
2405 
2406  if (empty($mode)) {
2407  $reparray[$i]['id'] = $obj->rowid;
2408  $reparray[$i]['lastname'] = $obj->lastname;
2409  $reparray[$i]['firstname'] = $obj->firstname;
2410  $reparray[$i]['email'] = $obj->email;
2411  $reparray[$i]['phone'] = $obj->office_phone;
2412  $reparray[$i]['office_phone'] = $obj->office_phone;
2413  $reparray[$i]['office_fax'] = $obj->office_fax;
2414  $reparray[$i]['user_mobile'] = $obj->user_mobile;
2415  $reparray[$i]['personal_mobile'] = $obj->personal_mobile;
2416  $reparray[$i]['job'] = $obj->job;
2417  $reparray[$i]['statut'] = $obj->status; // deprecated
2418  $reparray[$i]['status'] = $obj->status;
2419  $reparray[$i]['entity'] = $obj->entity;
2420  $reparray[$i]['login'] = $obj->login;
2421  $reparray[$i]['photo'] = $obj->photo;
2422  $reparray[$i]['gender'] = $obj->gender;
2423  } else {
2424  $reparray[] = $obj->rowid;
2425  }
2426  $i++;
2427  }
2428  return $reparray;
2429  } else {
2430  dol_print_error($this->db);
2431  return -1;
2432  }
2433  }
2434 
2442  public function setPriceLevel($price_level, User $user)
2443  {
2444  if ($this->id) {
2445  $now = dol_now();
2446 
2447  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2448  $sql .= " SET price_level = ".((int) $price_level);
2449  $sql .= " WHERE rowid = ".((int) $this->id);
2450 
2451  if (!$this->db->query($sql)) {
2452  dol_print_error($this->db);
2453  return -1;
2454  }
2455 
2456  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
2457  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
2458  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
2459 
2460  if (!$this->db->query($sql)) {
2461  dol_print_error($this->db);
2462  return -1;
2463  }
2464  return 1;
2465  }
2466  return -1;
2467  }
2468 
2469  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2477  public function add_commercial(User $user, $commid)
2478  {
2479  // phpcs:enable
2480  $error = 0;
2481 
2482  if ($this->id > 0 && $commid > 0) {
2483  $this->db->begin();
2484 
2485  if (!$error) {
2486  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
2487  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2488 
2489  $resql = $this->db->query($sql);
2490  if (!$resql) {
2491  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2492  $error++;
2493  }
2494  }
2495 
2496  if (!$error) {
2497  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
2498  $sql .= " (fk_soc, fk_user)";
2499  $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
2500 
2501  $resql = $this->db->query($sql);
2502  if (!$resql) {
2503  dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
2504  $error++;
2505  }
2506  }
2507 
2508  if (!$error) {
2509  $this->context = array('commercial_modified' => $commid);
2510 
2511  $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
2512  if ($result < 0) {
2513  $error++;
2514  }
2515  }
2516 
2517  if (!$error) {
2518  $this->db->commit();
2519  return 1;
2520  } else {
2521  $this->db->rollback();
2522  return -1;
2523  }
2524  }
2525 
2526  return 0;
2527  }
2528 
2529  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2537  public function del_commercial(User $user, $commid)
2538  {
2539  // phpcs:enable
2540  $error = 0;
2541  $this->context = array('commercial_modified'=>$commid);
2542 
2543  $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
2544  if ($result < 0) {
2545  $error++;
2546  }
2547 
2548  if ($this->id > 0 && $commid > 0) {
2549  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
2550  $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
2551 
2552  if (!$this->db->query($sql)) {
2553  dol_syslog(get_class($this)."::del_commercial Erreur");
2554  }
2555  }
2556  }
2557 
2558 
2571  public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
2572  {
2573  global $conf, $langs, $hookmanager;
2574 
2575  if (!empty($conf->dol_no_mouse_hover)) {
2576  $notooltip = 1; // Force disable tooltips
2577  }
2578 
2579  $name = $this->name ? $this->name : $this->nom;
2580 
2581  if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
2582  if (empty($option) && $this->client > 0) {
2583  $option = 'customer';
2584  }
2585  if (empty($option) && $this->fournisseur > 0) {
2586  $option = 'supplier';
2587  }
2588  }
2589 
2590  if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
2591  $code = '';
2592  if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2)) {
2593  $code = $this->code_client.' - ';
2594  }
2595 
2596  if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3)) {
2597  $code .= $this->code_fournisseur.' - ';
2598  }
2599 
2600  if ($code) {
2601  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
2602  $name = $code.' '.$name;
2603  } else {
2604  $name = $code;
2605  }
2606  }
2607  }
2608 
2609  if (!empty($this->name_alias) && empty($noaliasinname)) {
2610  $name .= ' ('.$this->name_alias.')';
2611  }
2612 
2613  $result = ''; $label = ''; $label2 = '';
2614  $linkstart = ''; $linkend = '';
2615 
2616  if (!empty($this->logo) && class_exists('Form')) {
2617  $label .= '<div class="photointooltip floatright">';
2618  $label .= 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.
2619  $label .= '</div>';
2620  //$label .= '<div style="clear: both;"></div>';
2621  } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
2622  /*$label.= '<div class="photointooltip">';
2623  $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.
2624  $label.= '</div><div style="clear: both;"></div>';*/
2625  }
2626 
2627  $label .= '<div class="centpercent">';
2628 
2629  if ($option == 'customer' || $option == 'compta' || $option == 'category') {
2630  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
2631  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2632  } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2633  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
2634  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2635  } elseif ($option == 'supplier' || $option == 'category_supplier') {
2636  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
2637  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2638  } elseif ($option == 'agenda') {
2639  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2640  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2641  } elseif ($option == 'project') {
2642  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2643  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2644  } elseif ($option == 'margin') {
2645  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2646  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2647  } elseif ($option == 'contact') {
2648  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2649  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2650  } elseif ($option == 'ban') {
2651  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2652  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2653  }
2654 
2655  // By default
2656  if (empty($linkstart)) {
2657  $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
2658  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2659  }
2660  if (isset($this->status)) {
2661  $label .= ' '.$this->getLibStatut(5);
2662  }
2663 
2664  $label .= '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag($this->name);
2665  if (!empty($this->name_alias)) {
2666  $label .= ' ('.dol_escape_htmltag($this->name_alias).')';
2667  }
2668  if ($this->email) {
2669  $label .= '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
2670  }
2671  if (!empty($this->phone) || !empty($this->fax)) {
2672  $phonelist = array();
2673  if ($this->phone) {
2674  $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
2675  }
2676  if ($this->fax) {
2677  $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
2678  }
2679  $label .= '<br>'.implode('&nbsp;', $phonelist);
2680  }
2681 
2682  if (!empty($this->address)) {
2683  $label2 .= '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
2684  } elseif (!empty($this->country_code)) {
2685  $label2 .= '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
2686  }
2687  if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
2688  $label2 .= '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
2689  }
2690 
2691  if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
2692  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
2693  $label2 .= '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
2694  }
2695  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
2696  $label2 .= '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
2697  }
2698  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
2699  $label2 .= '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
2700  }
2701  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
2702  $label2 .= '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
2703  }
2704  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
2705  $label2 .= '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
2706  }
2707  if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
2708  $label2 .= '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
2709  }
2710  }
2711  if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
2712  $label2 .= '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
2713  }
2714  if (!empty($this->code_fournisseur) && $this->fournisseur) {
2715  $label2 .= '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
2716  }
2717  if (!empty($conf->accounting->enabled) && ($this->client == 1 || $this->client == 3)) {
2718  $label2 .= '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
2719  }
2720  if (!empty($conf->accounting->enabled) && $this->fournisseur) {
2721  $label2 .= '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
2722  }
2723  $label .= ($label2 ? '<br>'.$label2 : '').'</div>';
2724 
2725  // Add type of canvas
2726  $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
2727  // Add param to save lastsearch_values or not
2728  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2729  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2730  $add_save_lastsearch_values = 1;
2731  }
2732  if ($add_save_lastsearch_values) {
2733  $linkstart .= '&save_lastsearch_values=1';
2734  }
2735  $linkstart .= '"';
2736 
2737  $linkclose = '';
2738  if (empty($notooltip)) {
2739  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2740  $label = $langs->trans("ShowCompany");
2741  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2742  }
2743  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
2744  $linkclose .= ' class="classfortooltip refurl"';
2745  $target_value = array('_self', '_blank', '_parent', '_top');
2746  if (in_array($target, $target_value)) {
2747  $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
2748  }
2749  }
2750  $linkstart .= $linkclose.'>';
2751  $linkend = '</a>';
2752 
2753  global $user;
2754  if (empty($user->rights->societe->client->voir) && $user->socid > 0 && $this->id != $user->socid) {
2755  $linkstart = '';
2756  $linkend = '';
2757  }
2758 
2759  $result .= $linkstart;
2760  if ($withpicto) {
2761  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
2762  }
2763  if ($withpicto != 2) {
2764  $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
2765  }
2766  $result .= $linkend;
2767 
2768  global $action;
2769  $hookmanager->initHooks(array('thirdpartydao'));
2770  $parameters = array(
2771  'id'=>$this->id,
2772  'getnomurl' => &$result,
2773  'withpicto '=> $withpicto,
2774  'option'=> $option,
2775  'maxlen'=> $maxlen,
2776  'notooltip'=> $notooltip,
2777  'save_lastsearch_value'=> $save_lastsearch_value
2778  );
2779  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2780  if ($reshook > 0) {
2781  $result = $hookmanager->resPrint;
2782  } else {
2783  $result .= $hookmanager->resPrint;
2784  }
2785 
2786  return $result;
2787  }
2788 
2798  public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
2799  {
2800  global $conf, $langs;
2801 
2802  $s = '';
2803  if (empty($option) || preg_match('/prospect/', $option)) {
2804  if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
2805  $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.'>';
2806  }
2807  }
2808  if (empty($option) || preg_match('/customer/', $option)) {
2809  if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
2810  $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.'>';
2811  }
2812  }
2813  if (empty($option) || preg_match('/supplier/', $option)) {
2814  if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $this->fournisseur) {
2815  $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.'>';
2816  }
2817  }
2818  return $s;
2819  }
2820 
2821 
2828  public function getLibStatut($mode = 0)
2829  {
2830  return $this->LibStatut($this->status, $mode);
2831  }
2832 
2833  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2841  public function LibStatut($status, $mode = 0)
2842  {
2843  // phpcs:enable
2844  global $langs;
2845  $langs->load('companies');
2846 
2847  $statusType = 'status4';
2848  if ($status == 0) {
2849  $statusType = 'status6';
2850  }
2851 
2852  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2853  $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2854  $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
2855  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
2856  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
2857  }
2858 
2859  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2860  }
2861 
2862  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2869  public function thirdparty_and_contact_email_array($addthirdparty = 0)
2870  {
2871  // phpcs:enable
2872  global $langs;
2873 
2874  $contact_emails = $this->contact_property_array('email', 1);
2875  if ($this->email && $addthirdparty) {
2876  if (empty($this->name)) {
2877  $this->name = $this->nom;
2878  }
2879  $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">";
2880  }
2881  //var_dump($contact_emails)
2882  return $contact_emails;
2883  }
2884 
2885  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2892  {
2893  // phpcs:enable
2894  global $langs;
2895 
2896  $contact_phone = $this->contact_property_array('mobile');
2897 
2898  if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
2899  if (empty($this->name)) {
2900  $this->name = $this->nom;
2901  }
2902  // TODO: Tester si tel non deja present dans tableau contact
2903  $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
2904  }
2905  return $contact_phone;
2906  }
2907 
2908  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2916  public function contact_property_array($mode = 'email', $hidedisabled = 0)
2917  {
2918  // phpcs:enable
2919  global $langs;
2920 
2921  $contact_property = array();
2922 
2923 
2924  $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
2925  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
2926  $sql .= " WHERE fk_soc = ".((int) $this->id);
2927  $sql .= " ORDER BY lastname, firstname";
2928 
2929  $resql = $this->db->query($sql);
2930  if ($resql) {
2931  $nump = $this->db->num_rows($resql);
2932  if ($nump) {
2933  $sepa = "("; $sepb = ")";
2934  if ($mode == 'email') {
2935  //$sepa="&lt;"; $sepb="&gt;";
2936  $sepa = "<"; $sepb = ">";
2937  }
2938  $i = 0;
2939  while ($i < $nump) {
2940  $obj = $this->db->fetch_object($resql);
2941  if ($mode == 'email') {
2942  $property = $obj->email;
2943  } elseif ($mode == 'mobile') {
2944  $property = $obj->phone_mobile;
2945  } else {
2946  $property = $obj->$mode;
2947  }
2948 
2949  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2950  if ($obj->status == 1 || empty($hidedisabled)) {
2951  if (empty($property)) {
2952  if ($mode == 'email') {
2953  $property = $langs->transnoentitiesnoconv("NoEMail");
2954  } elseif ($mode == 'mobile') {
2955  $property = $langs->transnoentitiesnoconv("NoMobilePhone");
2956  }
2957  }
2958 
2959  if (!empty($obj->poste)) {
2960  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2961  } else {
2962  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2963  }
2964  }
2965  $i++;
2966  }
2967  }
2968  } else {
2969  dol_print_error($this->db);
2970  }
2971  return $contact_property;
2972  }
2973 
2974 
2975  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2981  public function contact_array()
2982  {
2983  // phpcs:enable
2984  $contacts = array();
2985 
2986  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
2987  $resql = $this->db->query($sql);
2988  if ($resql) {
2989  $nump = $this->db->num_rows($resql);
2990  if ($nump) {
2991  $i = 0;
2992  while ($i < $nump) {
2993  $obj = $this->db->fetch_object($resql);
2994  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
2995  $i++;
2996  }
2997  }
2998  } else {
2999  dol_print_error($this->db);
3000  }
3001  return $contacts;
3002  }
3003 
3004  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3010  public function contact_array_objects()
3011  {
3012  // phpcs:enable
3013  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
3014  $contacts = array();
3015 
3016  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
3017  $resql = $this->db->query($sql);
3018  if ($resql) {
3019  $nump = $this->db->num_rows($resql);
3020  if ($nump) {
3021  $i = 0;
3022  while ($i < $nump) {
3023  $obj = $this->db->fetch_object($resql);
3024  $contact = new Contact($this->db);
3025  $contact->fetch($obj->rowid);
3026  $contacts[] = $contact;
3027  $i++;
3028  }
3029  }
3030  } else {
3031  dol_print_error($this->db);
3032  }
3033  return $contacts;
3034  }
3035 
3036  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3044  public function contact_get_property($rowid, $mode)
3045  {
3046  // phpcs:enable
3047  $contact_property = '';
3048 
3049  if (empty($rowid)) {
3050  return '';
3051  }
3052 
3053  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
3054  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
3055  $sql .= " WHERE rowid = ".((int) $rowid);
3056 
3057  $resql = $this->db->query($sql);
3058  if ($resql) {
3059  $nump = $this->db->num_rows($resql);
3060 
3061  if ($nump) {
3062  $obj = $this->db->fetch_object($resql);
3063 
3064  if ($mode == 'email') {
3065  $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
3066  } elseif ($mode == 'mobile') {
3067  $contact_property = $obj->phone_mobile;
3068  }
3069  }
3070  return $contact_property;
3071  } else {
3072  dol_print_error($this->db);
3073  }
3074  }
3075 
3076 
3077  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3084  public function display_rib($mode = 'label')
3085  {
3086  // phpcs:enable
3087  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3088 
3089  $bac = new CompanyBankAccount($this->db);
3090  $bac->fetch(0, $this->id);
3091 
3092  if ($bac->id > 0) { // If a bank account has been found for company $this->id
3093  if ($mode == 'label') {
3094  return $bac->getRibLabel(true);
3095  } elseif ($mode == 'rum') {
3096  if (empty($bac->rum)) {
3097  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
3098  $prelevement = new BonPrelevement($this->db);
3099  $bac->fetch_thirdparty();
3100  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
3101  }
3102  return $bac->rum;
3103  } elseif ($mode == 'format') {
3104  return $bac->frstrecur;
3105  } else {
3106  return 'BadParameterToFunctionDisplayRib';
3107  }
3108  } else {
3109  return '';
3110  }
3111  }
3112 
3113  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3119  public function get_all_rib()
3120  {
3121  // phpcs:enable
3122  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3123  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
3124  $result = $this->db->query($sql);
3125  if (!$result) {
3126  $this->error++;
3127  $this->errors[] = $this->db->lasterror;
3128  return 0;
3129  } else {
3130  $num_rows = $this->db->num_rows($result);
3131  $rib_array = array();
3132  if ($num_rows) {
3133  while ($obj = $this->db->fetch_object($result)) {
3134  $rib = new CompanyBankAccount($this->db);
3135  $rib->fetch($obj->rowid);
3136  $rib_array[] = $rib;
3137  }
3138  }
3139  return $rib_array;
3140  }
3141  }
3142 
3143  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3152  public function get_codeclient($objsoc = 0, $type = 0)
3153  {
3154  // phpcs:enable
3155  global $conf;
3156  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3157  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3158 
3159  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3160  foreach ($dirsociete as $dirroot) {
3161  $res = dol_include_once($dirroot.$module.'.php');
3162  if ($res) {
3163  break;
3164  }
3165  }
3166  $mod = new $module();
3167 
3168  $this->code_client = $mod->getNextValue($objsoc, $type);
3169  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
3170 
3171  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
3172  }
3173  }
3174 
3175  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3184  public function get_codefournisseur($objsoc = 0, $type = 1)
3185  {
3186  // phpcs:enable
3187  global $conf;
3188  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3189  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3190 
3191  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3192  foreach ($dirsociete as $dirroot) {
3193  $res = dol_include_once($dirroot.$module.'.php');
3194  if ($res) {
3195  break;
3196  }
3197  }
3198  $mod = new $module();
3199 
3200  $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
3201 
3202  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3203  }
3204  }
3205 
3206  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3213  public function codeclient_modifiable()
3214  {
3215  // phpcs:enable
3216  global $conf;
3217  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3218  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3219 
3220  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3221  foreach ($dirsociete as $dirroot) {
3222  $res = dol_include_once($dirroot.$module.'.php');
3223  if ($res) {
3224  break;
3225  }
3226  }
3227 
3228  $mod = new $module();
3229 
3230  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
3231  if ($mod->code_modifiable_null && !$this->code_client) {
3232  return 1;
3233  }
3234  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
3235  return 1;
3236  }
3237  if ($mod->code_modifiable) {
3238  return 1; // A mettre en dernier
3239  }
3240  return 0;
3241  } else {
3242  return 0;
3243  }
3244  }
3245 
3246 
3247  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3253  public function codefournisseur_modifiable()
3254  {
3255  // phpcs:enable
3256  global $conf;
3257  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3258  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3259 
3260  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3261  foreach ($dirsociete as $dirroot) {
3262  $res = dol_include_once($dirroot.$module.'.php');
3263  if ($res) {
3264  break;
3265  }
3266  }
3267 
3268  $mod = new $module();
3269 
3270  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
3271  if ($mod->code_modifiable_null && !$this->code_fournisseur) {
3272  return 1;
3273  }
3274  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
3275  return 1;
3276  }
3277  if ($mod->code_modifiable) {
3278  return 1; // A mettre en dernier
3279  }
3280  return 0;
3281  } else {
3282  return 0;
3283  }
3284  }
3285 
3286 
3287  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3299  public function check_codeclient()
3300  {
3301  // phpcs:enable
3302  global $conf;
3303  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3304  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3305 
3306  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3307  foreach ($dirsociete as $dirroot) {
3308  $res = dol_include_once($dirroot.$module.'.php');
3309  if ($res) {
3310  break;
3311  }
3312  }
3313 
3314  $mod = new $module();
3315 
3316  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
3317  $result = $mod->verif($this->db, $this->code_client, $this, 0);
3318  if ($result) { // If error
3319  $this->error = $mod->error;
3320  $this->errors = $mod->errors;
3321  }
3322  return $result;
3323  } else {
3324  return 0;
3325  }
3326  }
3327 
3328  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3340  public function check_codefournisseur()
3341  {
3342  // phpcs:enable
3343  global $conf;
3344  if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
3345  $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
3346 
3347  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3348  foreach ($dirsociete as $dirroot) {
3349  $res = dol_include_once($dirroot.$module.'.php');
3350  if ($res) {
3351  break;
3352  }
3353  }
3354 
3355  $mod = new $module();
3356 
3357  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
3358  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
3359  if ($result) { // If error
3360  $this->error = $mod->error;
3361  $this->errors = $mod->errors;
3362  }
3363  return $result;
3364  } else {
3365  return 0;
3366  }
3367  }
3368 
3369  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3378  public function get_codecompta($type)
3379  {
3380  // phpcs:enable
3381  global $conf;
3382 
3383  if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3384  $res = false;
3385  $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3386  foreach ($dirsociete as $dirroot) {
3387  $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
3388  if ($res) {
3389  break;
3390  }
3391  }
3392 
3393  if ($res) {
3394  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3395  $mod = new $classname;
3396 
3397  // Set code count in $mod->code
3398  $result = $mod->get_code($this->db, $this, $type);
3399 
3400  if ($type == 'customer') {
3401  $this->code_compta_client = $mod->code;
3402  $this->code_compta = $this->code_compta_client; // For backward compatibility
3403  } elseif ($type == 'supplier') {
3404  $this->code_compta_fournisseur = $mod->code;
3405  }
3406 
3407  return $result;
3408  } else {
3409  $this->error = 'ErrorAccountancyCodeNotDefined';
3410  return -1;
3411  }
3412  } else {
3413  if ($type == 'customer') {
3414  $this->code_compta_client = '';
3415  $this->code_compta = '';
3416  } elseif ($type == 'supplier') {
3417  $this->code_compta_fournisseur = '';
3418  }
3419 
3420  return 0;
3421  }
3422  }
3423 
3430  public function setParent($id)
3431  {
3432  dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
3433 
3434  if ($this->id) {
3435  // Check if the id we want to add as parent has not already one parent that is the current id we try to update
3436  if ($id > 0) {
3437  $sameparent = $this->validateFamilyTree($id, $this->id, 0);
3438  if ($sameparent < 0) {
3439  return -1;
3440  }
3441  if ($sameparent == 1) {
3442  setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
3443  return -1;
3444  }
3445  }
3446 
3447  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
3448 
3449  $resql = $this->db->query($sql);
3450  if ($resql) {
3451  $this->parent = $id;
3452  return 1;
3453  } else {
3454  return -1;
3455  }
3456  } else {
3457  return -1;
3458  }
3459  }
3460 
3469  public function validateFamilyTree($idparent, $idchild, $counter = 0)
3470  {
3471  if ($counter > 100) {
3472  dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
3473  }
3474 
3475  $sql = 'SELECT s.parent';
3476  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
3477  $sql .= ' WHERE rowid = '.((int) $idparent);
3478  $resql = $this->db->query($sql);
3479  if ($resql) {
3480  $obj = $this->db->fetch_object($resql);
3481 
3482  if ($obj->parent == '') {
3483  return 0;
3484  } elseif ($obj->parent == $idchild) {
3485  return 1;
3486  } else {
3487  $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
3488  }
3489  return $sameparent;
3490  } else {
3491  return -1;
3492  }
3493  }
3494 
3502  public function getParentsForCompany($company_id, $parents = [])
3503  {
3504  global $langs;
3505 
3506  if ($company_id > 0) {
3507  $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = $company_id";
3508  $resql = $this->db->query($sql);
3509  if ($resql) {
3510  if ($obj = $this->db->fetch_object($resql)) {
3511  $parent = $obj->parent;
3512  if ($parent > 0 && !in_array($parent, $parents)) {
3513  $parents[] = $parent;
3514  return $this->getParentsForCompany($parent, $parents);
3515  } else {
3516  return $parents;
3517  }
3518  }
3519  $this->db->free($resql);
3520  } else {
3521  setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
3522  }
3523  }
3524  }
3525 
3526  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3533  public function id_prof_verifiable($idprof)
3534  {
3535  // phpcs:enable
3536  global $conf;
3537 
3538  switch ($idprof) {
3539  case 1:
3540  $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
3541  break;
3542  case 2:
3543  $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
3544  break;
3545  case 3:
3546  $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
3547  break;
3548  case 4:
3549  $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
3550  break;
3551  case 5:
3552  $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
3553  break;
3554  case 6:
3555  $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
3556  break;
3557  default:
3558  $ret = false;
3559  }
3560 
3561  return $ret;
3562  }
3563 
3564  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3573  public function id_prof_exists($idprof, $value, $socid = 0)
3574  {
3575  // phpcs:enable
3576  $field = $idprof;
3577 
3578  switch ($idprof) { // For backward compatibility
3579  case '1':
3580  case 'idprof1':
3581  $field = "siren";
3582  break;
3583  case '2':
3584  case 'idprof2':
3585  $field = "siret";
3586  break;
3587  case '3':
3588  case 'idprof3':
3589  $field = "ape";
3590  break;
3591  case '4':
3592  case 'idprof4':
3593  $field = "idprof4";
3594  break;
3595  case '5':
3596  $field = "idprof5";
3597  break;
3598  case '6':
3599  $field = "idprof6";
3600  break;
3601  }
3602 
3603  //Verify duplicate entries
3604  $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
3605  if ($socid) {
3606  $sql .= " AND rowid <> ".$socid;
3607  }
3608  $resql = $this->db->query($sql);
3609  if ($resql) {
3610  $obj = $this->db->fetch_object($resql);
3611  $count = $obj->idprof;
3612  } else {
3613  $count = 0;
3614  print $this->db->error();
3615  }
3616  $this->db->free($resql);
3617 
3618  if ($count > 0) {
3619  return true;
3620  } else {
3621  return false;
3622  }
3623  }
3624 
3625  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3634  public function id_prof_check($idprof, $soc)
3635  {
3636  // phpcs:enable
3637  global $conf;
3638 
3639  $ok = 1;
3640 
3641  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3642  return 1;
3643  }
3644 
3645  // Check SIREN if country FR
3646  if ($idprof == 1 && $soc->country_code == 'FR') {
3647  $chaine = trim($this->idprof1);
3648  $chaine = preg_replace('/(\s)/', '', $chaine);
3649 
3650  if (!is_numeric($chaine)) {
3651  return -1;
3652  }
3653  if (dol_strlen($chaine) != 9) {
3654  return -1;
3655  }
3656 
3657  // on prend chaque chiffre un par un
3658  // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
3659  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3660  // on ajoute cette valeur à la somme totale
3661  $sum = 0;
3662  for ($index = 0; $index < 9; $index++) {
3663  $number = (int) $chaine[$index];
3664  if (($index % 2) != 0) {
3665  if (($number *= 2) > 9) {
3666  $number -= 9;
3667  }
3668  }
3669  $sum += $number;
3670  }
3671 
3672  // le numéro est valide si la somme des chiffres est multiple de 10
3673  if (($sum % 10) != 0) {
3674  return -1;
3675  }
3676  }
3677 
3678  // Verifie SIRET si pays FR
3679  if ($idprof == 2 && $soc->country_code == 'FR') {
3680  $chaine = trim($this->idprof2);
3681  $chaine = preg_replace('/(\s)/', '', $chaine);
3682 
3683  if (!is_numeric($chaine)) {
3684  return -1;
3685  }
3686  if (dol_strlen($chaine) != 14) {
3687  return -1;
3688  }
3689 
3690  // on prend chaque chiffre un par un
3691  // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
3692  // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
3693  // on ajoute cette valeur à la somme totale
3694  $sum = 0;
3695  for ($index = 0; $index < 14; $index++) {
3696  $number = (int) $chaine[$index];
3697  if (($index % 2) == 0) {
3698  if (($number *= 2) > 9) {
3699  $number -= 9;
3700  }
3701  }
3702  $sum += $number;
3703  }
3704 
3705  // le numéro est valide si la somme des chiffres est multiple de 10
3706  if (($sum % 10) != 0) {
3707  return -1;
3708  }
3709  }
3710 
3711  //Verify CIF/NIF/NIE if pays ES
3712  //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
3713  if ($idprof == 1 && $soc->country_code == 'ES') {
3714  $string = trim($this->idprof1);
3715  $string = preg_replace('/(\s)/', '', $string);
3716  $string = strtoupper($string);
3717 
3718  //Check format
3719  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)) {
3720  return 0;
3721  }
3722 
3723  $num = array();
3724  for ($i = 0; $i < 9; $i++) {
3725  $num[$i] = substr($string, $i, 1);
3726  }
3727 
3728  //Check NIF
3729  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
3730  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
3731  return 1;
3732  } else {
3733  return -1;
3734  }
3735  }
3736 
3737  //algorithm checking type code CIF
3738  $sum = $num[2] + $num[4] + $num[6];
3739  for ($i = 1; $i < 8; $i += 2) {
3740  $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
3741  }
3742  $n = 10 - substr($sum, strlen($sum) - 1, 1);
3743 
3744  //Chek special NIF
3745  if (preg_match('/^[KLM]{1}/', $string)) {
3746  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
3747  return 1;
3748  } else {
3749  return -1;
3750  }
3751  }
3752 
3753  //Check CIF
3754  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
3755  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
3756  return 2;
3757  } else {
3758  return -2;
3759  }
3760  }
3761 
3762  //Check NIE T
3763  if (preg_match('/^[T]{1}/', $string)) {
3764  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
3765  return 3;
3766  } else {
3767  return -3;
3768  }
3769  }
3770 
3771  //Check NIE XYZ
3772  if (preg_match('/^[XYZ]{1}/', $string)) {
3773  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
3774  return 3;
3775  } else {
3776  return -3;
3777  }
3778  }
3779 
3780  //Can not be verified
3781  return -4;
3782  }
3783 
3784  //Verify NIF if country is PT
3785  //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3786  if ($idprof == 1 && $soc->country_code == 'PT') {
3787  $string = trim($this->idprof1);
3788  $string = preg_replace('/(\s)/', '', $string);
3789 
3790  //Check NIF
3791  if (preg_match('/(^[0-9]{9}$)/', $string)) {
3792  return 1;
3793  } else {
3794  return -1;
3795  }
3796  }
3797 
3798  return $ok;
3799  }
3800 
3801  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3810  public function id_prof_url($idprof, $thirdparty)
3811  {
3812  // phpcs:enable
3813  global $conf, $langs, $hookmanager;
3814 
3815  $url = '';
3816  $action = '';
3817 
3818  $hookmanager->initHooks(array('idprofurl'));
3819  $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
3820  $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3821  if (empty($reshook)) {
3822  if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3823  return '';
3824  }
3825 
3826  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3827  $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3828  if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3829  $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
3830  }
3831  if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3832  $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3833  }
3834  if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3835  $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3836  }
3837  if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3838  $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3839  }
3840  if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3841  $url = 'http://www.nif.pt/'.$strippedIdProf1;
3842  }
3843 
3844  if ($url) {
3845  return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
3846  }
3847  } else {
3848  return $hookmanager->resPrint;
3849  }
3850 
3851  return '';
3852  }
3853 
3854  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3860  public function has_projects()
3861  {
3862  // phpcs:enable
3863  $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
3864  $resql = $this->db->query($sql);
3865  if ($resql) {
3866  $obj = $this->db->fetch_object($resql);
3867  $count = $obj->numproj;
3868  } else {
3869  $count = 0;
3870  print $this->db->error();
3871  }
3872  $this->db->free($resql);
3873  return ($count > 0);
3874  }
3875 
3876 
3883  public function info($id)
3884  {
3885  $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
3886  $sql .= " fk_user_creat, fk_user_modif";
3887  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
3888  $sql .= " WHERE s.rowid = ".((int) $id);
3889 
3890  $result = $this->db->query($sql);
3891  if ($result) {
3892  if ($this->db->num_rows($result)) {
3893  $obj = $this->db->fetch_object($result);
3894 
3895  $this->id = $obj->rowid;
3896 
3897  $this->user_creation_id = $obj->fk_user_creat;
3898  $this->user_modification_id = $obj->fk_user_modif;
3899  $this->date_creation = $this->db->jdate($obj->datec);
3900  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
3901 
3902  $this->ref = $obj->name;
3903  }
3904 
3905  $this->db->free($result);
3906  } else {
3907  dol_print_error($this->db);
3908  }
3909  }
3910 
3916  public function isACompany()
3917  {
3918  global $conf;
3919 
3920  // Define if third party is treated as company (or not) when nature is unknown
3921  $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
3922  if (!empty($this->tva_intra)) {
3923  $isacompany = 1;
3924  } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
3925  $isacompany = 1;
3926  } elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
3927  // TODO Add a field is_a_company into dictionary
3928  if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
3929  $isacompany = 0;
3930  } else {
3931  $isacompany = 1;
3932  }
3933  }
3934 
3935  return $isacompany;
3936  }
3937 
3943  public function isInEEC()
3944  {
3945  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3946  return isInEEC($this);
3947  }
3948 
3949  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3955  public function LoadSupplierCateg()
3956  {
3957  // phpcs:enable
3958  $this->SupplierCategories = array();
3959  $sql = "SELECT rowid, label";
3960  $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
3961  $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
3962 
3963  $resql = $this->db->query($sql);
3964  if ($resql) {
3965  while ($obj = $this->db->fetch_object($resql)) {
3966  $this->SupplierCategories[$obj->rowid] = $obj->label;
3967  }
3968  return 0;
3969  } else {
3970  return -1;
3971  }
3972  }
3973 
3974  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3981  public function AddFournisseurInCategory($categorie_id)
3982  {
3983  // phpcs:enable
3984  if ($categorie_id > 0 && $this->id > 0) {
3985  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
3986  $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
3987 
3988  if ($resql = $this->db->query($sql)) {
3989  return 0;
3990  }
3991  } else {
3992  return 0;
3993  }
3994  return -1;
3995  }
3996 
3997 
3998  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4008  public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
4009  {
4010  // phpcs:enable
4011  global $conf, $user, $langs;
4012 
4013  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
4014 
4015  $name = $socname ? $socname : $member->societe;
4016  if (empty($name)) {
4017  $name = $member->getFullName($langs);
4018  }
4019 
4020  $alias = $socalias ? $socalias : '';
4021 
4022  // Positionne parametres
4023  $this->nom = $name; // TODO deprecated
4024  $this->name = $name;
4025  $this->name_alias = $alias;
4026  $this->address = $member->address;
4027  $this->zip = $member->zip;
4028  $this->town = $member->town;
4029  $this->country_code = $member->country_code;
4030  $this->country_id = $member->country_id;
4031  $this->phone = $member->phone; // Prof phone
4032  $this->email = $member->email;
4033  $this->socialnetworks = $member->socialnetworks;
4034  $this->entity = $member->entity;
4035 
4036  $this->client = 1; // A member is a customer by default
4037  $this->code_client = ($customercode ? $customercode : -1);
4038  $this->code_fournisseur = -1;
4039  $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
4040  $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
4041 
4042  $this->db->begin();
4043 
4044  // Cree et positionne $this->id
4045  $result = $this->create($user);
4046 
4047  if ($result >= 0) {
4048  // Auto-create contact on thirdparty creation
4049  if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
4050  // Fill fields needed by contact
4051  $this->name_bis = $member->lastname;
4052  $this->firstname = $member->firstname;
4053  $this->civility_id = $member->civility_id;
4054 
4055  dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
4056  $result = $this->create_individual($user);
4057 
4058  if ($result < 0) {
4059  setEventMessages($this->error, $this->errors, 'errors');
4060  $this->db->rollback();
4061  return -1;
4062  }
4063  }
4064 
4065  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
4066  $sql .= " SET fk_soc = ".((int) $this->id);
4067  $sql .= " WHERE rowid = ".((int) $member->id);
4068 
4069  $resql = $this->db->query($sql);
4070  if ($resql) {
4071  $this->db->commit();
4072  return $this->id;
4073  } else {
4074  $this->error = $this->db->error();
4075 
4076  $this->db->rollback();
4077  return -1;
4078  }
4079  } else {
4080  // $this->error deja positionne
4081  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
4082 
4083  $this->db->rollback();
4084  return $result;
4085  }
4086  }
4087 
4094  public function setMysoc(Conf $conf)
4095  {
4096  global $langs;
4097 
4098  $this->id = 0;
4099  $this->name = empty($conf->global->MAIN_INFO_SOCIETE_NOM) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOM;
4100  $this->address = empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS) ? '' : $conf->global->MAIN_INFO_SOCIETE_ADDRESS;
4101  $this->zip = empty($conf->global->MAIN_INFO_SOCIETE_ZIP) ? '' : $conf->global->MAIN_INFO_SOCIETE_ZIP;
4102  $this->town = empty($conf->global->MAIN_INFO_SOCIETE_TOWN) ? '' : $conf->global->MAIN_INFO_SOCIETE_TOWN;
4103  $this->region_code = empty($conf->global->MAIN_INFO_SOCIETE_REGION) ? '' : $conf->global->MAIN_INFO_SOCIETE_REGION;
4104  $this->object = empty($conf->global->MAIN_INFO_SOCIETE_OBJECT) ? '' : $conf->global->MAIN_INFO_SOCIETE_OBJECT;
4105 
4106  $this->note_private = empty($conf->global->MAIN_INFO_SOCIETE_NOTE) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOTE;
4107 
4108  $this->nom = $this->name; // deprecated
4109 
4110  // We define country_id, country_code and country
4111  $country_id = $country_code = $country_label = '';
4112  if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
4113  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
4114  $country_id = $tmp[0];
4115  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
4116  $country_code = $tmp[1];
4117  $country_label = $tmp[2];
4118  } else // For backward compatibility
4119  {
4120  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
4121  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4122  $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
4123  $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
4124  }
4125  }
4126  $this->country_id = $country_id;
4127  $this->country_code = $country_code;
4128  $this->country = $country_label;
4129  if (is_object($langs)) {
4130  $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
4131  }
4132 
4133  //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
4134  // We define state_id, state_code and state
4135  $state_id = 0; $state_code = $state_label = '';
4136  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
4137  $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
4138  $state_id = $tmp[0];
4139  if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
4140  $state_code = $tmp[1];
4141  $state_label = $tmp[2];
4142  } else { // For backward compatibility
4143  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);
4144  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4145  $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
4146  $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
4147  }
4148  }
4149  $this->state_id = $state_id;
4150  $this->state_code = $state_code;
4151  $this->state = $state_label;
4152  if (is_object($langs)) {
4153  $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
4154  }
4155 
4156  $this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL;
4157  $this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX;
4158  $this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB;
4159 
4160  // Social networks
4161  $this->facebook_url = empty($conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL;
4162  $this->twitter_url = empty($conf->global->MAIN_INFO_SOCIETE_TWITTER_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TWITTER_URL;
4163  $this->linkedin_url = empty($conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL;
4164  $this->instagram_url = empty($conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL;
4165  $this->youtube_url = empty($conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL;
4166  $this->github_url = empty($conf->global->MAIN_INFO_SOCIETE_GITHUB_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_GITHUB_URL;
4167  $this->socialnetworks = array();
4168  if (!empty($this->facebook_url)) {
4169  $this->socialnetworks['facebook'] = $this->facebook_url;
4170  }
4171  if (!empty($this->twitter_url)) {
4172  $this->socialnetworks['twitter'] = $this->twitter_url;
4173  }
4174  if (!empty($this->linkedin_url)) {
4175  $this->socialnetworks['linkedin'] = $this->linkedin_url;
4176  }
4177  if (!empty($this->instagram_url)) {
4178  $this->socialnetworks['instagram'] = $this->instagram_url;
4179  }
4180  if (!empty($this->youtube_url)) {
4181  $this->socialnetworks['youtube'] = $this->youtube_url;
4182  }
4183  if (!empty($this->github_url)) {
4184  $this->socialnetworks['github'] = $this->github_url;
4185  }
4186 
4187  // Id prof generiques
4188  $this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN;
4189  $this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET;
4190  $this->idprof3 = empty($conf->global->MAIN_INFO_APE) ? '' : $conf->global->MAIN_INFO_APE;
4191  $this->idprof4 = empty($conf->global->MAIN_INFO_RCS) ? '' : $conf->global->MAIN_INFO_RCS;
4192  $this->idprof5 = empty($conf->global->MAIN_INFO_PROFID5) ? '' : $conf->global->MAIN_INFO_PROFID5;
4193  $this->idprof6 = empty($conf->global->MAIN_INFO_PROFID6) ? '' : $conf->global->MAIN_INFO_PROFID6;
4194  $this->tva_intra = empty($conf->global->MAIN_INFO_TVAINTRA) ? '' : $conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
4195  $this->managers = empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS) ? '' : $conf->global->MAIN_INFO_SOCIETE_MANAGERS;
4196  $this->capital = empty($conf->global->MAIN_INFO_CAPITAL) ? '' : $conf->global->MAIN_INFO_CAPITAL;
4197  $this->forme_juridique_code = empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE) ? '' : $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
4198  $this->email = empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? '' : $conf->global->MAIN_INFO_SOCIETE_MAIL;
4199  $this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
4200  $this->logo = empty($conf->global->MAIN_INFO_SOCIETE_LOGO) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO;
4201  $this->logo_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
4202  $this->logo_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
4203  $this->logo_squarred = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED;
4204  $this->logo_squarred_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL;
4205  $this->logo_squarred_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI;
4206 
4207  // Define if company use vat or not
4208  $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
4209 
4210  // Define if company use local taxes
4211  $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION == 'localtax1on')) ? 1 : 0);
4212  $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION == 'localtax2on')) ? 1 : 0);
4213  }
4214 
4222  public function initAsSpecimen()
4223  {
4224  $now = dol_now();
4225 
4226  // Initialize parameters
4227  $this->id = 0;
4228  $this->entity = 1;
4229  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
4230  $this->nom = $this->name; // For backward compatibility
4231  $this->ref_ext = 'Ref ext';
4232  $this->specimen = 1;
4233  $this->address = '21 jump street';
4234  $this->zip = '99999';
4235  $this->town = 'MyTown';
4236  $this->state_id = 1;
4237  $this->state_code = 'AA';
4238  $this->state = 'MyState';
4239  $this->country_id = 1;
4240  $this->country_code = 'FR';
4241  $this->email = 'specimen@specimen.com';
4242  $this->socialnetworks = array(
4243  'skype' => 'tom.hanson',
4244  'twitter' => 'tomhanson',
4245  'facebook' => 'tomhanson',
4246  'linkedin' => 'tomhanson',
4247  );
4248  $this->url = 'http://www.specimen.com';
4249 
4250  $this->phone = '0909090901';
4251  $this->fax = '0909090909';
4252 
4253  $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
4254  $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
4255  $this->capital = 10000;
4256  $this->client = 1;
4257  $this->prospect = 1;
4258  $this->fournisseur = 1;
4259  $this->tva_assuj = 1;
4260  $this->tva_intra = 'EU1234567';
4261  $this->note_public = 'This is a comment (public)';
4262  $this->note_private = 'This is a comment (private)';
4263 
4264  $this->idprof1 = 'idprof1';
4265  $this->idprof2 = 'idprof2';
4266  $this->idprof3 = 'idprof3';
4267  $this->idprof4 = 'idprof4';
4268  $this->idprof5 = 'idprof5';
4269  $this->idprof6 = 'idprof6';
4270  return 1;
4271  }
4272 
4279  public function useLocalTax($localTaxNum = 0)
4280  {
4281  $sql = "SELECT t.localtax1, t.localtax2";
4282  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4283  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4284  $sql .= " AND t.active = 1";
4285  if (empty($localTaxNum)) {
4286  $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
4287  } elseif ($localTaxNum == 1) {
4288  $sql .= " AND t.localtax1_type <> '0'";
4289  } elseif ($localTaxNum == 2) {
4290  $sql .= " AND t.localtax2_type <> '0'";
4291  }
4292 
4293  $resql = $this->db->query($sql);
4294  if ($resql) {
4295  return ($this->db->num_rows($resql) > 0);
4296  } else {
4297  return false;
4298  }
4299  }
4300 
4306  public function useNPR()
4307  {
4308  $sql = "SELECT t.rowid";
4309  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4310  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4311  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
4312 
4313  dol_syslog("useNPR", LOG_DEBUG);
4314  $resql = $this->db->query($sql);
4315  if ($resql) {
4316  return ($this->db->num_rows($resql) > 0);
4317  } else {
4318  return false;
4319  }
4320  }
4321 
4328  public function useRevenueStamp()
4329  {
4330  $sql = "SELECT COUNT(*) as nb";
4331  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
4332  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
4333  $sql .= " AND r.active = 1";
4334 
4335  dol_syslog("useRevenueStamp", LOG_DEBUG);
4336  $resql = $this->db->query($sql);
4337  if ($resql) {
4338  $obj = $this->db->fetch_object($resql);
4339  return (($obj->nb > 0) ?true:false);
4340  } else {
4341  $this->error = $this->db->lasterror();
4342  return false;
4343  }
4344  }
4345 
4351  public function getLibProspLevel()
4352  {
4353  return $this->LibProspLevel($this->fk_prospectlevel);
4354  }
4355 
4356  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4363  public function LibProspLevel($fk_prospectlevel)
4364  {
4365  // phpcs:enable
4366  global $langs;
4367 
4368  $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
4369  // If lib not found in language file, we get label from cache/databse
4370  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
4371  $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
4372  }
4373  return $lib;
4374  }
4375 
4383  public function getLibProspCommStatut($mode = 0, $label = '')
4384  {
4385  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
4386  }
4387 
4388  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4402  public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
4403  {
4404  // phpcs:enable
4405  global $langs;
4406  $langs->load('customers');
4407 
4408  if ($mode == 2) {
4409  if ($status == '-1' || $status == 'ST_NO') {
4410  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4411  } elseif ($status == '0' || $status == 'ST_NEVER') {
4412  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4413  } elseif ($status == '1' || $status == 'ST_TODO') {
4414  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4415  } elseif ($status == '2' || $status == 'ST_PEND') {
4416  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4417  } elseif ($status == '3' || $status == 'ST_DONE') {
4418  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4419  } else {
4420  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4421  }
4422  } elseif ($mode == 3) {
4423  if ($status == '-1' || $status == 'ST_NO') {
4424  return img_action($langs->trans("StatusProspect-1"), -1, $picto);
4425  } elseif ($status == '0' || $status == 'ST_NEVER') {
4426  return img_action($langs->trans("StatusProspect0"), 0, $picto);
4427  } elseif ($status == '1' || $status == 'ST_TODO') {
4428  return img_action($langs->trans("StatusProspect1"), 1, $picto);
4429  } elseif ($status == '2' || $status == 'ST_PEND') {
4430  return img_action($langs->trans("StatusProspect2"), 2, $picto);
4431  } elseif ($status == '3' || $status == 'ST_DONE') {
4432  return img_action($langs->trans("StatusProspect3"), 3, $picto);
4433  } else {
4434  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto);
4435  }
4436  } elseif ($mode == 4) {
4437  if ($status == '-1' || $status == 'ST_NO') {
4438  return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
4439  } elseif ($status == '0' || $status == 'ST_NEVER') {
4440  return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
4441  } elseif ($status == '1' || $status == 'ST_TODO') {
4442  return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
4443  } elseif ($status == '2' || $status == 'ST_PEND') {
4444  return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
4445  } elseif ($status == '3' || $status == 'ST_DONE') {
4446  return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
4447  } else {
4448  return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
4449  }
4450  }
4451 
4452  return "Error, mode/status not found";
4453  }
4454 
4461  public function getOutstandingProposals($mode = 'customer')
4462  {
4463  $table = 'propal';
4464  if ($mode == 'supplier') {
4465  $table = 'supplier_proposal';
4466  }
4467 
4468  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4469  $sql .= " WHERE fk_soc = ".((int) $this->id);
4470  if ($mode == 'supplier') {
4471  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
4472  } else {
4473  $sql .= " AND entity IN (".getEntity('propal').")";
4474  }
4475 
4476  dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
4477 
4478  $resql = $this->db->query($sql);
4479  if ($resql) {
4480  $outstandingOpened = 0;
4481  $outstandingTotal = 0;
4482  $outstandingTotalIncTax = 0;
4483  $arrayofref = array();
4484  while ($obj = $this->db->fetch_object($resql)) {
4485  $arrayofref[$obj->rowid] = $obj->ref;
4486  $outstandingTotal += $obj->total_ht;
4487  $outstandingTotalIncTax += $obj->total_ttc;
4488  if ($obj->status != 0) {
4489  // Not a draft
4490  $outstandingOpened += $obj->total_ttc;
4491  }
4492  }
4493  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4494  } else {
4495  return array();
4496  }
4497  }
4498 
4505  public function getOutstandingOrders($mode = 'customer')
4506  {
4507  $table = 'commande';
4508  if ($mode == 'supplier') {
4509  $table = 'commande_fournisseur';
4510  }
4511 
4512  $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
4513  $sql .= " WHERE fk_soc = ".((int) $this->id);
4514  if ($mode == 'supplier') {
4515  $sql .= " AND entity IN (".getEntity('supplier_order').")";
4516  } else {
4517  $sql .= " AND entity IN (".getEntity('commande').")";
4518  }
4519 
4520  dol_syslog("getOutstandingOrders", LOG_DEBUG);
4521  $resql = $this->db->query($sql);
4522  if ($resql) {
4523  $outstandingOpened = 0;
4524  $outstandingTotal = 0;
4525  $outstandingTotalIncTax = 0;
4526  $arrayofref = array();
4527  while ($obj = $this->db->fetch_object($resql)) {
4528  $arrayofref[$obj->rowid] = $obj->ref;
4529  $outstandingTotal += $obj->total_ht;
4530  $outstandingTotalIncTax += $obj->total_ttc;
4531  if ($obj->status != 0) {
4532  // Not a draft
4533  $outstandingOpened += $obj->total_ttc;
4534  }
4535  }
4536  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
4537  } else {
4538  return array();
4539  }
4540  }
4541 
4549  public function getOutstandingBills($mode = 'customer', $late = 0)
4550  {
4551  $table = 'facture';
4552  if ($mode == 'supplier') {
4553  $table = 'facture_fourn';
4554  }
4555 
4556  /* Accurate value of remain to pay is to sum remaintopay for each invoice
4557  $paiement = $invoice->getSommePaiement();
4558  $creditnotes=$invoice->getSumCreditNotesUsed();
4559  $deposits=$invoice->getSumDepositsUsed();
4560  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
4561  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
4562  */
4563  $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
4564  $sql .= " WHERE fk_soc = ".((int) $this->id);
4565  if (!empty($late)) {
4566  $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
4567  }
4568  if ($mode == 'supplier') {
4569  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
4570  } else {
4571  $sql .= " AND entity IN (".getEntity('invoice').")";
4572  }
4573 
4574  dol_syslog("getOutstandingBills", LOG_DEBUG);
4575  $resql = $this->db->query($sql);
4576  if ($resql) {
4577  $outstandingOpened = 0;
4578  $outstandingTotal = 0;
4579  $outstandingTotalIncTax = 0;
4580  $arrayofref = array();
4581  $arrayofrefopened = array();
4582  if ($mode == 'supplier') {
4583  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
4584  $tmpobject = new FactureFournisseur($this->db);
4585  } else {
4586  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4587  $tmpobject = new Facture($this->db);
4588  }
4589  while ($obj = $this->db->fetch_object($resql)) {
4590  $arrayofref[$obj->rowid] = $obj->ref;
4591  $tmpobject->id = $obj->rowid;
4592 
4593  if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4594  && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
4595  ) {
4596  $outstandingTotal += $obj->total_ht;
4597  $outstandingTotalIncTax += $obj->total_ttc;
4598  }
4599 
4600  $remaintopay = 0;
4601 
4602  if ($obj->paye == 0
4603  && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
4604  && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
4605  && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
4606  //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
4607  $paiement = $tmpobject->getSommePaiement();
4608  $creditnotes = $tmpobject->getSumCreditNotesUsed();
4609  $deposits = $tmpobject->getSumDepositsUsed();
4610 
4611  $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
4612  $outstandingOpened += $remaintopay;
4613  }
4614 
4615  //if credit note is converted but not used
4616  // TODO Do this also for customer ?
4617  if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
4618  $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
4619  $remaintopay -= $remainingcreditnote;
4620  $outstandingOpened -= $remainingcreditnote;
4621  }
4622 
4623  if ($remaintopay) {
4624  $arrayofrefopened[$obj->rowid] = $obj->ref;
4625  }
4626  }
4627  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
4628  } else {
4629  dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
4630  return array();
4631  }
4632  }
4633 
4640  public function getLibCustProspStatut()
4641  {
4642  return $this->LibCustProspStatut($this->client);
4643  }
4644 
4645  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4652  public function LibCustProspStatut($status)
4653  {
4654  // phpcs:enable
4655  global $langs;
4656  $langs->load('companies');
4657 
4658  if ($status == 0) {
4659  return $langs->trans("NorProspectNorCustomer");
4660  } elseif ($status == 1) {
4661  return $langs->trans("Customer");
4662  } elseif ($status == 2) {
4663  return $langs->trans("Prospect");
4664  } elseif ($status == 3) {
4665  return $langs->trans("ProspectCustomer");
4666  }
4667  }
4668 
4669 
4681  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4682  {
4683  global $conf, $user, $langs;
4684 
4685  if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
4686  $modelpath = "core/modules/bank/doc/";
4687 
4688  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4689  $companybankaccount = new CompanyBankAccount($this->db);
4690  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
4691  if (!$result) {
4692  dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
4693  }
4694  $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4695  } else {
4696  // Positionne le modele sur le nom du modele a utiliser
4697  if (!dol_strlen($modele)) {
4698  if (!empty($conf->global->COMPANY_ADDON_PDF)) {
4699  $modele = $conf->global->COMPANY_ADDON_PDF;
4700  } else {
4701  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
4702  return 0;
4703  }
4704  }
4705 
4706  if (!isset($this->bank_account)) {
4707  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
4708  $bac = new CompanyBankAccount($this->db);
4709  $result = $bac->fetch(0, $this->id);
4710  if ($result > 0) {
4711  $this->bank_account = $bac;
4712  } else {
4713  $this->bank_account = '';
4714  }
4715  }
4716 
4717  $modelpath = "core/modules/societe/doc/";
4718 
4719  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4720  }
4721 
4722  return $result;
4723  }
4724 
4725 
4737  public function setCategories($categories, $type_categ)
4738  {
4739  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4740 
4741  // Decode type
4742  if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
4743  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
4744  return -1;
4745  }
4746 
4747  return parent::setCategoriesCommon($categories, $type_categ);
4748  }
4749 
4757  public function setSalesRep($salesrep, $onlyAdd = false)
4758  {
4759  global $user;
4760 
4761  // Handle single user
4762  if (!is_array($salesrep)) {
4763  $salesrep = array($salesrep);
4764  }
4765 
4766  $to_del = array(); // Nothing to delete
4767  $to_add = $salesrep;
4768  if ($onlyAdd === false) {
4769  // Get current users
4770  $existing = $this->getSalesRepresentatives($user, 1);
4771 
4772  // Diff
4773  if (is_array($existing)) {
4774  $to_del = array_diff($existing, $salesrep);
4775  $to_add = array_diff($salesrep, $existing);
4776  }
4777  }
4778 
4779  $error = 0;
4780 
4781  // Process
4782  foreach ($to_del as $del) {
4783  $this->del_commercial($user, $del);
4784  }
4785  foreach ($to_add as $add) {
4786  $result = $this->add_commercial($user, $add);
4787  if ($result < 0) {
4788  $error++;
4789  break;
4790  }
4791  }
4792 
4793  return $error ? -1 : 1;
4794  }
4795 
4802  public function setThirdpartyType($typent_id)
4803  {
4804  if ($this->id) {
4805  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
4806  $sql .= " SET fk_typent = ".($typent_id > 0 ? $typent_id : "null");
4807  $sql .= " WHERE rowid = ".((int) $this->id);
4808  dol_syslog(get_class($this).'::setThirdpartyType', LOG_DEBUG);
4809  $resql = $this->db->query($sql);
4810  if ($resql) {
4811  $this->typent_id = $typent_id;
4812  $this->typent_code = dol_getIdFromCode($this->db, $this->$typent_id, 'c_typent', 'id', 'code');
4813  return 1;
4814  } else {
4815  return -1;
4816  }
4817  } else {
4818  return -1;
4819  }
4820  }
4821 
4831  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4832  {
4833  if ($origin_id == $dest_id) {
4834  dol_syslog('Error: Try to merge a thirdparty into itself');
4835  return false;
4836  }
4837 
4842  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4843  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
4844  $sql .= ' SELECT fk_user ';
4845  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4846  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
4847 
4848  $resql = $dbs->query($sql);
4849  while ($obj = $dbs->fetch_object($resql)) {
4850  $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
4851  }
4852 
4857  $tables = array(
4858  'societe_address',
4859  'societe_commerciaux',
4860  'societe_prices',
4861  'societe_remise',
4862  'societe_remise_except',
4863  'societe_rib'
4864  );
4865 
4866  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4867  }
4868 
4877  public function setAccountancyCode($type, $value)
4878  {
4879  global $user, $langs, $conf;
4880 
4881  $this->db->begin();
4882 
4883  $field = 'accountancy_code_sell';
4884  if ($type == 'buy') {
4885  $field = 'accountancy_code_buy';
4886  } elseif ($type == 'sell') {
4887  $field = 'accountancy_code_sell';
4888  } else {
4889  return -1;
4890  }
4891 
4892  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
4893  $sql .= $field." = '".$this->db->escape($value)."'";
4894  $sql .= " WHERE rowid = ".((int) $this->id);
4895 
4896  dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
4897  $resql = $this->db->query($sql);
4898 
4899  if ($resql) {
4900  // Call triggers
4901  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
4902  $interface = new Interfaces($this->db);
4903  $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
4904  if ($result < 0) {
4905  $this->errors = $interface->errors;
4906  $this->db->rollback();
4907  return -1;
4908  }
4909  // End call triggers
4910 
4911  $this->$field = $value;
4912 
4913  $this->db->commit();
4914  return 1;
4915  } else {
4916  $this->error = $this->db->lasterror();
4917  $this->db->rollback();
4918  return -1;
4919  }
4920  }
4921 
4928  public function fetchPartnerships($mode)
4929  {
4930  global $langs;
4931 
4932  require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
4933 
4934 
4935  $this->partnerships[] = array();
4936 
4937  return 1;
4938  }
4939 }
Societe\NO_SUPPLIER
const NO_SUPPLIER
Third party is no supplier.
Definition: societe.class.php:829
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:48
Societe\replaceThirdparty
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: societe.class.php:4831
clean_url
clean_url($url, $http=1)
Clean an url string.
Definition: functions2.lib.php:825
db
$conf db
API class for accounts.
Definition: inc.php:41
Societe\PROSPECT
const PROSPECT
Third party is a prospect.
Definition: societe.class.php:819
Societe\create_individual
create_individual(User $user, $no_email=0, $tags=array())
Create a contact/address from thirdparty.
Definition: societe.class.php:1054
Societe\validateFamilyTree
validateFamilyTree($idparent, $idchild, $counter=0)
Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty ...
Definition: societe.class.php:3469
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
Definition: functions.lib.php:1468
dol_trunc
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.
Definition: functions.lib.php:3805
Societe\LibProspCommStatut
LibProspCommStatut($status, $mode=0, $label='', $picto='')
Return label of a given status.
Definition: societe.class.php:4402
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
FactureFournisseur\TYPE_CREDIT_NOTE
const TYPE_CREDIT_NOTE
Credit note invoice.
Definition: fournisseur.facture.class.php:338
Societe\get_codefournisseur
get_codefournisseur($objsoc=0, $type=1)
Assigns a vendor code from the code control module.
Definition: societe.class.php:3184
Societe\id_prof_verifiable
id_prof_verifiable($idprof)
Returns if a profid sould be verified to be unique.
Definition: societe.class.php:3533
Societe\getParentsForCompany
getParentsForCompany($company_id, $parents=[])
Get parents for company.
Definition: societe.class.php:3502
dol_delete_dir_recursive
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)
Definition: files.lib.php:1383
img_action
img_action($titlealt, $numaction, $picto='')
Show logo action.
Definition: functions.lib.php:4296
Societe\codefournisseur_modifiable
codefournisseur_modifiable()
Check if a vendor code is editable in the code control module configuration.
Definition: societe.class.php:3253
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
dol_substr
dol_substr($string, $start, $length, $stringencoding='', $trunconbytes=0)
Make a substring.
Definition: functions.lib.php:3766
Societe\LoadSupplierCateg
LoadSupplierCateg()
Load the list of provider categories.
Definition: societe.class.php:3955
Societe\set_remise_supplier
set_remise_supplier($remise, $note, User $user)
Defines the company as a customer.
Definition: societe.class.php:2225
CommonObject\setUpperOrLowerCase
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
Definition: commonobject.class.php:740
FactureFournisseur
Class to manage suppliers invoices.
Definition: fournisseur.facture.class.php:53
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
Societe\CUSTOMER_AND_PROSPECT
const CUSTOMER_AND_PROSPECT
Third party is a customer and a prospect.
Definition: societe.class.php:824
Societe\set_remise_except
set_remise_except($remise, User $user, $desc, $vatrate='', $discount_type=0)
Add a discount for third party.
Definition: societe.class.php:2286
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1033
MultiCurrency\getIdFromCode
static getIdFromCode($dbs, $code)
Get id of currency from code.
Definition: multicurrency.class.php:501
Societe\getLibStatut
getLibStatut($mode=0)
Return label of status (activity, closed)
Definition: societe.class.php:2828
CommonIncoterm
trait CommonIncoterm
Superclass for incoterm classes.
Definition: commonincoterm.class.php:29
ref
$object ref
Definition: info.php:77
Societe\NO_CUSTOMER
const NO_CUSTOMER
Third party is no customer.
Definition: societe.class.php:809
Societe\codeclient_modifiable
codeclient_modifiable()
Check if a client code is editable based on the parameters of the code control module.
Definition: societe.class.php:3213
Societe\create
create(User $user)
Create third party in database.
Definition: societe.class.php:872
Interfaces
Class to manage triggers.
Definition: interfaces.class.php:32
name
$conf db name
Definition: repair.php:122
Categorie
Class to manage categories.
Definition: categorie.class.php:47
Facture
Class to manage invoices.
Definition: facture.class.php:60
Societe\add_commercial
add_commercial(User $user, $commid)
Add link to sales representative.
Definition: societe.class.php:2477
Societe\useRevenueStamp
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysocin most cas...
Definition: societe.class.php:4328
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
CommonObject\getFullName
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
Definition: commonobject.class.php:712
Societe\setCategories
setCategories($categories, $type_categ)
Sets object to supplied categories.
Definition: societe.class.php:4737
CommonObject\isObjectUsed
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others.
Definition: commonobject.class.php:4556
CompanyBankAccount
Class to manage bank accounts description of third parties.
Definition: companybankaccount.class.php:34
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
Societe\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: societe.class.php:4222
Societe\setThirdpartyType
setThirdpartyType($typent_id)
Define third-party type of current company.
Definition: societe.class.php:4802
Societe\__construct
__construct($db)
Constructor.
Definition: societe.class.php:841
Societe\get_codecompta
get_codecompta($type)
Assigns a accounting code from the accounting code module.
Definition: societe.class.php:3378
Conf
Class to stock current configuration.
Definition: conf.class.php:33
CommonObject\insertExtraLanguages
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6424
Societe\useNPR
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
Definition: societe.class.php:4306
Societe\get_codeclient
get_codeclient($objsoc=0, $type=0)
Assigns a customer code from the code control module.
Definition: societe.class.php:3152
getState
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
Definition: company.lib.php:569
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
Societe\thirdparty_and_contact_email_array
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
Definition: societe.class.php:2869
Societe\getSalesRepresentatives
getSalesRepresentatives(User $user, $mode=0, $sortfield=null, $sortorder=null)
Return array of sales representatives.
Definition: societe.class.php:2374
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5406
BonPrelevement
Class to manage withdrawal receipts.
Definition: bonprelevement.class.php:43
Societe\setSalesRep
setSalesRep($salesrep, $onlyAdd=false)
Sets sales representatives of the thirdparty.
Definition: societe.class.php:4757
Societe\AddFournisseurInCategory
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
Definition: societe.class.php:3981
Societe\display_rib
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
Definition: societe.class.php:3084
Societe\setPriceLevel
setPriceLevel($price_level, User $user)
Set the price level.
Definition: societe.class.php:2442
Societe\getNomUrl
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1, $noaliasinname=0, $target='')
Return a link on thirdparty (with picto)
Definition: societe.class.php:2571
dol_getIdFromCode
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
Definition: functions.lib.php:8535
getEntity
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Definition: functions.lib.php:148
Societe\id_prof_check
id_prof_check($idprof, $soc)
Check the validity of a professional identifier according to the country of the company (siren,...
Definition: societe.class.php:3634
dol_string_nospecial
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
Definition: functions.lib.php:1376
Societe\getAvailableDiscounts
getAvailableDiscounts($user='', $filter='', $maxvalue=0, $discount_type=0)
Returns amount of included taxes of the current discounts/credits available from the company.
Definition: societe.class.php:2351
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6156
Societe\isACompany
isACompany()
Return if third party is a company (Business) or an end user (Consumer)
Definition: societe.class.php:3916
Database\fetch_object
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
Societe\update
update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.
Definition: societe.class.php:1249
Societe\SUPPLIER
const SUPPLIER
Third party is a supplier.
Definition: societe.class.php:834
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8347
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
Societe\getLibProspLevel
getLibProspLevel()
Return prostect level.
Definition: societe.class.php:4351
DiscountAbsolute
Class to manage absolute discounts.
Definition: discount.class.php:29
Societe\LibStatut
LibStatut($status, $mode=0)
Return the label of a given status.
Definition: societe.class.php:2841
setEventMessage
setEventMessage($mesgs, $style='mesgs')
Set event message in dol_events session object.
Definition: functions.lib.php:8108
Contact
Class to manage contact/addresses.
Definition: contact.class.php:40
Societe\has_projects
has_projects()
Indicates if the company has projects.
Definition: societe.class.php:3860
Societe\contact_property_array
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
Definition: societe.class.php:2916
Societe\setMysoc
setMysoc(Conf $conf)
Set properties with value into $conf.
Definition: societe.class.php:4094
dol_format_address
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.
Definition: functions.lib.php:2393
Societe\getOutstandingBills
getOutstandingBills($mode='customer', $late=0)
Return amount of bill not yet paid and total of all invoices.
Definition: societe.class.php:4549
Adherent
Class to manage members of a foundation.
Definition: adherent.class.php:46
Societe\create_from_member
create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
Create a third party into database from a member object.
Definition: societe.class.php:4008
Societe\isInEEC
isInEEC()
Return if a company is inside the EEC (European Economic Community)
Definition: societe.class.php:3943
Societe\getLibProspCommStatut
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
Definition: societe.class.php:4383
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
Societe\id_prof_exists
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
Definition: societe.class.php:3573
Societe\fetch
fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='')
Load a third party from database into memory.
Definition: societe.class.php:1697
Societe\contact_get_property
contact_get_property($rowid, $mode)
Return property of contact from its id.
Definition: societe.class.php:3044
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8062
Societe\useLocalTax
useLocalTax($localTaxNum=0)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
Definition: societe.class.php:4279
User
Class to manage Dolibarr users.
Definition: user.class.php:44
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6116
Societe\set_remise_client
set_remise_client($remise, $note, User $user)
Defines the company as a customer.
Definition: societe.class.php:2166
Societe\getOutstandingProposals
getOutstandingProposals($mode='customer')
Return amount of proposal not yet paid and total an dlist of all proposals.
Definition: societe.class.php:4461
Societe\setParent
setParent($id)
Define parent company of current company.
Definition: societe.class.php:3430
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10338
Societe\contact_array_objects
contact_array_objects()
Returns the contact list of this company.
Definition: societe.class.php:3010
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4211
Societe\contact_array
contact_array()
Returns the contact list of this company.
Definition: societe.class.php:2981
Societe\CUSTOMER
const CUSTOMER
Third party is a customer.
Definition: societe.class.php:814
Societe\thirdparty_and_contact_phone_array
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
Definition: societe.class.php:2891
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
Societe\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
Definition: societe.class.php:4681
Societe\getOutstandingOrders
getOutstandingOrders($mode='customer')
Return amount of order not yet paid and total and list of all orders.
Definition: societe.class.php:4505
Societe\set_as_client
set_as_client()
Define third party as a customer.
Definition: societe.class.php:2133
dol_print_phone
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
Definition: functions.lib.php:3185
Societe\get_all_rib
get_all_rib()
Return Array of RIB.
Definition: societe.class.php:3119
getCountry
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
Definition: company.lib.php:489
Form\showphoto
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Definition: html.form.class.php:9263
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5791
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
Societe\verify
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
Definition: societe.class.php:1127
Database\query
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
dol_is_dir
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:447
Societe\LibCustProspStatut
LibCustProspStatut($status)
Return the label of the customer/prospect status.
Definition: societe.class.php:4652
Societe\del_commercial
del_commercial(User $user, $commid)
Add link to sales representative.
Definition: societe.class.php:2537
Societe\getTypeUrl
getTypeUrl($withpicto=0, $option='', $notooltip=0, $tag='a')
Return link(s) on type of thirdparty (with picto)
Definition: societe.class.php:2798
Societe\id_prof_url
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
Definition: societe.class.php:3810
Societe\check_codefournisseur
check_codefournisseur()
Check supplier code.
Definition: societe.class.php:3340
Societe\LibProspLevel
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
Definition: societe.class.php:4363
Societe\getLibCustProspStatut
getLibCustProspStatut()
Return label of status customer is prospect/customer.
Definition: societe.class.php:4640
Societe\setAccountancyCode
setAccountancyCode($type, $value)
Sets an accountancy code for a thirdparty.
Definition: societe.class.php:4877
Societe\check_codeclient
check_codeclient()
Check customer code.
Definition: societe.class.php:3299
Societe\info
info($id)
Load information for tab info.
Definition: societe.class.php:3883
Societe\fetchPartnerships
fetchPartnerships($mode)
Function to get partnerships array.
Definition: societe.class.php:4928