dolibarr  7.0.0-beta
societe.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2015 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@capnetworks.com>
8  * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
9  * Copyright (C) 2010-2014 Juanjo Menent <jmenent@2byte.es>
10  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11  * Copyright (C) 2013 Alexandre Spangaro <aspangaro.dolibarr@gmail.com>
12  * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
13  * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
14  * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program. If not, see <http://www.gnu.org/licenses/>.
28  */
29 
35 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
37 
41 class Societe extends CommonObject
42 {
43  public $element='societe';
44  public $table_element = 'societe';
45  public $fk_element='fk_soc';
46  public $fieldsforcombobox='nom,name_alias';
47  protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord'); // To test if we can delete object
48  protected $childtablesoncascade=array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm");
49  public $picto = 'company';
50 
55  public $ismultientitymanaged = 1;
60  public $restrictiononfksoc = 1;
61 
62 
63  // BEGIN MODULEBUILDER PROPERTIES
67  public $fields=array(
68  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
69  'nom' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
70  'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
71  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20),
72  'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>60),
73  'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>61),
74  'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500),
75  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
76  //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
77  'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510),
78  'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
79  //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
80  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>1, 'position'=>1000),
81  );
82 
83 
84  public $entity;
85 
92  public $nom;
93 
98  public $name_alias;
99 
100  public $particulier;
101  public $address;
102  public $zip;
103  public $town;
104 
109  var $status;
110 
115  var $state_id;
116  var $state_code;
117  var $state;
118 
125  var $departement_code;
126 
132  var $departement;
133 
139  var $pays;
140 
145  var $phone;
150  var $fax;
155  var $email;
160  var $skype;
165  var $url;
166 
168 
172  var $barcode;
173 
174  // 6 professional id (usage depends on country)
175 
180  var $idprof1;
181 
186  var $idprof2;
187 
192  var $idprof3;
193 
198  var $idprof4;
199 
204  var $idprof5;
205 
210  var $idprof6;
211 
212  var $prefix_comm;
213 
214  var $tva_assuj;
219  var $tva_intra;
220 
221  // Local taxes
222  var $localtax1_assuj;
223  var $localtax1_value;
224  var $localtax2_assuj;
225  var $localtax2_value;
226 
227  var $managers;
228  var $capital;
229  var $typent_id;
230  var $typent_code;
231  var $effectif;
232  var $effectif_id;
233  var $forme_juridique_code;
234  var $forme_juridique;
235 
236  var $remise_percent;
237  var $mode_reglement_supplier_id;
238  var $cond_reglement_supplier_id;
239  var $fk_prospectlevel;
240  var $name_bis;
241 
242  //Log data
243 
248  var $date_modification;
253  var $user_modification;
258  var $date_creation;
263  var $user_creation;
264 
265 
266  var $specimen;
267 
272  var $client;
277  var $prospect;
282  var $fournisseur;
283 
288  var $code_client;
289 
294  var $code_fournisseur;
295 
300  var $code_compta;
301 
306  var $code_compta_fournisseur;
307 
313  var $note;
314 
319  var $note_private;
320 
325  var $note_public;
326 
329  var $statut_commercial;
330 
335  var $price_level;
336  var $outstanding_limit;
337 
342  var $commercial_id;
347  var $parent;
352  var $default_lang;
353 
354  var $ref;
355  var $ref_int;
362  var $ref_ext;
363 
370  var $import_key;
371 
376  var $webservices_url;
377 
382  var $webservices_key;
383 
384  var $logo;
385  var $logo_small;
386  var $logo_mini;
387 
388  var $array_options;
389 
390  // Incoterms
391  var $fk_incoterms;
392  var $location_incoterms;
393  var $libelle_incoterms; //Used into tooltip
394 
395  // Multicurrency
396  var $fk_multicurrency;
397  var $multicurrency_code;
398 
399 
400  // END MODULEBUILDER PROPERTIES
401 
402 
407  var $oldcopy;
408 
414  public function __construct($db)
415  {
416  $this->db = $db;
417 
418  $this->client = 0;
419  $this->prospect = 0;
420  $this->fournisseur = 0;
421  $this->typent_id = 0;
422  $this->effectif_id = 0;
423  $this->forme_juridique_code = 0;
424  $this->tva_assuj = 1;
425  $this->status = 1;
426  }
427 
428 
436  function create(User $user)
437  {
438  global $langs,$conf,$mysoc;
439 
440  $error=0;
441 
442  // Clean parameters
443  if (empty($this->status)) $this->status=0;
444  $this->name=$this->name?trim($this->name):trim($this->nom);
445  if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
446  $this->nom=$this->name; // For backward compatibility
447  if (empty($this->client)) $this->client=0;
448  if (empty($this->fournisseur)) $this->fournisseur=0;
449  $this->import_key = trim($this->import_key);
450 
451  if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
452  if (empty($this->fk_multicurrency))
453  {
454  $this->multicurrency_code = '';
455  $this->fk_multicurrency = 0;
456  }
457 
458  dol_syslog(get_class($this)."::create ".$this->name);
459 
460  $now=dol_now();
461 
462  $this->db->begin();
463 
464  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
465  if ($this->code_client == -1 || $this->code_client === 'auto') $this->get_codeclient($this,0);
466  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this,1);
467 
468  // Check more parameters (including mandatory setup
469  // If error, this->errors[] is filled
470  $result = $this->verify();
471 
472  if ($result >= 0)
473  {
474  $entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
475 
476  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
477  $sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$entity.", '".$this->db->idate($now)."'";
478  $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
479  $sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
480  $sql.= ", ".$this->status;
481  $sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
482  $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
483  $sql.= ", 0";
484  $sql.= ", ".(int) $this->fk_incoterms;
485  $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
486  $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
487  $sql.= ", ".(int) $this->fk_multicurrency;
488  $sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
489 
490  dol_syslog(get_class($this)."::create", LOG_DEBUG);
491  $result=$this->db->query($sql);
492  if ($result)
493  {
494  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
495 
496  $ret = $this->update($this->id,$user,0,1,1,'add');
497 
498  // Ajout du commercial affecte
499  if ($this->commercial_id != '' && $this->commercial_id != -1)
500  {
501  $this->add_commercial($user, $this->commercial_id);
502  }
503  // si un commercial cree un client il lui est affecte automatiquement
504  else if (empty($user->rights->societe->client->voir))
505  {
506  $this->add_commercial($user, $user->id);
507  }
508 
509  if ($ret >= 0)
510  {
511  // Call trigger
512  $result=$this->call_trigger('COMPANY_CREATE',$user);
513  if ($result < 0) $error++;
514  // End call triggers
515  }
516  else $error++;
517 
518  if (! $error)
519  {
520  dol_syslog(get_class($this)."::Create success id=".$this->id);
521  $this->db->commit();
522  return $this->id;
523  }
524  else
525  {
526  dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR);
527  $this->db->rollback();
528  return -4;
529  }
530  }
531  else
532  {
533  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
534  {
535  $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name); // duplicate on a field (code or profid or ...)
536  $result=-1;
537  }
538  else
539  {
540  $this->error=$this->db->lasterror();
541  $result=-2;
542  }
543  $this->db->rollback();
544  return $result;
545  }
546 
547  }
548  else
549  {
550  $this->db->rollback();
551  dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
552  return -3;
553  }
554  }
555 
556 
563  function create_individual(User $user)
564  {
565  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
566  $contact=new Contact($this->db);
567 
568  $contact->name = $this->name_bis;
569  $contact->firstname = $this->firstname;
570  $contact->civility_id = $this->civility_id;
571  $contact->socid = $this->id; // fk_soc
572  $contact->statut = 1;
573  $contact->priv = 0;
574  $contact->country_id = $this->country_id;
575  $contact->state_id = $this->state_id;
576  $contact->address = $this->address;
577  $contact->email = $this->email;
578  $contact->zip = $this->zip;
579  $contact->town = $this->town;
580  $contact->phone_pro = $this->phone;
581 
582  $result = $contact->create($user);
583  if ($result < 0)
584  {
585  $this->error = $contact->error;
586  $this->errors = $contact->errors;
587  dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
588  }
589 
590  return $result;
591  }
592 
599  function verify()
600  {
601  global $conf, $langs, $mysoc;
602 
603  $error = 0;
604  $this->errors=array();
605 
606  $result = 0;
607  $this->name = trim($this->name);
608  $this->nom=$this->name; // For backward compatibility
609 
610  if (! $this->name)
611  {
612  $this->errors[] = 'ErrorBadThirdPartyName';
613  $result = -2;
614  }
615 
616  if ($this->client)
617  {
618  $rescode = $this->check_codeclient();
619  if ($rescode <> 0)
620  {
621  if ($rescode == -1)
622  {
623  $this->errors[] = 'ErrorBadCustomerCodeSyntax';
624  }
625  if ($rescode == -2)
626  {
627  $this->errors[] = 'ErrorCustomerCodeRequired';
628  }
629  if ($rescode == -3)
630  {
631  $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
632  }
633  if ($rescode == -4)
634  {
635  $this->errors[] = 'ErrorPrefixRequired';
636  }
637  $result = -3;
638  }
639  }
640 
641  if ($this->fournisseur)
642  {
643  $rescode = $this->check_codefournisseur();
644  if ($rescode <> 0)
645  {
646  if ($rescode == -1)
647  {
648  $this->errors[] = 'ErrorBadSupplierCodeSyntax';
649  }
650  if ($rescode == -2)
651  {
652  $this->errors[] = 'ErrorSupplierCodeRequired';
653  }
654  if ($rescode == -3)
655  {
656  $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
657  }
658  if ($rescode == -5)
659  {
660  $this->errors[] = 'ErrorprefixRequired';
661  }
662  $result = -3;
663  }
664  }
665 
666  // Check for duplicate or mandatory fields defined into setup
667  $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL');
668  foreach($array_to_check as $key)
669  {
670  $keymin=strtolower($key);
671  $i=(int) preg_replace('/[^0-9]/','',$key);
672  $vallabel=$this->$keymin;
673 
674  if ($i > 0)
675  {
676  if ($this->isACompany())
677  {
678  // Check for unicity
679  if ($vallabel && $this->id_prof_verifiable($i))
680  {
681  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
682  {
683  $langs->load("errors");
684  $error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
685  }
686  }
687 
688  // Check for mandatory prof id (but only if country is other than ours)
689  if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id)
690  {
691  $idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY';
692  if (! $vallabel && ! empty($conf->global->$idprof_mandatory))
693  {
694  $langs->load("errors");
695  $error++;
696  $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
697  }
698  }
699  }
700  }
701  else
702  {
703  //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
704  //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
705  if ($key == 'EMAIL')
706  {
707  // Check for unicity
708  if ($vallabel && ! empty($conf->global->SOCIETE_EMAIL_UNIQUE))
709  {
710  if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
711  {
712  $langs->load("errors");
713  $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
714  }
715  }
716 
717  // Check for mandatory
718  if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email))
719  {
720  $langs->load("errors");
721  $error++;
722  $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
723  }
724  }
725  }
726  }
727 
728  if ($error) $result = -4;
729 
730  return $result;
731  }
732 
745  function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
746  {
747  global $langs,$conf,$hookmanager;
748  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
749 
750  if (empty($id)) $id = $this->id;
751 
752  $error=0;
753 
754  dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
755 
756  $now=dol_now();
757 
758  // Clean parameters
759  $this->id = $id;
760  $this->name = $this->name?trim($this->name):trim($this->nom);
761  $this->nom = $this->name; // For backward compatibility
762  $this->name_alias = trim($this->name_alias);
763  $this->ref_ext = trim($this->ref_ext);
764  $this->address = $this->address?trim($this->address):trim($this->address);
765  $this->zip = $this->zip?trim($this->zip):trim($this->zip);
766  $this->town = $this->town?trim($this->town):trim($this->town);
767  $this->state_id = trim($this->state_id);
768  $this->country_id = ($this->country_id > 0)?$this->country_id:0;
769  $this->phone = trim($this->phone);
770  $this->phone = preg_replace("/\s/","",$this->phone);
771  $this->phone = preg_replace("/\./","",$this->phone);
772  $this->fax = trim($this->fax);
773  $this->fax = preg_replace("/\s/","",$this->fax);
774  $this->fax = preg_replace("/\./","",$this->fax);
775  $this->email = trim($this->email);
776  $this->skype = trim($this->skype);
777  $this->url = $this->url?clean_url($this->url,0):'';
778  $this->note_private = trim($this->note_private);
779  $this->note_public = trim($this->note_public);
780  $this->idprof1 = trim($this->idprof1);
781  $this->idprof2 = trim($this->idprof2);
782  $this->idprof3 = trim($this->idprof3);
783  $this->idprof4 = trim($this->idprof4);
784  $this->idprof5 = (! empty($this->idprof5)?trim($this->idprof5):'');
785  $this->idprof6 = (! empty($this->idprof6)?trim($this->idprof6):'');
786  $this->prefix_comm = trim($this->prefix_comm);
787  $this->outstanding_limit = price2num($this->outstanding_limit);
788 
789  $this->tva_assuj = trim($this->tva_assuj);
790  $this->tva_intra = dol_sanitizeFileName($this->tva_intra,'');
791  if (empty($this->status)) $this->status = 0;
792 
793  if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
794  if (empty($this->fk_multicurrency))
795  {
796  $this->multicurrency_code = '';
797  $this->fk_multicurrency = 0;
798  }
799 
800  // Local taxes
801  $this->localtax1_assuj=trim($this->localtax1_assuj);
802  $this->localtax2_assuj=trim($this->localtax2_assuj);
803 
804  $this->localtax1_value=trim($this->localtax1_value);
805  $this->localtax2_value=trim($this->localtax2_value);
806 
807  if ($this->capital != '') $this->capital=price2num(trim($this->capital));
808  if (! is_numeric($this->capital)) $this->capital = ''; // '' = undef
809 
810  $this->effectif_id=trim($this->effectif_id);
811  $this->forme_juridique_code=trim($this->forme_juridique_code);
812 
813  //Gencod
814  $this->barcode=trim($this->barcode);
815 
816  // For automatic creation
817  if ($this->code_client == -1 || $this->code_client === 'auto') $this->get_codeclient($this,0);
818  if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this,1);
819 
820  $this->code_compta=trim($this->code_compta);
821  $this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
822 
823  // Check parameters. More tests are done later in the ->verify()
824  if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
825  {
826  $langs->load("errors");
827  $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
828  return -1;
829  }
830 
831  $customer=false;
832  if (! empty($allowmodcodeclient) && ! empty($this->client))
833  {
834  // Attention get_codecompta peut modifier le code suivant le module utilise
835  if (empty($this->code_compta))
836  {
837  $ret=$this->get_codecompta('customer');
838  if ($ret < 0) return -1;
839  }
840 
841  $customer=true;
842  }
843 
844  $supplier=false;
845  if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
846  {
847  // Attention get_codecompta peut modifier le code suivant le module utilise
848  if (empty($this->code_compta_fournisseur))
849  {
850  $ret=$this->get_codecompta('supplier');
851  if ($ret < 0) return -1;
852  }
853 
854  $supplier=true;
855  }
856 
857  //Web services
858  $this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
859  $this->webservices_key = trim($this->webservices_key);
860 
861  //Incoterms
862  $this->fk_incoterms = (int) $this->fk_incoterms;
863  $this->location_incoterms = trim($this->location_incoterms);
864 
865  $this->db->begin();
866 
867  // Check name is required and codes are ok or unique.
868  // If error, this->errors[] is filled
869  $result = 0;
870  if ($action != 'add') $result = $this->verify(); // We don't check when update called during a create because verify was already done
871 
872  if ($result >= 0)
873  {
874  dol_syslog(get_class($this)."::update verify ok or not done");
875 
876  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
877  $sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required
878  $sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
879  $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
880  $sql .= ",address = '" . $this->db->escape($this->address) ."'";
881 
882  $sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
883  $sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
884 
885  $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
886  $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
887 
888  $sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
889  $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
890  $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
891  $sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
892  $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
893 
894  $sql .= ",note_private = ".(! empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null");
895  $sql .= ",note_public = ".(! empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null");
896 
897  $sql .= ",siren = '". $this->db->escape($this->idprof1) ."'";
898  $sql .= ",siret = '". $this->db->escape($this->idprof2) ."'";
899  $sql .= ",ape = '". $this->db->escape($this->idprof3) ."'";
900  $sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
901  $sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
902  $sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
903 
904  $sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null");
905  $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
906  $sql .= ",status = " .$this->status;
907 
908  // Local taxes
909  $sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null");
910  $sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null");
911  if($this->localtax1_assuj==1)
912  {
913  if($this->localtax1_value!='')
914  {
915  $sql .=",localtax1_value =".$this->localtax1_value;
916  }
917  else $sql .=",localtax1_value =0.000";
918 
919  }
920  else $sql .=",localtax1_value =0.000";
921 
922  if($this->localtax2_assuj==1)
923  {
924  if($this->localtax2_value!='')
925  {
926  $sql .=",localtax2_value =".$this->localtax2_value;
927  }
928  else $sql .=",localtax2_value =0.000";
929 
930  }
931  else $sql .=",localtax2_value =0.000";
932 
933  $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
934 
935  $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
936 
937  $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
938  if (isset($this->stcomm_id))
939  {
940  $sql .= ",fk_stcomm=".($this->stcomm_id > 0 ? $this->stcomm_id : "0");
941  }
942  $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
943 
944  $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
945 
946  $sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
947  $sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
948  $sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
949  $sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
950  $sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
951 
952  $sql .= ",client = " . (! empty($this->client)?$this->client:0);
953  $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
954  $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
955  $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
956  $sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
957  $sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
958  $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
959 
960  $sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
961  $sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
962 
963  //Incoterms
964  $sql.= ", fk_incoterms = ".$this->fk_incoterms;
965  $sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
966 
967  if ($customer)
968  {
969  $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
970  $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
971  }
972 
973  if ($supplier)
974  {
975  $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
976  $sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
977  }
978  $sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null");
979  $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
980  $sql .= ', multicurrency_code = \''.$this->db->escape($this->multicurrency_code)."'";
981  $sql .= " WHERE rowid = '" . $id ."'";
982 
983  $resql=$this->db->query($sql);
984  if ($resql)
985  {
986  unset($this->country_code); // We clean this because it may have been changed after an update of country_id
987  unset($this->country);
988  unset($this->state_code);
989  unset($this->state);
990 
991  $nbrowsaffected = $this->db->affected_rows($resql);
992 
993  if (! $error && $nbrowsaffected)
994  {
995  // Update information on linked member if it is an update
996  if (! $nosyncmember && ! empty($conf->adherent->enabled))
997  {
998  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
999 
1000  dol_syslog(get_class($this)."::update update linked member");
1001 
1002  $lmember=new Adherent($this->db);
1003  $result=$lmember->fetch(0, 0, $this->id);
1004 
1005  if ($result > 0)
1006  {
1007  $lmember->societe=$this->name;
1008  //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
1009  //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
1010  $lmember->address=$this->address;
1011  $lmember->email=$this->email;
1012  $lmember->skype=$this->skype;
1013  $lmember->phone=$this->phone;
1014 
1015  $result=$lmember->update($user,0,1,1,1); // Use nosync to 1 to avoid cyclic updates
1016  if ($result < 0)
1017  {
1018  $this->error=$lmember->error;
1019  dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
1020  $error++;
1021  }
1022  }
1023  else if ($result < 0)
1024  {
1025  $this->error=$lmember->error;
1026  $error++;
1027  }
1028  }
1029  }
1030 
1031  $action='update';
1032 
1033  // Actions on extra fields (by external module or standard code)
1034  // TODO le hook fait double emploi avec le trigger !!
1035  $hookmanager->initHooks(array('thirdpartydao'));
1036  $parameters=array('socid'=>$this->id);
1037  $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
1038  if (empty($reshook))
1039  {
1040  if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1041  {
1042  $result=$this->insertExtraFields();
1043  if ($result < 0)
1044  {
1045  $error++;
1046  }
1047  }
1048  }
1049  else if ($reshook < 0) $error++;
1050 
1051  if (! $error && $call_trigger)
1052  {
1053  // Call trigger
1054  $result=$this->call_trigger('COMPANY_MODIFY',$user);
1055  if ($result < 0) $error++;
1056  // End call triggers
1057  }
1058 
1059  if (! $error)
1060  {
1061  dol_syslog(get_class($this)."::Update success");
1062  $this->db->commit();
1063  return 1;
1064  }
1065  else
1066  {
1067  $this->db->rollback();
1068  return -1;
1069  }
1070  }
1071  else
1072  {
1073  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1074  {
1075  // Doublon
1076  $this->error = $langs->trans("ErrorDuplicateField");
1077  $result = -1;
1078  }
1079  else
1080  {
1081  $this->error = $this->db->lasterror();
1082  $result = -2;
1083  }
1084  $this->db->rollback();
1085  return $result;
1086  }
1087  }
1088  else
1089  {
1090  $this->db->rollback();
1091  dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
1092  return -3;
1093  }
1094  }
1095 
1112  function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='', $email='')
1113  {
1114  global $langs;
1115  global $conf;
1116 
1117  if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1;
1118 
1119  $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
1120  $sql .= ', s.status';
1121  $sql .= ', s.price_level';
1122  $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1123  $sql .= ', s.phone, s.fax, s.email, s.skype, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
1124  $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1125  $sql .= ', s.capital, s.tva_intra';
1126  $sql .= ', s.fk_typent as typent_id';
1127  $sql .= ', s.fk_effectif as effectif_id';
1128  $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1129  $sql .= ', s.webservices_url, s.webservices_key';
1130  $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
1131  $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
1132  $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
1133  $sql .= ', s.fk_shipping_method';
1134  $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1135  $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1136  $sql .= ', fj.libelle as forme_juridique';
1137  $sql .= ', e.libelle as effectif';
1138  $sql .= ', c.code as country_code, c.label as country';
1139  $sql .= ', d.code_departement as state_code, d.nom as state';
1140  $sql .= ', st.libelle as stcomm';
1141  $sql .= ', te.code as typent_code';
1142  $sql .= ', i.libelle as libelle_incoterms';
1143  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1144  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1145  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1146  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1147  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1148  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1149  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1150  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1151  $sql .= ' WHERE s.entity IN ('.getEntity($this->element, 1).')';
1152  if ($rowid) $sql .= ' AND s.rowid = '.$rowid;
1153  if ($ref) $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1154  if ($ref_ext) $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1155  if ($ref_int) $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'";
1156  if ($idprof1) $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1157  if ($idprof2) $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1158  if ($idprof3) $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1159  if ($idprof4) $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1160  if ($idprof5) $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1161  if ($idprof6) $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1162  if ($email) $sql .= " AND s.email = '".$this->db->escape($email)."'";
1163 
1164  $resql=$this->db->query($sql);
1165  if ($resql)
1166  {
1167  $num=$this->db->num_rows($resql);
1168  if ($num > 1)
1169  {
1170  $this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
1171  dol_syslog($this->error, LOG_ERR);
1172  $result = -2;
1173  }
1174  elseif ($num) // $num = 1
1175  {
1176  $obj = $this->db->fetch_object($resql);
1177 
1178  $this->id = $obj->rowid;
1179  $this->entity = $obj->entity;
1180  $this->canvas = $obj->canvas;
1181 
1182  $this->ref = $obj->rowid;
1183  $this->name = $obj->name;
1184  $this->nom = $obj->name; // deprecated
1185  $this->name_alias = $obj->name_alias;
1186  $this->ref_ext = $obj->ref_ext;
1187  $this->ref_int = $obj->ref_int;
1188 
1189  $this->date_creation = $this->db->jdate($obj->date_creation);
1190  $this->date_modification = $this->db->jdate($obj->date_modification);
1191  $this->user_creation = $obj->fk_user_creat;
1192  $this->user_modification = $obj->fk_user_modif;
1193 
1194  $this->address = $obj->address;
1195  $this->zip = $obj->zip;
1196  $this->town = $obj->town;
1197 
1198  $this->country_id = $obj->country_id;
1199  $this->country_code = $obj->country_id?$obj->country_code:'';
1200  $this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
1201 
1202  $this->state_id = $obj->fk_departement;
1203  $this->state_code = $obj->state_code;
1204  $this->state = ($obj->state!='-'?$obj->state:'');
1205 
1206  $transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
1207  $libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
1208  $this->stcomm_id = $obj->fk_stcomm; // id statut commercial
1209  $this->statut_commercial = $libelle; // libelle statut commercial
1210 
1211  $this->email = $obj->email;
1212  $this->skype = $obj->skype;
1213  $this->url = $obj->url;
1214  $this->phone = $obj->phone;
1215  $this->fax = $obj->fax;
1216 
1217  $this->parent = $obj->parent;
1218 
1219  $this->idprof1 = $obj->idprof1;
1220  $this->idprof2 = $obj->idprof2;
1221  $this->idprof3 = $obj->idprof3;
1222  $this->idprof4 = $obj->idprof4;
1223  $this->idprof5 = $obj->idprof5;
1224  $this->idprof6 = $obj->idprof6;
1225 
1226  $this->capital = $obj->capital;
1227 
1228  $this->code_client = $obj->code_client;
1229  $this->code_fournisseur = $obj->code_fournisseur;
1230 
1231  $this->code_compta = $obj->code_compta;
1232  $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1233 
1234  $this->barcode = $obj->barcode;
1235 
1236  $this->tva_assuj = $obj->tva_assuj;
1237  $this->tva_intra = $obj->tva_intra;
1238  $this->status = $obj->status;
1239 
1240  // Local Taxes
1241  $this->localtax1_assuj = $obj->localtax1_assuj;
1242  $this->localtax2_assuj = $obj->localtax2_assuj;
1243 
1244  $this->localtax1_value = $obj->localtax1_value;
1245  $this->localtax2_value = $obj->localtax2_value;
1246 
1247  $this->typent_id = $obj->typent_id;
1248  $this->typent_code = $obj->typent_code;
1249 
1250  $this->effectif_id = $obj->effectif_id;
1251  $this->effectif = $obj->effectif_id?$obj->effectif:'';
1252 
1253  $this->forme_juridique_code= $obj->forme_juridique_code;
1254  $this->forme_juridique = $obj->forme_juridique_code?$obj->forme_juridique:'';
1255 
1256  $this->fk_prospectlevel = $obj->fk_prospectlevel;
1257 
1258  $this->prefix_comm = $obj->prefix_comm;
1259 
1260  $this->remise_percent = $obj->remise_client;
1261  $this->mode_reglement_id = $obj->mode_reglement;
1262  $this->cond_reglement_id = $obj->cond_reglement;
1263  $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
1264  $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
1265  $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1266  $this->fk_account = $obj->fk_account;
1267 
1268  $this->client = $obj->client;
1269  $this->fournisseur = $obj->fournisseur;
1270 
1271  $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1272  $this->note_private = $obj->note_private;
1273  $this->note_public = $obj->note_public;
1274  $this->modelpdf = $obj->model_pdf;
1275  $this->default_lang = $obj->default_lang;
1276  $this->logo = $obj->logo;
1277 
1278  $this->webservices_url = $obj->webservices_url;
1279  $this->webservices_key = $obj->webservices_key;
1280 
1281  $this->outstanding_limit = $obj->outstanding_limit;
1282 
1283  // multiprix
1284  $this->price_level = $obj->price_level;
1285 
1286  $this->import_key = $obj->import_key;
1287 
1288  //Incoterms
1289  $this->fk_incoterms = $obj->fk_incoterms;
1290  $this->location_incoterms = $obj->location_incoterms;
1291  $this->libelle_incoterms = $obj->libelle_incoterms;
1292 
1293  // multicurrency
1294  $this->fk_multicurrency = $obj->fk_multicurrency;
1295  $this->multicurrency_code = $obj->multicurrency_code;
1296 
1297  $result = 1;
1298 
1299  // Retreive all extrafield for thirdparty
1300  $this->fetch_optionals();
1301  }
1302  else
1303  {
1304  $result = 0;
1305  }
1306 
1307  $this->db->free($resql);
1308  }
1309  else
1310  {
1311  $this->error=$this->db->lasterror();
1312  $result = -3;
1313  }
1314 
1315  // Use first price level if level not defined for third party
1316  if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1;
1317 
1318  return $result;
1319  }
1320 
1333  function searchByName($name, $type='0', $filters = array(), $exact = false, $case = false, $similar = false, $clause = 'AND')
1334  {
1335  $thirdparties = array();
1336 
1337  dol_syslog("searchByName name=".$name." type=".$type." exact=".$exact);
1338 
1339  // Check parameter
1340  if (empty($name))
1341  {
1342  $this->errors[]='ErrorBadValueForParameter';
1343  return -1;
1344  }
1345 
1346  // Generation requete recherche
1347  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
1348  $sql.= " WHERE entity IN (".getEntity('category').")";
1349  if (! empty($type))
1350  {
1351  if ($type == 1 || $type == 2)
1352  $sql.= " AND client = ".$type;
1353  elseif ($type == 3)
1354  $sql.= " AND fournisseur = 1";
1355  }
1356  if (! empty($name))
1357  {
1358  if (! $exact)
1359  {
1360  if (preg_match('/^([\*])?[^*]+([\*])?$/', $name, $regs) && count($regs) > 1)
1361  {
1362  $name = str_replace('*', '%', $name);
1363  }
1364  else
1365  {
1366  $name = '%'.$name.'%';
1367  }
1368  }
1369  $sql.= " AND ";
1370  if (is_array($filters) && ! empty($filters))
1371  $sql.= "(";
1372  if ($similar)
1373  {
1374  // For test similitude (string inside name into database, or name into database inside string)
1375  // Do not use this. Not compatible with other database.
1376  $sql.= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)";
1377  }
1378  else
1379  {
1380  if (! $case)
1381  $sql.= "nom LIKE '".$this->db->escape($name)."'";
1382  else
1383  $sql.= "nom LIKE BINARY '".$this->db->escape($name)."'";
1384  }
1385  }
1386  if (is_array($filters) && ! empty($filters))
1387  {
1388  foreach($filters as $field => $value)
1389  {
1390  if (! $exact)
1391  {
1392  if (preg_match('/^([\*])?[^*]+([\*])?$/', $value, $regs) && count($regs) > 1)
1393  {
1394  $value = str_replace('*', '%', $value);
1395  }
1396  else
1397  {
1398  $value = '%'.$value.'%';
1399  }
1400  }
1401  if (! $case)
1402  $sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
1403  else
1404  $sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
1405  }
1406  if (! empty($name))
1407  $sql.= ")";
1408  }
1409 
1410  $res = $this->db->query($sql);
1411  if ($res)
1412  {
1413  while ($rec = $this->db->fetch_array($res))
1414  {
1415  $soc = new Societe($this->db);
1416  $soc->fetch($rec['rowid']);
1417  $thirdparties[] = $soc;
1418  }
1419 
1420  return $thirdparties;
1421  }
1422  else
1423  {
1424  $this->error=$this->db->lasterror();
1425  return -1;
1426  }
1427  }
1428 
1437  function delete($id, User $fuser=null, $call_trigger=1)
1438  {
1439  global $langs, $conf, $user;
1440 
1441  if (empty($fuser)) $fuser=$user;
1442 
1443  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1444 
1445  $entity=isset($this->entity)?$this->entity:$conf->entity;
1446 
1447  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1448  $error = 0;
1449 
1450  // Test if child exists
1451  $objectisused = $this->isObjectUsed($id);
1452  if (empty($objectisused))
1453  {
1454  $this->db->begin();
1455 
1456  // User is mandatory for trigger call
1457  if (! $error && $call_trigger)
1458  {
1459  // Call trigger
1460  $result=$this->call_trigger('COMPANY_DELETE',$fuser);
1461  if ($result < 0) $error++;
1462  // End call triggers
1463  }
1464 
1465  if (! $error)
1466  {
1467  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1468  $static_cat = new Categorie($this->db);
1469  $toute_categs = array();
1470 
1471  // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
1472  if ($this->client || $this->prospect)
1473  {
1474  $toute_categs['customer'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER);
1475  }
1476  if ($this->fournisseur)
1477  {
1478  $toute_categs['supplier'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER);
1479  }
1480 
1481  // Remove each "Categorie"
1482  foreach ($toute_categs as $type => $categs_type)
1483  {
1484  foreach ($categs_type as $cat)
1485  {
1486  $cat->del_type($this, $type);
1487  }
1488  }
1489  }
1490 
1491  foreach ($this->childtablesoncascade as $tabletodelete)
1492  {
1493  if (! $error)
1494  {
1495  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
1496  $sql.= " WHERE fk_soc = " . $id;
1497  if (! $this->db->query($sql))
1498  {
1499  $error++;
1500  $this->errors[] = $this->db->lasterror();
1501  }
1502  }
1503  }
1504 
1505  // Removed extrafields
1506  if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1507  {
1508  $result=$this->deleteExtraFields();
1509  if ($result < 0)
1510  {
1511  $error++;
1512  dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1513  }
1514  }
1515 
1516  // Remove third party
1517  if (! $error)
1518  {
1519  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
1520  $sql.= " WHERE rowid = " . $id;
1521  if (! $this->db->query($sql))
1522  {
1523  $error++;
1524  $this->errors[] = $this->db->lasterror();
1525  }
1526  }
1527 
1528  if (! $error)
1529  {
1530  $this->db->commit();
1531 
1532  // Delete directory
1533  if (! empty($conf->societe->multidir_output[$entity]))
1534  {
1535  $docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
1536  if (dol_is_dir($docdir))
1537  {
1538  dol_delete_dir_recursive($docdir);
1539  }
1540  }
1541 
1542  return 1;
1543  }
1544  else
1545  {
1546  dol_syslog($this->error, LOG_ERR);
1547  $this->db->rollback();
1548  return -1;
1549  }
1550  }
1551  else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
1552  return 0;
1553  }
1554 
1560  function set_as_client()
1561  {
1562  if ($this->id)
1563  {
1564  $newclient=1;
1565  if ($this->client == 2 || $this->client == 3) $newclient=3; //If prospect, we keep prospect tag
1566  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1567  $sql.= " SET client = ".$newclient;
1568  $sql.= " WHERE rowid = " . $this->id;
1569 
1570  $resql=$this->db->query($sql);
1571  if ($resql)
1572  {
1573  $this->client = $newclient;
1574  return 1;
1575  }
1576  else return -1;
1577  }
1578  return 0;
1579  }
1580 
1589  function set_remise_client($remise, $note, User $user)
1590  {
1591  global $conf, $langs;
1592 
1593  // Nettoyage parametres
1594  $note=trim($note);
1595  if (! $note)
1596  {
1597  $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
1598  return -2;
1599  }
1600 
1601  dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
1602 
1603  if ($this->id)
1604  {
1605  $this->db->begin();
1606 
1607  $now=dol_now();
1608 
1609  // Positionne remise courante
1610  $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1611  $sql.= " SET remise_client = '".$this->db->escape($remise)."'";
1612  $sql.= " WHERE rowid = " . $this->id;
1613  $resql=$this->db->query($sql);
1614  if (! $resql)
1615  {
1616  $this->db->rollback();
1617  $this->error=$this->db->error();
1618  return -1;
1619  }
1620 
1621  // Ecrit trace dans historique des remises
1622  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
1623  $sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
1624  $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1625  $sql.= " '".$this->db->escape($note)."',";
1626  $sql.= " ".$user->id;
1627  $sql.= ")";
1628 
1629  $resql=$this->db->query($sql);
1630  if (! $resql)
1631  {
1632  $this->db->rollback();
1633  $this->error=$this->db->lasterror();
1634  return -1;
1635  }
1636 
1637  $this->db->commit();
1638  return 1;
1639  }
1640  }
1641 
1651  function set_remise_except($remise, User $user, $desc, $tva_tx=0)
1652  {
1653  global $langs;
1654 
1655  // Clean parameters
1656  $remise = price2num($remise);
1657  $desc = trim($desc);
1658 
1659  // Check parameters
1660  if (! $remise > 0)
1661  {
1662  $this->error=$langs->trans("ErrorWrongValueForParameter","1");
1663  return -1;
1664  }
1665  if (! $desc)
1666  {
1667  $this->error=$langs->trans("ErrorWrongValueForParameter","3");
1668  return -2;
1669  }
1670 
1671  if ($this->id)
1672  {
1673  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1674 
1675  $discount = new DiscountAbsolute($this->db);
1676  $discount->fk_soc=$this->id;
1677  $discount->amount_ht=price2num($remise,'MT');
1678  $discount->amount_tva=price2num($remise*$tva_tx/100,'MT');
1679  $discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT');
1680  $discount->tva_tx=price2num($tva_tx,'MT');
1681  $discount->description=$desc;
1682  $result=$discount->create($user);
1683  if ($result > 0)
1684  {
1685  return $result;
1686  }
1687  else
1688  {
1689  $this->error=$discount->error;
1690  return -3;
1691  }
1692  }
1693  else return 0;
1694  }
1695 
1704  function getAvailableDiscounts($user='',$filter='',$maxvalue=0)
1705  {
1706  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1707 
1708  $discountstatic=new DiscountAbsolute($this->db);
1709  $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue);
1710  if ($result >= 0)
1711  {
1712  return $result;
1713  }
1714  else
1715  {
1716  $this->error=$discountstatic->error;
1717  return -1;
1718  }
1719  }
1720 
1728  {
1729  global $conf;
1730 
1731  $reparray=array();
1732 
1733  $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
1734  $sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
1735  if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1736  {
1737  $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1738  $sql.= " WHERE ((ug.fk_user = sc.fk_user";
1739  $sql.= " AND ug.entity = ".$conf->entity.")";
1740  $sql.= " OR u.admin = 1)";
1741  }
1742  else
1743  $sql.= " WHERE entity in (0, ".$conf->entity.")";
1744 
1745  $sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
1746 
1747  $resql = $this->db->query($sql);
1748  if ($resql)
1749  {
1750  $num = $this->db->num_rows($resql);
1751  $i=0;
1752  while ($i < $num)
1753  {
1754  $obj = $this->db->fetch_object($resql);
1755  $reparray[$i]['id']=$obj->rowid;
1756  $reparray[$i]['lastname']=$obj->lastname;
1757  $reparray[$i]['firstname']=$obj->firstname;
1758  $reparray[$i]['email']=$obj->email;
1759  $reparray[$i]['statut']=$obj->statut;
1760  $reparray[$i]['entity']=$obj->entity;
1761  $reparray[$i]['login']=$obj->login;
1762  $reparray[$i]['photo']=$obj->photo;
1763  $i++;
1764  }
1765  return $reparray;
1766  }
1767  else {
1768  dol_print_error($this->db);
1769  return -1;
1770  }
1771  }
1772 
1780  function set_price_level($price_level, User $user)
1781  {
1782  if ($this->id)
1783  {
1784  $now=dol_now();
1785 
1786  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1787  $sql .= " SET price_level = '".$this->db->escape($price_level)."'";
1788  $sql .= " WHERE rowid = " . $this->id;
1789 
1790  if (! $this->db->query($sql))
1791  {
1792  dol_print_error($this->db);
1793  return -1;
1794  }
1795 
1796  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
1797  $sql .= " (datec, fk_soc, price_level, fk_user_author)";
1798  $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")";
1799 
1800  if (! $this->db->query($sql))
1801  {
1802  dol_print_error($this->db);
1803  return -1;
1804  }
1805  return 1;
1806  }
1807  return -1;
1808  }
1809 
1817  function add_commercial(User $user, $commid)
1818  {
1819  if ($this->id > 0 && $commid > 0)
1820  {
1821  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
1822  $sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1823 
1824  $this->db->query($sql);
1825 
1826  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
1827  $sql.= " ( fk_soc, fk_user )";
1828  $sql.= " VALUES (".$this->id.",".$commid.")";
1829 
1830  if (! $this->db->query($sql) )
1831  {
1832  dol_syslog(get_class($this)."::add_commercial Erreur");
1833  }
1834  }
1835  }
1836 
1844  function del_commercial(User $user, $commid)
1845  {
1846  if ($this->id > 0 && $commid > 0)
1847  {
1848  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
1849  $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1850 
1851  if (! $this->db->query($sql) )
1852  {
1853  dol_syslog(get_class($this)."::del_commercial Erreur");
1854  }
1855  }
1856  }
1857 
1858 
1869  function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1)
1870  {
1871  global $conf, $langs, $hookmanager;
1872 
1873  if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips
1874 
1875  $name=$this->name?$this->name:$this->nom;
1876 
1877  if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
1878  {
1879  if (($this->client) && (! empty ( $this->code_client ))
1880  && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1881  || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
1882  )
1883  )
1884  $code = $this->code_client . ' - ';
1885 
1886  if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))
1887  && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1888  || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
1889  )
1890  )
1891  $code .= $this->code_fournisseur . ' - ';
1892 
1893  if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1)
1894  $name =$code.' '.$name;
1895  else
1896  $name =$code;
1897  }
1898 
1899  if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
1900 
1901  $result=''; $label='';
1902  $linkstart=''; $linkend='';
1903 
1904  if (! empty($this->logo) && class_exists('Form'))
1905  {
1906  $label.= '<div class="photointooltip">';
1907  $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.
1908  $label.= '</div><div style="clear: both;"></div>';
1909  }
1910 
1911  $label.= '<div class="centpercent">';
1912 
1913  if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
1914  {
1915  $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
1916  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1917  }
1918  else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
1919  {
1920  $label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
1921  $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1922  }
1923  else if ($option == 'supplier')
1924  {
1925  $label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
1926  $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
1927  }
1928  else if ($option == 'agenda')
1929  {
1930  $label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
1931  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
1932  }
1933  else if ($option == 'project')
1934  {
1935  $label.= '<u>' . $langs->trans("ShowProject") . '</u>';
1936  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
1937  }
1938  else if ($option == 'margin')
1939  {
1940  $label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
1941  $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
1942  }
1943  else if ($option == 'contact')
1944  {
1945  $label.= '<u>' . $langs->trans("ShowContacts") . '</u>';
1946  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
1947  }
1948  else if ($option == 'ban')
1949  {
1950  $label.= '<u>' . $langs->trans("ShowBan") . '</u>';
1951  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/rib.php?socid='.$this->id;
1952  }
1953 
1954  // By default
1955  if (empty($linkstart))
1956  {
1957  $label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
1958  $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
1959  }
1960 
1961  if (! empty($this->name))
1962  {
1963  $label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
1964  if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
1965  $label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email;
1966  }
1967  if (! empty($this->country_code))
1968  $label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
1969  if (! empty($this->tva_intra))
1970  $label.= '<br><b>' . $langs->trans('VATIntra') . ':</b> '. $this->tva_intra;
1971  if (! empty($this->code_client) && $this->client)
1972  $label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
1973  if (! empty($this->code_fournisseur) && $this->fournisseur)
1974  $label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
1975  if (! empty($conf->accounting->enabled) && $this->client)
1976  $label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. ($this->code_compta ? $this->code_compta : $this->code_compta_client);
1977  if (! empty($conf->accounting->enabled) && $this->fournisseur)
1978  $label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
1979 
1980  $label.= '</div>';
1981 
1982  // Add type of canvas
1983  $linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'');
1984  // Add param to save lastsearch_values or not
1985  $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1986  if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1987  if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1';
1988  $linkstart.='"';
1989 
1990  $linkclose='';
1991  if (empty($notooltip))
1992  {
1993  if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1994  {
1995  $label=$langs->trans("ShowCompany");
1996  $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1997  }
1998  $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1999  $linkclose.=' class="classfortooltip"';
2000 
2001  if (! is_object($hookmanager))
2002  {
2003  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
2004  $hookmanager=new HookManager($this->db);
2005  }
2006  $hookmanager->initHooks(array('societedao'));
2007  $parameters=array('id'=>$this->id);
2008  $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
2009  if ($reshook > 0) $linkclose = $hookmanager->resPrint;
2010  }
2011  $linkstart.=$linkclose.'>';
2012  $linkend='</a>';
2013 
2014  global $user;
2015  if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id)
2016  {
2017  $linkstart='';
2018  $linkend='';
2019  }
2020 
2021  $result.=$linkstart;
2022  if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1);
2023  if ($withpicto != 2) $result.=($maxlen?dol_trunc($name,$maxlen):$name);
2024  $result.=$linkend;
2025 
2026  return $result;
2027  }
2028 
2035  function getLibStatut($mode=0)
2036  {
2037  return $this->LibStatut($this->status,$mode);
2038  }
2039 
2047  function LibStatut($statut,$mode=0)
2048  {
2049  global $langs;
2050  $langs->load('companies');
2051 
2052  if ($mode == 0)
2053  {
2054  if ($statut==0) return $langs->trans("ActivityCeased");
2055  if ($statut==1) return $langs->trans("InActivity");
2056  }
2057  if ($mode == 1)
2058  {
2059  if ($statut==0) return $langs->trans("ActivityCeased");
2060  if ($statut==1) return $langs->trans("InActivity");
2061  }
2062  if ($mode == 2)
2063  {
2064  if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2065  if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2066  }
2067  if ($mode == 3)
2068  {
2069  if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2070  if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2071  }
2072  if ($mode == 4)
2073  {
2074  if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2075  if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2076  }
2077  if ($mode == 5)
2078  {
2079  if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans("ActivityCeased").'</span> '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2080  if ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans("InActivity").'</span> '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2081  }
2082  if ($mode == 6)
2083  {
2084  if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans("ActivityCeased").'</span> '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2085  if ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans("InActivity").'</span> '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2086  }
2087  }
2088 
2095  function thirdparty_and_contact_email_array($addthirdparty=0)
2096  {
2097  global $langs;
2098 
2099  $contact_emails = $this->contact_property_array('email',1);
2100  if ($this->email && $addthirdparty)
2101  {
2102  if (empty($this->name)) $this->name=$this->nom;
2103  $contact_emails['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->email.">";
2104  }
2105  //var_dump($contact_emails)
2106  return $contact_emails;
2107  }
2108 
2115  {
2116  global $langs;
2117 
2118  $contact_phone = $this->contact_property_array('mobile');
2119 
2120  if (! empty($this->phone)) // If a phone of thirdparty is defined, we add it ot mobile of contacts
2121  {
2122  if (empty($this->name)) $this->name=$this->nom;
2123  // TODO: Tester si tel non deja present dans tableau contact
2124  $contact_phone['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->phone.">";
2125  }
2126  return $contact_phone;
2127  }
2128 
2136  function contact_property_array($mode='email', $hidedisabled=0)
2137  {
2138  global $langs;
2139 
2140  $contact_property = array();
2141 
2142 
2143  $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
2144  $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2145  $sql.= " WHERE fk_soc = ".$this->id;
2146 
2147  $resql=$this->db->query($sql);
2148  if ($resql)
2149  {
2150  $nump = $this->db->num_rows($resql);
2151  if ($nump)
2152  {
2153  $sepa="("; $sepb=")";
2154  if ($mode == 'email')
2155  {
2156  //$sepa="&lt;"; $sepb="&gt;";
2157  $sepa="<"; $sepb=">";
2158  }
2159  $i = 0;
2160  while ($i < $nump)
2161  {
2162  $obj = $this->db->fetch_object($resql);
2163  if ($mode == 'email') $property=$obj->email;
2164  else if ($mode == 'mobile') $property=$obj->phone_mobile;
2165  else $property=$obj->$mode;
2166 
2167  // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2168  if ($obj->statut == 1 || empty($hidedisabled))
2169  {
2170  if (empty($property))
2171  {
2172  if ($mode == 'email') $property=$langs->transnoentitiesnoconv("NoEMail");
2173  else if ($mode == 'mobile') $property=$langs->transnoentitiesnoconv("NoMobilePhone");
2174  }
2175 
2176  if (!empty($obj->poste))
2177  {
2178  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2179  }
2180  else
2181  {
2182  $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2183  }
2184  }
2185  $i++;
2186  }
2187  }
2188  }
2189  else
2190  {
2191  dol_print_error($this->db);
2192  }
2193  return $contact_property;
2194  }
2195 
2196 
2202  function contact_array()
2203  {
2204  $contacts = array();
2205 
2206  $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2207  $resql=$this->db->query($sql);
2208  if ($resql)
2209  {
2210  $nump = $this->db->num_rows($resql);
2211  if ($nump)
2212  {
2213  $i = 0;
2214  while ($i < $nump)
2215  {
2216  $obj = $this->db->fetch_object($resql);
2217  $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname);
2218  $i++;
2219  }
2220  }
2221  }
2222  else
2223  {
2224  dol_print_error($this->db);
2225  }
2226  return $contacts;
2227  }
2228 
2235  {
2236  require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2237  $contacts = array();
2238 
2239  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2240  $resql=$this->db->query($sql);
2241  if ($resql)
2242  {
2243  $nump = $this->db->num_rows($resql);
2244  if ($nump)
2245  {
2246  $i = 0;
2247  while ($i < $nump)
2248  {
2249  $obj = $this->db->fetch_object($resql);
2250  $contact = new Contact($this->db);
2251  $contact->fetch($obj->rowid);
2252  $contacts[] = $contact;
2253  $i++;
2254  }
2255  }
2256  }
2257  else
2258  {
2259  dol_print_error($this->db);
2260  }
2261  return $contacts;
2262  }
2263 
2271  function contact_get_property($rowid,$mode)
2272  {
2273  $contact_property='';
2274 
2275  if (empty($rowid)) return '';
2276 
2277  $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
2278  $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2279  $sql.= " WHERE rowid = '".$rowid."'";
2280 
2281  $resql=$this->db->query($sql);
2282  if ($resql)
2283  {
2284  $nump = $this->db->num_rows($resql);
2285 
2286  if ($nump)
2287  {
2288  $obj = $this->db->fetch_object($resql);
2289 
2290  if ($mode == 'email') $contact_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
2291  else if ($mode == 'mobile') $contact_property = $obj->phone_mobile;
2292  }
2293  return $contact_property;
2294  }
2295  else
2296  {
2297  dol_print_error($this->db);
2298  }
2299 
2300  }
2301 
2302 
2309  function display_rib($mode='label')
2310  {
2311  require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2312 
2313  $bac = new CompanyBankAccount($this->db);
2314  $bac->fetch(0,$this->id);
2315 
2316  if ($mode == 'label')
2317  {
2318  return $bac->getRibLabel(true);
2319  }
2320  elseif ($mode == 'rum')
2321  {
2322  if (empty($bac->rum))
2323  {
2324  require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
2325  $prelevement = new BonPrelevement($this->db);
2326  $bac->fetch_thirdparty();
2327  $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
2328  }
2329  return $bac->rum;
2330  }
2331  elseif ($mode == 'format')
2332  {
2333  return $bac->frstrecur;
2334  }
2335 
2336  return 'BadParameterToFunctionDisplayRib';
2337  }
2338 
2344  function get_all_rib()
2345  {
2346  require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2347  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id;
2348  $result = $this->db->query($sql);
2349  if (!$result) {
2350  $this->error++;
2351  $this->errors[] = $this->db->lasterror;
2352  return 0;
2353  } else {
2354  $num_rows = $this->db->num_rows($result);
2355  $rib_array = array();
2356  if ($num_rows) {
2357  while ($obj = $this->db->fetch_object($result)) {
2358  $rib = new CompanyBankAccount($this->db);
2359  $rib->fetch($obj->rowid);
2360  $rib_array[] = $rib;
2361  }
2362  }
2363  return $rib_array;
2364  }
2365  }
2366 
2375  function get_codeclient($objsoc=0,$type=0)
2376  {
2377  global $conf;
2378  if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2379  {
2380  $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2381 
2382  $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2383  foreach ($dirsociete as $dirroot)
2384  {
2385  $res=dol_include_once($dirroot.$module.'.php');
2386  if ($res) break;
2387  }
2388  $mod = new $module();
2389 
2390  $this->code_client = $mod->getNextValue($objsoc,$type);
2391  $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
2392 
2393  dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
2394  }
2395  }
2396 
2405  function get_codefournisseur($objsoc=0,$type=1)
2406  {
2407  global $conf;
2408  if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2409  {
2410  $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2411 
2412  $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2413  foreach ($dirsociete as $dirroot)
2414  {
2415  $res=dol_include_once($dirroot.$module.'.php');
2416  if ($res) break;
2417  }
2418  $mod = new $module();
2419 
2420  $this->code_fournisseur = $mod->getNextValue($objsoc,$type);
2421 
2422  dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2423  }
2424  }
2425 
2433  {
2434  global $conf;
2435  if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2436  {
2437  $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2438 
2439  $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2440  foreach ($dirsociete as $dirroot)
2441  {
2442  $res=dol_include_once($dirroot.$module.'.php');
2443  if ($res) break;
2444  }
2445 
2446  $mod = new $module();
2447 
2448  dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
2449  if ($mod->code_modifiable_null && ! $this->code_client) return 1;
2450  if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
2451  if ($mod->code_modifiable) return 1; // A mettre en dernier
2452  return 0;
2453  }
2454  else
2455  {
2456  return 0;
2457  }
2458  }
2459 
2460 
2467  {
2468  global $conf;
2469  if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2470  {
2471  $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2472 
2473  $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2474  foreach ($dirsociete as $dirroot)
2475  {
2476  $res=dol_include_once($dirroot.$module.'.php');
2477  if ($res) break;
2478  }
2479 
2480  $mod = new $module();
2481 
2482  dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
2483  if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
2484  if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
2485  if ($mod->code_modifiable) return 1; // A mettre en dernier
2486  return 0;
2487  }
2488  else
2489  {
2490  return 0;
2491  }
2492  }
2493 
2494 
2504  function check_codeclient()
2505  {
2506  global $conf;
2507  if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2508  {
2509  $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2510 
2511  $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2512  foreach ($dirsociete as $dirroot)
2513  {
2514  $res=dol_include_once($dirroot.$module.'.php');
2515  if ($res) break;
2516  }
2517 
2518  $mod = new $module();
2519 
2520  dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
2521  $result = $mod->verif($this->db, $this->code_client, $this, 0);
2522  return $result;
2523  }
2524  else
2525  {
2526  return 0;
2527  }
2528  }
2529 
2540  {
2541  global $conf;
2542  if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2543  {
2544  $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2545 
2546  $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2547  foreach ($dirsociete as $dirroot)
2548  {
2549  $res=dol_include_once($dirroot.$module.'.php');
2550  if ($res) break;
2551  }
2552 
2553  $mod = new $module();
2554 
2555  dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2556  $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
2557  return $result;
2558  }
2559  else
2560  {
2561  return 0;
2562  }
2563  }
2564 
2573  function get_codecompta($type)
2574  {
2575  global $conf;
2576 
2577  if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
2578  {
2579  $file='';
2580  $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2581  foreach ($dirsociete as $dirroot)
2582  {
2583  if (file_exists(DOL_DOCUMENT_ROOT.'/'.$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php"))
2584  {
2585  $file=$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php";
2586  break;
2587  }
2588  }
2589 
2590  if (! empty($file))
2591  {
2592  dol_include_once($file);
2593 
2594  $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
2595  $mod = new $classname;
2596 
2597  // Defini code compta dans $mod->code
2598  $result = $mod->get_code($this->db, $this, $type);
2599 
2600  if ($type == 'customer') $this->code_compta = $mod->code;
2601  else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
2602 
2603  return $result;
2604  }
2605  else
2606  {
2607  $this->error = 'ErrorAccountancyCodeNotDefined';
2608  return -1;
2609  }
2610  }
2611  else
2612  {
2613  if ($type == 'customer') $this->code_compta = '';
2614  else if ($type == 'supplier') $this->code_compta_fournisseur = '';
2615 
2616  return 0;
2617  }
2618  }
2619 
2626  function set_parent($id)
2627  {
2628  if ($this->id)
2629  {
2630  $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2631  $sql.= " SET parent = ".($id > 0 ? $id : "null");
2632  $sql.= " WHERE rowid = " . $this->id;
2633  dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
2634  $resql=$this->db->query($sql);
2635  if ($resql)
2636  {
2637  $this->parent = $id;
2638  return 1;
2639  }
2640  else
2641  {
2642  return -1;
2643  }
2644  }
2645  else return -1;
2646  }
2647 
2654  function id_prof_verifiable($idprof)
2655  {
2656  global $conf;
2657 
2658  switch($idprof)
2659  {
2660  case 1:
2661  $ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
2662  break;
2663  case 2:
2664  $ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
2665  break;
2666  case 3:
2667  $ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
2668  break;
2669  case 4:
2670  $ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
2671  break;
2672  case 5:
2673  $ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true);
2674  break;
2675  case 6:
2676  $ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true);
2677  break;
2678  default:
2679  $ret=false;
2680  }
2681 
2682  return $ret;
2683  }
2684 
2693  function id_prof_exists($idprof, $value, $socid=0)
2694  {
2695  $field = $idprof;
2696 
2697  switch($idprof) // For backward compatibility
2698  {
2699  case '1':
2700  case 'idprof1':
2701  $field="siren";
2702  break;
2703  case '2':
2704  case 'idprof2':
2705  $field="siret";
2706  break;
2707  case '3':
2708  case 'idprof3':
2709  $field="ape";
2710  break;
2711  case '4':
2712  case 'idprof4':
2713  $field="idprof4";
2714  break;
2715  case '5':
2716  $field="idprof5";
2717  break;
2718  case '6':
2719  $field="idprof6";
2720  break;
2721  }
2722 
2723  //Verify duplicate entries
2724  $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
2725  if($socid) $sql .= " AND rowid <> ".$socid;
2726  $resql = $this->db->query($sql);
2727  if ($resql)
2728  {
2729  $obj = $this->db->fetch_object($resql);
2730  $count = $obj->idprof;
2731  }
2732  else
2733  {
2734  $count = 0;
2735  print $this->db->error();
2736  }
2737  $this->db->free($resql);
2738 
2739  if ($count > 0) return true;
2740  else return false;
2741  }
2742 
2751  function id_prof_check($idprof,$soc)
2752  {
2753  global $conf;
2754 
2755  $ok=1;
2756 
2757  if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
2758 
2759  // Verifie SIREN si pays FR
2760  if ($idprof == 1 && $soc->country_code == 'FR')
2761  {
2762  $chaine=trim($this->idprof1);
2763  $chaine=preg_replace('/(\s)/','',$chaine);
2764 
2765  if (dol_strlen($chaine) != 9) return -1;
2766 
2767  $sum = 0;
2768 
2769  for ($i = 0 ; $i < 10 ; $i = $i+2)
2770  {
2771  $sum = $sum + substr($this->idprof1, (8 - $i), 1);
2772  }
2773 
2774  for ($i = 1 ; $i < 9 ; $i = $i+2)
2775  {
2776  $ps = 2 * substr($this->idprof1, (8 - $i), 1);
2777 
2778  if ($ps > 9)
2779  {
2780  $ps = substr($ps, 0,1) + substr($ps, 1, 1);
2781  }
2782  $sum = $sum + $ps;
2783  }
2784 
2785  if (substr($sum, -1) != 0) return -1;
2786  }
2787 
2788  // Verifie SIRET si pays FR
2789  if ($idprof == 2 && $soc->country_code == 'FR')
2790  {
2791  $chaine=trim($this->idprof2);
2792  $chaine=preg_replace('/(\s)/','',$chaine);
2793 
2794  if (dol_strlen($chaine) != 14) return -1;
2795  }
2796 
2797  //Verify CIF/NIF/NIE if pays ES
2798  //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
2799  if ($idprof == 1 && $soc->country_code == 'ES')
2800  {
2801  $string=trim($this->idprof1);
2802  $string=preg_replace('/(\s)/','',$string);
2803  $string = strtoupper($string);
2804 
2805  for ($i = 0; $i < 9; $i ++)
2806  $num[$i] = substr($string, $i, 1);
2807 
2808  //Check format
2809  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))
2810  return 0;
2811 
2812  //Check NIF
2813  if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
2814  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
2815  return 1;
2816  else
2817  return -1;
2818 
2819  //algorithm checking type code CIF
2820  $sum = $num[2] + $num[4] + $num[6];
2821  for ($i = 1; $i < 8; $i += 2)
2822  $sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1);
2823  $n = 10 - substr($sum, strlen($sum) - 1, 1);
2824 
2825  //Chek special NIF
2826  if (preg_match('/^[KLM]{1}/', $string))
2827  if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
2828  return 1;
2829  else
2830  return -1;
2831 
2832  //Check CIF
2833  if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
2834  if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
2835  return 2;
2836  else
2837  return -2;
2838 
2839  //Check NIE T
2840  if (preg_match('/^[T]{1}/', $string))
2841  if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
2842  return 3;
2843  else
2844  return -3;
2845 
2846  //Check NIE XYZ
2847  if (preg_match('/^[XYZ]{1}/', $string))
2848  if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
2849  return 3;
2850  else
2851  return -3;
2852 
2853  //Can not be verified
2854  return -4;
2855  }
2856 
2857  return $ok;
2858  }
2859 
2868  function id_prof_url($idprof,$thirdparty)
2869  {
2870  global $conf,$langs,$hookmanager;
2871 
2872  $url='';
2873  $action = '';
2874 
2875  $hookmanager->initHooks(array('idprofurl'));
2876  $parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
2877  $reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
2878  if (empty($reshook))
2879  {
2880  if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return '';
2881 
2882  // TODO Move links to validate professional ID into a dictionary table "country" + "link"
2883  if ($idprof == 1 && $thirdparty->country_code == 'FR') $url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1; // See also http://avis-situation-sirene.insee.fr/
2884  //if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/'; // Link no more valid
2885  if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
2886  if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
2887 
2888  if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
2889  }
2890  else
2891  {
2892  return $hookmanager->resPrint;
2893  }
2894 
2895  return '';
2896  }
2897 
2903  function has_projects()
2904  {
2905  $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
2906  $resql = $this->db->query($sql);
2907  if ($resql)
2908  {
2909  $obj = $this->db->fetch_object($resql);
2910  $count = $obj->numproj;
2911  }
2912  else
2913  {
2914  $count = 0;
2915  print $this->db->error();
2916  }
2917  $this->db->free($resql);
2918  return ($count > 0);
2919  }
2920 
2921 
2928  function info($id)
2929  {
2930  $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
2931  $sql.= " fk_user_creat, fk_user_modif";
2932  $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
2933  $sql.= " WHERE s.rowid = ".$id;
2934 
2935  $result=$this->db->query($sql);
2936  if ($result)
2937  {
2938  if ($this->db->num_rows($result))
2939  {
2940  $obj = $this->db->fetch_object($result);
2941 
2942  $this->id = $obj->rowid;
2943 
2944  if ($obj->fk_user_creat) {
2945  $cuser = new User($this->db);
2946  $cuser->fetch($obj->fk_user_creat);
2947  $this->user_creation = $cuser;
2948  }
2949 
2950  if ($obj->fk_user_modif) {
2951  $muser = new User($this->db);
2952  $muser->fetch($obj->fk_user_modif);
2953  $this->user_modification = $muser;
2954  }
2955 
2956  $this->ref = $obj->name;
2957  $this->date_creation = $this->db->jdate($obj->date_creation);
2958  $this->date_modification = $this->db->jdate($obj->date_modification);
2959  }
2960 
2961  $this->db->free($result);
2962 
2963  }
2964  else
2965  {
2966  dol_print_error($this->db);
2967  }
2968  }
2969 
2975  function isACompany()
2976  {
2977  global $conf;
2978 
2979  // Define if third party is treated as company (or not) when nature is unknown
2980  $isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
2981  if (! empty($this->tva_intra)) $isacompany=1;
2982  else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) $isacompany=0;
2983  else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE','TE_GROUP'))) $isacompany=1;
2984 
2985  return $isacompany;
2986  }
2987 
2994  {
2995  $this->SupplierCategories = array();
2996  $sql = "SELECT rowid, label";
2997  $sql.= " FROM ".MAIN_DB_PREFIX."categorie";
2998  $sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
2999 
3000  $resql=$this->db->query($sql);
3001  if ($resql)
3002  {
3003  while ($obj = $this->db->fetch_object($resql) )
3004  {
3005  $this->SupplierCategories[$obj->rowid] = $obj->label;
3006  }
3007  return 0;
3008  }
3009  else
3010  {
3011  return -1;
3012  }
3013  }
3014 
3021  function AddFournisseurInCategory($categorie_id)
3022  {
3023  if ($categorie_id > 0 && $this->id > 0)
3024  {
3025  $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
3026  $sql.= " VALUES (".$categorie_id.", ".$this->id.")";
3027 
3028  if ($resql=$this->db->query($sql)) return 0;
3029  }
3030  else
3031  {
3032  return 0;
3033  }
3034  return -1;
3035  }
3036 
3037 
3046  function create_from_member(Adherent $member, $socname='', $socalias='')
3047  {
3048  global $user,$langs;
3049 
3050  $name = $socname?$socname:$member->societe;
3051  if (empty($name)) $name=$member->getFullName($langs);
3052 
3053  $alias = $socalias?$socalias:'';
3054 
3055  // Positionne parametres
3056  $this->nom=$name; // TODO deprecated
3057  $this->name=$name;
3058  $this->name_alias=$alias;
3059  $this->address=$member->address;
3060  $this->zip=$member->zip;
3061  $this->town=$member->town;
3062  $this->country_code=$member->country_code;
3063  $this->country_id=$member->country_id;
3064  $this->phone=$member->phone; // Prof phone
3065  $this->email=$member->email;
3066  $this->skype=$member->skype;
3067 
3068  $this->client = 1; // A member is a customer by default
3069  $this->code_client = -1;
3070  $this->code_fournisseur = -1;
3071 
3072  $this->db->begin();
3073 
3074  // Cree et positionne $this->id
3075  $result=$this->create($user);
3076  if ($result >= 0)
3077  {
3078  $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
3079  $sql.= " SET fk_soc=".$this->id;
3080  $sql.= " WHERE rowid=".$member->id;
3081 
3082  dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
3083  $resql=$this->db->query($sql);
3084  if ($resql)
3085  {
3086  $this->db->commit();
3087  return $this->id;
3088  }
3089  else
3090  {
3091  $this->error=$this->db->error();
3092 
3093  $this->db->rollback();
3094  return -1;
3095  }
3096  }
3097  else
3098  {
3099  // $this->error deja positionne
3100  dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
3101 
3102  $this->db->rollback();
3103  return $result;
3104  }
3105  }
3106 
3113  function setMysoc(Conf $conf)
3114  {
3115  global $langs;
3116 
3117  $this->id=0;
3118  $this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
3119  $this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3120  $this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
3121  $this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
3122  $this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE;
3123 
3124  /* Disabled: we don't want any SQL request into method setMySoc. This method set object from env only.
3125  If we need label, label must be loaded by output that need it from id (label depends on output language)
3126  require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
3127  if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
3128  $this->state_id= $conf->global->MAIN_INFO_SOCIETE_STATE;
3129  $this->state = getState($this->state_id);
3130  }
3131  */
3132 
3133  $this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
3134 
3135  $this->nom=$this->name; // deprecated
3136 
3137  // We define country_id, country_code and country
3138  $country_id=$country_code=$country_label='';
3139  if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
3140  {
3141  $tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3142  $country_id=$tmp[0];
3143  if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3144  {
3145  $country_code=$tmp[1];
3146  $country_label=$tmp[2];
3147  }
3148  else // For backward compatibility
3149  {
3150  dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3151  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3152  $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
3153  $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
3154  }
3155  }
3156  $this->country_id=$country_id;
3157  $this->country_code=$country_code;
3158  $this->country=$country_label;
3159  if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3160 
3161  $this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
3162  $this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
3163  $this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
3164  // Id prof generiques
3165  $this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
3166  $this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
3167  $this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
3168  $this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
3169  $this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
3170  $this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
3171  $this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
3172  $this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3173  $this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
3174  $this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3175  $this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
3176  $this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
3177  $this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3178  $this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3179 
3180  // Define if company use vat or not
3181  $this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
3182 
3183  // Define if company use local taxes
3184  $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);
3185  $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);
3186  }
3187 
3195  function initAsSpecimen()
3196  {
3197  $now=dol_now();
3198 
3199  // Initialize parameters
3200  $this->id=0;
3201  $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog');
3202  $this->nom = $this->name; // For backward compatibility
3203  $this->ref_ext = 'Ref ext';
3204  $this->specimen=1;
3205  $this->address='21 jump street';
3206  $this->zip='99999';
3207  $this->town='MyTown';
3208  $this->state_id=1;
3209  $this->state_code='AA';
3210  $this->state='MyState';
3211  $this->country_id=1;
3212  $this->country_code='FR';
3213  $this->email='specimen@specimen.com';
3214  $this->skype='tom.hanson';
3215  $this->url='http://www.specimen.com';
3216 
3217  $this->phone='0909090901';
3218  $this->fax='0909090909';
3219 
3220  $this->code_client='CC-'.dol_print_date($now,'dayhourlog');
3221  $this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog');
3222  $this->capital=10000;
3223  $this->client=1;
3224  $this->prospect=1;
3225  $this->fournisseur=1;
3226  $this->tva_assuj=1;
3227  $this->tva_intra='EU1234567';
3228  $this->note_public='This is a comment (public)';
3229  $this->note_private='This is a comment (private)';
3230 
3231  $this->idprof1='idprof1';
3232  $this->idprof2='idprof2';
3233  $this->idprof3='idprof3';
3234  $this->idprof4='idprof4';
3235  $this->idprof5='idprof5';
3236  $this->idprof6='idprof6';
3237  }
3238 
3245  function useLocalTax($localTaxNum=0)
3246  {
3247  $sql = "SELECT t.localtax1, t.localtax2";
3248  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3249  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3250  $sql .= " AND t.active = 1";
3251  if (empty($localTaxNum)) $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3252  elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
3253  elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
3254 
3255  dol_syslog("useLocalTax", LOG_DEBUG);
3256  $resql=$this->db->query($sql);
3257  if ($resql)
3258  {
3259  return ($this->db->num_rows($resql) > 0);
3260  }
3261  else return false;
3262  }
3263 
3269  function useNPR()
3270  {
3271  $sql = "SELECT t.rowid";
3272  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3273  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3274  $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
3275 
3276  dol_syslog("useNPR", LOG_DEBUG);
3277  $resql=$this->db->query($sql);
3278  if ($resql)
3279  {
3280  return ($this->db->num_rows($resql) > 0);
3281  }
3282  else return false;
3283  }
3284 
3290  function useRevenueStamp()
3291  {
3292  $sql = "SELECT COUNT(*) as nb";
3293  $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
3294  $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3295  $sql .= " AND r.active = 1";
3296 
3297  dol_syslog("useRevenueStamp", LOG_DEBUG);
3298  $resql=$this->db->query($sql);
3299  if ($resql)
3300  {
3301  $obj=$this->db->fetch_object($resql);
3302  return (($obj->nb > 0)?true:false);
3303  }
3304  else
3305  {
3306  $this->error=$this->db->lasterror();
3307  return false;
3308  }
3309  }
3310 
3316  function getLibProspLevel()
3317  {
3318  return $this->LibProspLevel($this->fk_prospectlevel);
3319  }
3320 
3327  function LibProspLevel($fk_prospectlevel)
3328  {
3329  global $langs;
3330 
3331  $lib=$langs->trans("ProspectLevel".$fk_prospectlevel);
3332  // If lib not found in language file, we get label from cache/databse
3333  if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
3334  {
3335  $lib=$langs->getLabelFromKey($this->db,$fk_prospectlevel,'c_prospectlevel','code','label');
3336  }
3337  return $lib;
3338  }
3339 
3340 
3348  function set_prospect_level(User $user)
3349  {
3350  return $this->update($this->id, $user);
3351  }
3352 
3360  function getLibProspCommStatut($mode=0, $label='')
3361  {
3362  return $this->LibProspCommStatut($this->stcomm_id, $mode, $label);
3363  }
3364 
3373  function LibProspCommStatut($statut, $mode=0, $label='')
3374  {
3375  global $langs;
3376  $langs->load('customers');
3377 
3378  if ($mode == 2)
3379  {
3380  if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3381  elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3382  elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3383  elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3384  elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3385  else
3386  {
3387  return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3388  }
3389  }
3390  if ($mode == 3)
3391  {
3392  if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1);
3393  elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
3394  elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1);
3395  elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2);
3396  elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3);
3397  else
3398  {
3399  return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0);
3400  }
3401  }
3402  if ($mode == 4)
3403  {
3404  if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3405  elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3406  elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3407  elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3408  elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3409  else
3410  {
3411  return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3412  }
3413  }
3414 
3415  return "Error, mode/status not found";
3416  }
3417 
3425  function set_OutstandingBill(User $user)
3426  {
3427  return $this->update($this->id, $user);
3428  }
3429 
3436  function getOutstandingProposals($mode='customer')
3437  {
3438  $table='propal';
3439  if ($mode == 'supplier') $table = 'supplier_proposal';
3440 
3441  $sql = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3442  $sql .= " WHERE fk_soc = ". $this->id;
3443  if ($mode == 'supplier') {
3444  $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
3445  } else {
3446  $sql .= " AND entity IN (".getEntity('propal').")";
3447  }
3448 
3449  dol_syslog("getOutstandingProposals", LOG_DEBUG);
3450  $resql=$this->db->query($sql);
3451  if ($resql)
3452  {
3453  $outstandingOpened = 0;
3454  $outstandingTotal = 0;
3455  $outstandingTotalIncTax = 0;
3456  while($obj=$this->db->fetch_object($resql)) {
3457  $outstandingTotal+= $obj->total_ht;
3458  $outstandingTotalIncTax+= $obj->total_ttc;
3459  if ($obj->fk_statut != 0) // Not a draft
3460  {
3461  $outstandingOpened+=$obj->total_ttc;
3462  }
3463  }
3464  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);
3465  }
3466  else
3467  return array();
3468  }
3469 
3476  function getOutstandingOrders($mode='customer')
3477  {
3478  $table='commande';
3479  if ($mode == 'supplier') $table = 'commande_fournisseur';
3480 
3481  $sql = "SELECT rowid, total_ht, total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3482  $sql .= " WHERE fk_soc = ". $this->id;
3483  if ($mode == 'supplier') {
3484  $sql .= " AND entity IN (".getEntity('supplier_order').")";
3485  } else {
3486  $sql .= " AND entity IN (".getEntity('commande').")";
3487  }
3488 
3489  dol_syslog("getOutstandingOrders", LOG_DEBUG);
3490  $resql=$this->db->query($sql);
3491  if ($resql)
3492  {
3493  $outstandingOpened = 0;
3494  $outstandingTotal = 0;
3495  $outstandingTotalIncTax = 0;
3496  while($obj=$this->db->fetch_object($resql)) {
3497  $outstandingTotal+= $obj->total_ht;
3498  $outstandingTotalIncTax+= $obj->total_ttc;
3499  if ($obj->fk_statut != 0) // Not a draft
3500  {
3501  $outstandingOpened+=$obj->total_ttc;
3502  }
3503  }
3504  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);
3505  }
3506  else
3507  return array();
3508  }
3509 
3516  function getOutstandingBills($mode='customer')
3517  {
3518  $table='facture';
3519  if ($mode == 'supplier') $table = 'facture_fourn';
3520 
3521  /* Accurate value of remain to pay is to sum remaintopay for each invoice
3522  $paiement = $invoice->getSommePaiement();
3523  $creditnotes=$invoice->getSumCreditNotesUsed();
3524  $deposits=$invoice->getSumDepositsUsed();
3525  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3526  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3527  */
3528  if ($mode == 'supplier') $sql = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3529  else $sql = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3530  $sql .= " WHERE fk_soc = ". $this->id;
3531  if ($mode == 'supplier') {
3532  $sql .= " AND entity IN (".getEntity('facture_fourn').")";
3533  } else {
3534  $sql .= " AND entity IN (".getEntity('facture').")";
3535  }
3536 
3537  dol_syslog("getOutstandingBills", LOG_DEBUG);
3538  $resql=$this->db->query($sql);
3539  if ($resql)
3540  {
3541  $outstandingOpened = 0;
3542  $outstandingTotal = 0;
3543  $outstandingTotalIncTax = 0;
3544  if ($mode == 'supplier')
3545  {
3546  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
3547  $tmpobject=new FactureFournisseur($this->db);
3548  }
3549  else
3550  {
3551  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3552  $tmpobject=new Facture($this->db);
3553  }
3554  while($obj=$this->db->fetch_object($resql)) {
3555  $tmpobject->id=$obj->rowid;
3556  if ($obj->fk_statut != 0 // Not a draft
3557  && ! ($obj->fk_statut == 3 && $obj->close_code == 'replaced') // Not a replaced invoice
3558  )
3559  {
3560  $outstandingTotal+= $obj->total_ht;
3561  $outstandingTotalIncTax+= $obj->total_ttc;
3562  }
3563  if ($obj->paye == 0
3564  && $obj->fk_statut != 0 // Not a draft
3565  && $obj->fk_statut != 3 // Not abandonned
3566  && $obj->fk_statut != 2) // Not classified as paid
3567  //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
3568  {
3569  $paiement = $tmpobject->getSommePaiement();
3570  $creditnotes = $tmpobject->getSumCreditNotesUsed();
3571  $deposits = $tmpobject->getSumDepositsUsed();
3572  $outstandingOpened+=$obj->total_ttc - $paiement - $creditnotes - $deposits;
3573  }
3574  }
3575  return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);
3576  }
3577  else
3578  {
3579  return array();
3580  }
3581  }
3582 
3590  {
3591  /* Accurate value of remain to pay is to sum remaintopay for each invoice
3592  $paiement = $invoice->getSommePaiement();
3593  $creditnotes=$invoice->getSumCreditNotesUsed();
3594  $deposits=$invoice->getSumDepositsUsed();
3595  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3596  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3597  */
3598  $sql = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
3599  $sql .= " WHERE fk_soc = ". $this->id;
3600  $sql .= " AND paye = 0";
3601  $sql .= " AND fk_statut <> 0"; // Not a draft
3602  //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
3603  $sql .= " AND fk_statut <> 3"; // Not abandonned
3604  $sql .= " AND fk_statut <> 2"; // Not clasified as paid
3605 
3606  dol_syslog("get_OutstandingBill", LOG_DEBUG);
3607  $resql=$this->db->query($sql);
3608  if ($resql)
3609  {
3610  $outstandingAmount = 0;
3611  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3612  $tmpobject=new Facture($this->db);
3613  while($obj=$this->db->fetch_object($resql)) {
3614  $tmpobject->id=$obj->rowid;
3615  $paiement = $tmpobject->getSommePaiement();
3616  $creditnotes = $tmpobject->getSumCreditNotesUsed();
3617  $deposits = $tmpobject->getSumDepositsUsed();
3618  $outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
3619  }
3620  return $outstandingAmount;
3621  }
3622  else
3623  return 0;
3624  }
3625 
3632  {
3633  return $this->LibCustProspStatut($this->client);
3634  }
3635 
3642  function LibCustProspStatut($statut)
3643  {
3644  global $langs;
3645  $langs->load('companies');
3646 
3647  if ($statut==0) return $langs->trans("NorProspectNorCustomer");
3648  if ($statut==1) return $langs->trans("Customer");
3649  if ($statut==2) return $langs->trans("Prospect");
3650  if ($statut==3) return $langs->trans("ProspectCustomer");
3651 
3652  }
3653 
3654 
3666  public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
3667  {
3668  global $conf,$user,$langs;
3669 
3670  if (! empty($moreparams) && ! empty($moreparams['use_companybankid']))
3671  {
3672  $modelpath = "core/modules/bank/doc/";
3673 
3674  include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3675  $companybankaccount = new CompanyBankAccount($this->db);
3676  $result = $companybankaccount->fetch($moreparams['use_companybankid']);
3677  if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3678  $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3679  }
3680  else
3681  {
3682  // Positionne le modele sur le nom du modele a utiliser
3683  if (! dol_strlen($modele))
3684  {
3685  if (! empty($conf->global->COMPANY_ADDON_PDF))
3686  {
3687  $modele = $conf->global->COMPANY_ADDON_PDF;
3688  }
3689  else
3690  {
3691  print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
3692  return 0;
3693  }
3694  }
3695 
3696  $modelpath = "core/modules/societe/doc/";
3697 
3698  $result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3699  }
3700 
3701  return $result;
3702  }
3703 
3704 
3716  public function setCategories($categories, $type)
3717  {
3718  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3719 
3720  // Decode type
3721  if ($type == 'customer') {
3722  $type_id = Categorie::TYPE_CUSTOMER;
3723  $type_text = 'customer';
3724  } elseif ($type == 'supplier') {
3725  $type_id = Categorie::TYPE_SUPPLIER;
3726  $type_text = 'supplier';
3727  } else {
3728  dol_syslog(__METHOD__ . ': Type ' . $type . 'is an unknown company category type. Done nothing.', LOG_ERR);
3729  return -1;
3730  }
3731 
3732  // Handle single category
3733  if (!is_array($categories)) {
3734  $categories = array($categories);
3735  }
3736 
3737  // Get current categories
3738  $c = new Categorie($this->db);
3739  $existing = $c->containing($this->id, $type_id, 'id');
3740 
3741  // Diff
3742  if (is_array($existing)) {
3743  $to_del = array_diff($existing, $categories);
3744  $to_add = array_diff($categories, $existing);
3745  } else {
3746  $to_del = array(); // Nothing to delete
3747  $to_add = $categories;
3748  }
3749 
3750  // Process
3751  foreach ($to_del as $del) {
3752  if ($c->fetch($del) > 0) {
3753  $c->del_type($this, $type_text);
3754  }
3755  }
3756  foreach ($to_add as $add) {
3757  if ($c->fetch($add) > 0) {
3758  $c->add_type($this, $type_text);
3759  }
3760  }
3761 
3762  return 1;
3763  }
3764 
3765 
3775  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
3776  {
3781  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
3782  $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
3783  $sql .= ' SELECT fk_user ';
3784  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
3785  $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
3786 
3787  $query = $db->query($sql);
3788 
3789  while ($result = $db->fetch_object($query)) {
3790  $db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$result->rowid);
3791  }
3792 
3797  $tables = array(
3798  'societe_address',
3799  'societe_commerciaux',
3800  'societe_log',
3801  'societe_prices',
3802  'societe_remise',
3803  'societe_remise_except',
3804  'societe_rib'
3805  );
3806 
3807  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
3808  }
3809 }
__construct($db)
Constructor.
useLocalTax($localTaxNum=0)
Check if we must use localtax feature or not according to country (country of $mysoc in most cases)...
check_codeclient()
Check customer code.
create(User $user)
Create third party in database.
getAvailableDiscounts($user='', $filter='', $maxvalue=0)
Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe.
thirdparty_and_contact_email_array($addthirdparty=0)
Return list of contacts emails existing for third party.
getLibStatut($mode=0)
Return label of status (activity, closed)
Class to stock current configuration.
Definition: conf.class.php:33
create_from_member(Adherent $member, $socname='', $socalias='')
Create a third party into database from a member object.
fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='')
Load a third party from database into memory.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='')
Show picto whatever it's its name (generic function)
id_prof_url($idprof, $thirdparty)
Return an url to check online a professional id or empty string.
del_commercial(User $user, $commid)
Add link to sales representative.
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.
getLibCustProspStatut()
Return label of status customer is prospect/customer.
static getIdFromCode(&$db, $code)
Get id of currency from code.
useNPR()
Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in m...
LibCustProspStatut($statut)
Renvoi le libelle d'un statut donne.
initAsSpecimen()
Initialise an instance with random values.
isACompany()
Return if third party is a company (Business) or an end user (Consumer)
add_commercial(User $user, $commid)
Add link to sales representative.
isObjectUsed($id=0)
Function to check if an object is used by others.
Class to manage contact/addresses.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
set_parent($id)
Define parent commany of current company.
get_codefournisseur($objsoc=0, $type=1)
Attribut un code fournisseur a partir du module de controle des codes.
Class to manage Dolibarr users.
Definition: user.class.php:39
Class to manage Dolibarr database access.
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1)
Return a link on thirdparty (with picto)
setCategories($categories, $type)
Sets object to supplied categories.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Class to manage bank accounts description of third parties.
thirdparty_and_contact_phone_array()
Return list of contacts mobile phone existing for third party.
clean_url($url, $http=1)
Clean an url string.
getOutstandingProposals($mode='customer')
Return amount of order not paid and total.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0)
Return HTML code to output a photo.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:414
id_prof_exists($idprof, $value, $socid=0)
Verify if a profid exists into database for others thirds.
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
Class to manage suppliers invoices.
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
LibProspLevel($fk_prospectlevel)
Return label of prospect level.
LibProspCommStatut($statut, $mode=0, $label='')
Return label of a given status.
contact_property_array($mode='email', $hidedisabled=0)
Return list of contacts emails or mobile existing for third party.
create_individual(User $user)
Create a contact/address from thirdparty.
has_projects()
Indique si la societe a des projets.
getOutstandingOrders($mode='customer')
Return amount of order not paid and total.
LoadSupplierCateg()
Charge la liste des categories fournisseurs.
id_prof_verifiable($idprof)
Returns if a profid sould be verified.
get_codeclient($objsoc=0, $type=0)
Attribut un code client a partir du module de controle des codes.
fetch_object($resultset)
Renvoie la ligne courante (comme un objet) pour le curseur resultset.
Class to manage hooks.
set_remise_except($remise, User $user, $desc, $tva_tx=0)
Add a discount for third party.
getLibProspLevel()
Return prostect level.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
Class to manage third parties objects (customers, suppliers, prospects...)
img_action($titlealt, $numaction)
Show logo action.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Class to manage categories.
getLibProspCommStatut($mode=0, $label='')
Return status of prospect.
codeclient_modifiable()
Verifie si un code client est modifiable en fonction des parametres du module de controle des codes...
set_as_client()
Define third party as a customer.
LibStatut($statut, $mode=0)
Renvoi le libelle d'un statut donne.
Class to manage withdrawal receipts.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
query($query, $usesavepoint=0, $type= 'auto')
Execute a SQL request and return the resultset.
contact_get_property($rowid, $mode)
Return property of contact from its id.
set_remise_client($remise, $note, User $user)
Definit la societe comme un client.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories) ...
Definition: files.lib.php:1234
Class to manage members of a foundation.
getEntity($element, $shared=1, $forceentity=null)
Get list of entity id to use.
getSalesRepresentatives(User $user)
Return array of sales representatives.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
info($id)
Load information for tab info.
set_OutstandingBill(User $user)
Set outstanding value.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
get_OutstandingBill()
Return amount of bill not paid.
deleteExtraFields()
Delete all extra fields values for the current object.
searchByName($name, $type='0', $filters=array(), $exact=false, $case=false, $similar=false, $clause= 'AND')
Search and fetch thirparties by name.
dol_now($mode='gmt')
Return date for now.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:104
get_codecompta($type)
Renvoie un code compta, suivant le module de code compta.
set_prospect_level(User $user)
Set prospect level.
contact_array_objects()
Renvoie la liste des contacts de cette societe.
verify()
Check properties of third party are ok (like name, third party codes, ...) Used before an add or upda...
print
Draft customers invoices.
Definition: index.php:91
getOutstandingBills($mode='customer')
Return amount of bill not paid and total.
useRevenueStamp()
Check if we must use revenue stamps feature or not according to country (country of $mysocin most cas...
codefournisseur_modifiable()
Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes...
$stcomm_id
code statut prospect
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if(!empty($conf->fournisseur->enabled)&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->societe->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if(!empty($conf->fournisseur->enabled)&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1013
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Return a prefix to use for this Dolibarr instance, for session/cookie names or email id...
Class to manage absolute discounts.
contact_array()
Renvoie la liste des contacts de cette societe.
Class to manage invoices.
setMysoc(Conf $conf)
Set properties with value into $conf.
call_trigger($trigger_name, $user)
Call trigger based on this instance.
AddFournisseurInCategory($categorie_id)
Insert link supplier - category.
check_codefournisseur()
Check supplier code.
set_price_level($price_level, User $user)
Set the price level.
get_all_rib()
Return Array of RIB.
id_prof_check($idprof, $soc)
Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren...
price2num($amount, $rounding='', $alreadysqlnb=0)
Function that return a number with universal decimal format (decimal separator is '...
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
display_rib($mode='label')
Return bank number property of thirdparty (label or rum)
update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
Update parameters of third party.