dolibarr  17.0.4
api_thirdparties.class.php
1 <?php
2 /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3  * Copyright (C) 2018 Pierre Chéné <pierre.chene44@gmail.com>
4  * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com>
5  * Copyright (C) 2020-2021 Frédéric France <frederic.france@netlogic.fr>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <https://www.gnu.org/licenses/>.
19  */
20 
21 use Luracast\Restler\RestException;
22 
31 {
36  public static $FIELDS = array(
37  'name'
38  );
39 
43  public $company;
44 
48  public function __construct()
49  {
50  global $db, $conf;
51  $this->db = $db;
52 
53  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
54  require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
55  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
56  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
57 
58  $this->company = new Societe($this->db);
59 
60  if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY)) {
61  static::$FIELDS[] = 'email';
62  }
63  }
64 
75  public function get($id)
76  {
77  return $this->_fetch($id);
78  }
79 
92  public function getByEmail($email)
93  {
94  return $this->_fetch('', '', '', '', '', '', '', '', '', '', $email);
95  }
96 
109  public function getByBarcode($barcode)
110  {
111  return $this->_fetch('', '', '', $barcode);
112  }
113 
131  public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '')
132  {
133  $obj_ret = array();
134 
135  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
136  throw new RestException(401);
137  }
138 
139  // case of external user, we force socids
140  $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
141 
142  // If the internal user must only see his customers, force searching by him
143  $search_sale = 0;
144  if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
145  $search_sale = DolibarrApiAccess::$user->id;
146  }
147 
148  $sql = "SELECT t.rowid";
149  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
150  $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
151  }
152  $sql .= " FROM ".MAIN_DB_PREFIX."societe as t";
153  if ($category > 0) {
154  if ($mode != 4) {
155  $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c";
156  }
157  if (!in_array($mode, array(1, 2, 3))) {
158  $sql .= ", ".MAIN_DB_PREFIX."categorie_fournisseur as cc";
159  }
160  }
161  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
162  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
163  }
164  $sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st";
165  $sql .= " WHERE t.entity IN (".getEntity('societe').")";
166  $sql .= " AND t.fk_stcomm = st.id";
167 
168  if ($mode == 1) {
169  $sql .= " AND t.client IN (1, 3)";
170  } elseif ($mode == 2) {
171  $sql .= " AND t.client IN (2, 3)";
172  } elseif ($mode == 3) {
173  $sql .= " AND t.client IN (0)";
174  } elseif ($mode == 4) {
175  $sql .= " AND t.fournisseur IN (1)";
176  }
177 
178  // Select thirdparties of given category
179  if ($category > 0) {
180  if (!empty($mode) && $mode != 4) {
181  $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid";
182  } elseif (!empty($mode) && $mode == 4) {
183  $sql .= " AND cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid";
184  } else {
185  $sql .= " AND ((c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid) OR (cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid))";
186  }
187  }
188 
189  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
190  $sql .= " AND t.rowid = sc.fk_soc";
191  }
192  //if ($email != NULL) $sql.= " AND s.email = \"".$email."\"";
193  if ($socids) {
194  $sql .= " AND t.rowid IN (".$this->db->sanitize($socids).")";
195  }
196  if ($search_sale > 0) {
197  $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
198  }
199  // Insert sale filter
200  if ($search_sale > 0) {
201  $sql .= " AND sc.fk_user = ".((int) $search_sale);
202  }
203  // Add sql filters
204  if ($sqlfilters) {
205  $errormessage = '';
206  $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
207  if ($errormessage) {
208  throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
209  }
210  }
211 
212  $sql .= $this->db->order($sortfield, $sortorder);
213 
214  if ($limit) {
215  if ($page < 0) {
216  $page = 0;
217  }
218  $offset = $limit * $page;
219 
220  $sql .= $this->db->plimit($limit + 1, $offset);
221  }
222 
223  $result = $this->db->query($sql);
224  if ($result) {
225  $num = $this->db->num_rows($result);
226  $min = min($num, ($limit <= 0 ? $num : $limit));
227  $i = 0;
228  while ($i < $min) {
229  $obj = $this->db->fetch_object($result);
230  $soc_static = new Societe($this->db);
231  if ($soc_static->fetch($obj->rowid)) {
232  if (isModEnabled('mailing')) {
233  $soc_static->getNoEmail();
234  }
235  $obj_ret[] = $this->_cleanObjectDatas($soc_static);
236  }
237  $i++;
238  }
239  } else {
240  throw new RestException(503, 'Error when retrieve thirdparties : '.$this->db->lasterror());
241  }
242  if (!count($obj_ret)) {
243  throw new RestException(404, 'Thirdparties not found');
244  }
245  return $obj_ret;
246  }
247 
254  public function post($request_data = null)
255  {
256  if (!DolibarrApiAccess::$user->rights->societe->creer) {
257  throw new RestException(401);
258  }
259  // Check mandatory fields
260  $result = $this->_validate($request_data);
261 
262  foreach ($request_data as $field => $value) {
263  $this->company->$field = $value;
264  }
265  if ($this->company->create(DolibarrApiAccess::$user) < 0) {
266  throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors));
267  }
268  if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
269  $this->company->setNoEmail($this->company->no_email);
270  }
271 
272  return $this->company->id;
273  }
274 
282  public function put($id, $request_data = null)
283  {
284  if (!DolibarrApiAccess::$user->rights->societe->creer) {
285  throw new RestException(401);
286  }
287 
288  $result = $this->company->fetch($id);
289  if (!$result) {
290  throw new RestException(404, 'Thirdparty not found');
291  }
292 
293  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
294  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
295  }
296 
297  foreach ($request_data as $field => $value) {
298  if ($field == 'id') {
299  continue;
300  }
301  $this->company->$field = $value;
302  }
303 
304  if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
305  $this->company->setNoEmail($this->company->no_email);
306  }
307 
308  if ($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update', 1)) {
309  return $this->get($id);
310  }
311 
312  return false;
313  }
314 
329  public function merge($id, $idtodelete)
330  {
331  global $hookmanager;
332 
333  $error = 0;
334 
335  if ($id == $idtodelete) {
336  throw new RestException(400, 'Try to merge a thirdparty into itself');
337  }
338 
339  if (!DolibarrApiAccess::$user->rights->societe->creer) {
340  throw new RestException(401);
341  }
342 
343  $result = $this->company->fetch($id); // include the fetch of extra fields
344  if (!$result) {
345  throw new RestException(404, 'Thirdparty not found');
346  }
347 
348  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
349  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
350  }
351 
352  $this->companytoremove = new Societe($this->db);
353 
354  $result = $this->companytoremove->fetch($idtodelete); // include the fetch of extra fields
355  if (!$result) {
356  throw new RestException(404, 'Thirdparty not found');
357  }
358 
359  if (!DolibarrApi::_checkAccessToResource('societe', $this->companytoremove->id)) {
360  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
361  }
362 
363  $soc_origin = $this->companytoremove;
364  $object = $this->company;
365  $user = DolibarrApiAccess::$user;
366 
367 
368  // Call same code than into action 'confirm_merge'
369 
370 
371  $this->db->begin();
372 
373  // Recopy some data
374  $object->client = $object->client | $soc_origin->client;
375  $object->fournisseur = $object->fournisseur | $soc_origin->fournisseur;
376  $listofproperties = array(
377  'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode',
378  'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
379  'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
380  'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency',
381  'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
382  'model_pdf', 'fk_projet'
383  );
384  foreach ($listofproperties as $property) {
385  if (empty($object->$property)) {
386  $object->$property = $soc_origin->$property;
387  }
388  }
389 
390  // Concat some data
391  $listofproperties = array(
392  'note_public', 'note_private'
393  );
394  foreach ($listofproperties as $property) {
395  $object->$property = dol_concatdesc($object->$property, $soc_origin->$property);
396  }
397 
398  // Merge extrafields
399  if (is_array($soc_origin->array_options)) {
400  foreach ($soc_origin->array_options as $key => $val) {
401  if (empty($object->array_options[$key])) {
402  $object->array_options[$key] = $val;
403  }
404  }
405  }
406 
407  // Merge categories
408  $static_cat = new Categorie($this->db);
409  $custcats = $static_cat->containing($soc_origin->id, 'customer', 'id');
410  $object->setCategories($custcats, 'customer');
411  $suppcats = $static_cat->containing($soc_origin->id, 'supplier', 'id');
412  $object->setCategories($suppcats, 'supplier');
413 
414  // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
415  if ($soc_origin->code_client == $object->code_client
416  || $soc_origin->code_fournisseur == $object->code_fournisseur
417  || $soc_origin->barcode == $object->barcode) {
418  dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
419  $soc_origin->code_client = '';
420  $soc_origin->code_fournisseur = '';
421  $soc_origin->barcode = '';
422  $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
423  }
424 
425  // Update
426  $result = $object->update($object->id, $user, 0, 1, 1, 'merge');
427  if ($result < 0) {
428  $error++;
429  }
430 
431  // Move links
432  if (!$error) {
433  // This list is also into the societe/card.php file
434  // TODO Mutualise the list into object societe.class.php
435  $objects = array(
436  'Adherent' => '/adherents/class/adherent.class.php',
437  'Don' => '/don/class/don.class.php',
438  'Societe' => '/societe/class/societe.class.php',
439  //'Categorie' => '/categories/class/categorie.class.php',
440  'ActionComm' => '/comm/action/class/actioncomm.class.php',
441  'Propal' => '/comm/propal/class/propal.class.php',
442  'Commande' => '/commande/class/commande.class.php',
443  'Facture' => '/compta/facture/class/facture.class.php',
444  'FactureRec' => '/compta/facture/class/facture-rec.class.php',
445  'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
446  'Mo' => '/mrp/class/mo.class.php',
447  'Contact' => '/contact/class/contact.class.php',
448  'Contrat' => '/contrat/class/contrat.class.php',
449  'Expedition' => '/expedition/class/expedition.class.php',
450  'Fichinter' => '/fichinter/class/fichinter.class.php',
451  'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
452  'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
453  'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
454  'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
455  'Delivery' => '/delivery/class/delivery.class.php',
456  'Product' => '/product/class/product.class.php',
457  'Project' => '/projet/class/project.class.php',
458  'Ticket' => '/ticket/class/ticket.class.php',
459  'User' => '/user/class/user.class.php',
460  'Account' => '/compta/bank/class/account.class.php',
461  'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php'
462  );
463 
464  //First, all core objects must update their tables
465  foreach ($objects as $object_name => $object_file) {
466  require_once DOL_DOCUMENT_ROOT.$object_file;
467 
468  if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $object->id)) {
469  $error++;
470  //setEventMessages($this->db->lasterror(), null, 'errors');
471  }
472  }
473  }
474 
475  // External modules should update their ones too
476  if (!$error) {
477  $reshook = $hookmanager->executeHooks('replaceThirdparty', array(
478  'soc_origin' => $soc_origin->id,
479  'soc_dest' => $object->id
480  ), $soc_dest, $action);
481 
482  if ($reshook < 0) {
483  //setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
484  $error++;
485  }
486  }
487 
488 
489  if (!$error) {
490  $object->context = array('merge'=>1, 'mergefromid'=>$soc_origin->id);
491 
492  // Call trigger
493  $result = $object->call_trigger('COMPANY_MODIFY', $user);
494  if ($result < 0) {
495  //setEventMessages($object->error, $object->errors, 'errors');
496  $error++;
497  }
498  // End call triggers
499  }
500 
501  if (!$error) {
502  //We finally remove the old thirdparty
503  if ($soc_origin->delete($soc_origin->id, $user) < 1) {
504  $error++;
505  }
506  }
507 
508  // End of merge
509 
510  if ($error) {
511  $this->db->rollback();
512 
513  throw new RestException(500, 'Error failed to merged thirdparty '.$this->companytoremove->id.' into '.$id.'. Enable and read log file for more information.');
514  } else {
515  $this->db->commit();
516  }
517 
518  return $this->get($id);
519  }
520 
527  public function delete($id)
528  {
529  if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
530  throw new RestException(401);
531  }
532  $result = $this->company->fetch($id);
533  if (!$result) {
534  throw new RestException(404, 'Thirdparty not found');
535  }
536  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
537  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
538  }
539  $this->company->oldcopy = clone $this->company;
540 
541  $res = $this->company->delete($id);
542  if ($res < 0) {
543  throw new RestException(500, "Can't delete, error occurs");
544  } elseif ($res == 0) {
545  throw new RestException(409, "Can't delete, that product is probably used");
546  }
547 
548  return array(
549  'success' => array(
550  'code' => 200,
551  'message' => 'Object deleted'
552  )
553  );
554  }
555 
571  public function setThirdpartyPriceLevel($id, $priceLevel)
572  {
573  global $conf;
574 
575  if (!isModEnabled('societe')) {
576  throw new RestException(501, 'Module "Thirdparties" needed for this request');
577  }
578 
579  if (empty($conf->product->enabled)) {
580  throw new RestException(501, 'Module "Products" needed for this request');
581  }
582 
583  if (empty($conf->global->PRODUIT_MULTIPRICES)) {
584  throw new RestException(501, 'Multiprices features activation needed for this request');
585  }
586 
587  if ($priceLevel < 1 || $priceLevel > $conf->global->PRODUIT_MULTIPRICES_LIMIT) {
588  throw new RestException(400, 'Price level must be between 1 and '.$conf->global->PRODUIT_MULTIPRICES_LIMIT);
589  }
590 
591  if (empty(DolibarrApiAccess::$user->rights->societe->creer)) {
592  throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
593  }
594 
595  $result = $this->company->fetch($id);
596  if ($result < 0) {
597  throw new RestException(404, 'Thirdparty '.$id.' not found');
598  }
599 
600  if (empty($result)) {
601  throw new RestException(500, 'Error fetching thirdparty '.$id, array_merge(array($this->company->error), $this->company->errors));
602  }
603 
604  if (empty(DolibarrApi::_checkAccessToResource('societe', $this->company->id))) {
605  throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
606  }
607 
608  $result = $this->company->setPriceLevel($priceLevel, DolibarrApiAccess::$user);
609  if ($result <= 0) {
610  throw new RestException(500, 'Error setting new price level for thirdparty '.$id, array($this->company->db->lasterror()));
611  }
612 
613  return $this->_cleanObjectDatas($this->company);
614  }
615 
629  public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
630  {
631  if (!DolibarrApiAccess::$user->rights->categorie->lire) {
632  throw new RestException(401);
633  }
634 
635  $result = $this->company->fetch($id);
636  if (!$result) {
637  throw new RestException(404, 'Thirdparty not found');
638  }
639 
640  $categories = new Categorie($this->db);
641 
642  $result = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page);
643 
644  if (is_numeric($result) && $result < 0) {
645  throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
646  }
647 
648  if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
649  return array();
650  }
651 
652  return $result;
653  }
654 
665  public function addCategory($id, $category_id)
666  {
667  if (!DolibarrApiAccess::$user->rights->societe->creer) {
668  throw new RestException(401);
669  }
670 
671  $result = $this->company->fetch($id);
672  if (!$result) {
673  throw new RestException(404, 'Thirdparty not found');
674  }
675  $category = new Categorie($this->db);
676  $result = $category->fetch($category_id);
677  if (!$result) {
678  throw new RestException(404, 'category not found');
679  }
680 
681  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
682  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
683  }
684  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
685  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
686  }
687 
688  $category->add_type($this->company, 'customer');
689 
690  return $this->_cleanObjectDatas($this->company);
691  }
692 
703  public function deleteCategory($id, $category_id)
704  {
705  if (!DolibarrApiAccess::$user->rights->societe->creer) {
706  throw new RestException(401);
707  }
708 
709  $result = $this->company->fetch($id);
710  if (!$result) {
711  throw new RestException(404, 'Thirdparty not found');
712  }
713  $category = new Categorie($this->db);
714  $result = $category->fetch($category_id);
715  if (!$result) {
716  throw new RestException(404, 'category not found');
717  }
718 
719  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
720  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
721  }
722  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
723  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
724  }
725 
726  $category->del_type($this->company, 'customer');
727 
728  return $this->_cleanObjectDatas($this->company);
729  }
730 
744  public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
745  {
746  if (!DolibarrApiAccess::$user->rights->categorie->lire) {
747  throw new RestException(401);
748  }
749 
750  $result = $this->company->fetch($id);
751  if (!$result) {
752  throw new RestException(404, 'Thirdparty not found');
753  }
754 
755  $categories = new Categorie($this->db);
756 
757  $result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page);
758 
759  if (is_numeric($result) && $result < 0) {
760  throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
761  }
762 
763  if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
764  return array();
765  }
766 
767  return $result;
768  }
769 
780  public function addSupplierCategory($id, $category_id)
781  {
782  if (!DolibarrApiAccess::$user->rights->societe->creer) {
783  throw new RestException(401);
784  }
785 
786  $result = $this->company->fetch($id);
787  if (!$result) {
788  throw new RestException(404, 'Thirdparty not found');
789  }
790  $category = new Categorie($this->db);
791  $result = $category->fetch($category_id);
792  if (!$result) {
793  throw new RestException(404, 'category not found');
794  }
795 
796  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
797  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
798  }
799  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
800  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
801  }
802 
803  $category->add_type($this->company, 'supplier');
804 
805  return $this->_cleanObjectDatas($this->company);
806  }
807 
818  public function deleteSupplierCategory($id, $category_id)
819  {
820  if (!DolibarrApiAccess::$user->rights->societe->creer) {
821  throw new RestException(401);
822  }
823 
824  $result = $this->company->fetch($id);
825  if (!$result) {
826  throw new RestException(404, 'Thirdparty not found');
827  }
828  $category = new Categorie($this->db);
829  $result = $category->fetch($category_id);
830  if (!$result) {
831  throw new RestException(404, 'category not found');
832  }
833 
834  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
835  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
836  }
837  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
838  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
839  }
840 
841  $category->del_type($this->company, 'supplier');
842 
843  return $this->_cleanObjectDatas($this->company);
844  }
845 
846 
861  public function getOutStandingProposals($id, $mode = 'customer')
862  {
863  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
864  throw new RestException(401);
865  }
866 
867  if (empty($id)) {
868  throw new RestException(400, 'Thirdparty ID is mandatory');
869  }
870 
871  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
872  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
873  }
874 
875  $result = $this->company->fetch($id);
876  if (!$result) {
877  throw new RestException(404, 'Thirdparty not found');
878  }
879 
880  $result = $this->company->getOutstandingProposals($mode);
881 
882  unset($result['total_ht']);
883  unset($result['total_ttc']);
884 
885  return $result;
886  }
887 
888 
903  public function getOutStandingOrder($id, $mode = 'customer')
904  {
905  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
906  throw new RestException(401);
907  }
908 
909  if (empty($id)) {
910  throw new RestException(400, 'Thirdparty ID is mandatory');
911  }
912 
913  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
914  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
915  }
916 
917  $result = $this->company->fetch($id);
918  if (!$result) {
919  throw new RestException(404, 'Thirdparty not found');
920  }
921 
922  $result = $this->company->getOutstandingOrders($mode);
923 
924  unset($result['total_ht']);
925  unset($result['total_ttc']);
926 
927  return $result;
928  }
929 
944  public function getOutStandingInvoices($id, $mode = 'customer')
945  {
946  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
947  throw new RestException(401);
948  }
949 
950  if (empty($id)) {
951  throw new RestException(400, 'Thirdparty ID is mandatory');
952  }
953 
954  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
955  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
956  }
957 
958  $result = $this->company->fetch($id);
959  if (!$result) {
960  throw new RestException(404, 'Thirdparty not found');
961  }
962 
963  $result = $this->company->getOutstandingBills($mode);
964 
965  unset($result['total_ht']);
966  unset($result['total_ttc']);
967 
968  return $result;
969  }
970 
985  public function getSalesRepresentatives($id, $mode = 0)
986  {
987  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
988  throw new RestException(401);
989  }
990 
991  if (empty($id)) {
992  throw new RestException(400, 'Thirdparty ID is mandatory');
993  }
994 
995  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
996  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
997  }
998 
999  $result = $this->company->fetch($id);
1000  if (!$result) {
1001  throw new RestException(404, 'Thirdparty not found');
1002  }
1003 
1004  $result = $this->company->getSalesRepresentatives(DolibarrApiAccess::$user, $mode);
1005 
1006  return $result;
1007  }
1008 
1026  public function getFixedAmountDiscounts($id, $filter = "none", $sortfield = "f.type", $sortorder = 'ASC')
1027  {
1028  $obj_ret = array();
1029 
1030  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1031  throw new RestException(401);
1032  }
1033 
1034  if (empty($id)) {
1035  throw new RestException(400, 'Thirdparty ID is mandatory');
1036  }
1037 
1038  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1039  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1040  }
1041 
1042  $result = $this->company->fetch($id);
1043  if (!$result) {
1044  throw new RestException(404, 'Thirdparty not found');
1045  }
1046 
1047 
1048  $sql = "SELECT f.ref, f.type as factype, re.fk_facture_source, re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc, re.description, re.fk_facture, re.fk_facture_line";
1049  $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re, ".MAIN_DB_PREFIX."facture as f";
1050  $sql .= " WHERE f.rowid = re.fk_facture_source AND re.fk_soc = ".((int) $id);
1051  if ($filter == "available") {
1052  $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL";
1053  }
1054  if ($filter == "used") {
1055  $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)";
1056  }
1057 
1058  $sql .= $this->db->order($sortfield, $sortorder);
1059 
1060  $result = $this->db->query($sql);
1061  if (!$result) {
1062  throw new RestException(503, $this->db->lasterror());
1063  } else {
1064  $num = $this->db->num_rows($result);
1065  while ($obj = $this->db->fetch_object($result)) {
1066  $obj_ret[] = $obj;
1067  }
1068  }
1069 
1070  return $obj_ret;
1071  }
1072 
1073 
1074 
1089  {
1090  if (!DolibarrApiAccess::$user->rights->facture->lire) {
1091  throw new RestException(401);
1092  }
1093  if (empty($id)) {
1094  throw new RestException(400, 'Thirdparty ID is mandatory');
1095  }
1096 
1097  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1098  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1099  }
1100 
1101  /*$result = $this->thirdparty->fetch($id);
1102  if( ! $result ) {
1103  throw new RestException(404, 'Thirdparty not found');
1104  }*/
1105 
1106  $invoice = new Facture($this->db);
1107  $result = $invoice->list_replacable_invoices($id);
1108  if ($result < 0) {
1109  throw new RestException(405, $invoice->error);
1110  }
1111 
1112  return $result;
1113  }
1114 
1132  {
1133  if (!DolibarrApiAccess::$user->rights->facture->lire) {
1134  throw new RestException(401);
1135  }
1136  if (empty($id)) {
1137  throw new RestException(400, 'Thirdparty ID is mandatory');
1138  }
1139 
1140  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1141  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1142  }
1143 
1144  /*$result = $this->thirdparty->fetch($id);
1145  if( ! $result ) {
1146  throw new RestException(404, 'Thirdparty not found');
1147  }*/
1148 
1149  $invoice = new Facture($this->db);
1150  $result = $invoice->list_qualified_avoir_invoices($id);
1151  if ($result < 0) {
1152  throw new RestException(405, $invoice->error);
1153  }
1154 
1155  return $result;
1156  }
1157 
1167  public function getCompanyBankAccount($id)
1168  {
1169  if (!DolibarrApiAccess::$user->rights->societe->lire) {
1170  throw new RestException(401);
1171  }
1172  if (empty($id)) {
1173  throw new RestException(400, 'Thirdparty ID is mandatory');
1174  }
1175 
1176  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1177  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1178  }
1179 
1184  $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,";
1185  $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur";
1186  $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1187  if ($id) {
1188  $sql .= " WHERE fk_soc = ".((int) $id);
1189  }
1190 
1191  $result = $this->db->query($sql);
1192 
1193  if ($this->db->num_rows($result) == 0) {
1194  throw new RestException(404, 'Account not found');
1195  }
1196 
1197  $i = 0;
1198 
1199  $accounts = array();
1200 
1201  if ($result) {
1202  $num = $this->db->num_rows($result);
1203  while ($i < $num) {
1204  $obj = $this->db->fetch_object($result);
1205  $account = new CompanyBankAccount($this->db);
1206  if ($account->fetch($obj->rowid)) {
1207  $accounts[] = $account;
1208  }
1209  $i++;
1210  }
1211  } else {
1212  throw new RestException(404, 'Account not found');
1213  }
1214 
1215 
1216  $fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum');
1217 
1218  $returnAccounts = array();
1219 
1220  foreach ($accounts as $account) {
1221  $object = array();
1222  foreach ($account as $key => $value) {
1223  if (in_array($key, $fields)) {
1224  $object[$key] = $value;
1225  }
1226  }
1227  $returnAccounts[] = $object;
1228  }
1229 
1230  return $returnAccounts;
1231  }
1232 
1242  public function createCompanyBankAccount($id, $request_data = null)
1243  {
1244  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1245  throw new RestException(401);
1246  }
1247  if ($this->company->fetch($id) <= 0) {
1248  throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1249  }
1250  $account = new CompanyBankAccount($this->db);
1251 
1252  $account->socid = $id;
1253 
1254  foreach ($request_data as $field => $value) {
1255  $account->$field = $value;
1256  }
1257 
1258  if ($account->create(DolibarrApiAccess::$user) < 0) {
1259  throw new RestException(500, 'Error creating Company Bank account');
1260  }
1261 
1262  if (empty($account->rum)) {
1263  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1264  $prelevement = new BonPrelevement($this->db);
1265  $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1266  $account->date_rum = dol_now();
1267  }
1268 
1269  if ($account->update(DolibarrApiAccess::$user) < 0) {
1270  throw new RestException(500, 'Error updating values');
1271  }
1272 
1273  return $this->_cleanObjectDatas($account);
1274  }
1275 
1287  public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
1288  {
1289  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1290  throw new RestException(401);
1291  }
1292  if ($this->company->fetch($id) <= 0) {
1293  throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1294  }
1295  $account = new CompanyBankAccount($this->db);
1296 
1297  $account->fetch($bankaccount_id, $id, -1, '');
1298 
1299  if ($account->socid != $id) {
1300  throw new RestException(401);
1301  }
1302 
1303 
1304  foreach ($request_data as $field => $value) {
1305  $account->$field = $value;
1306  }
1307 
1308  if (empty($account->rum)) {
1309  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1310  $prelevement = new BonPrelevement($this->db);
1311  $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1312  $account->date_rum = dol_now();
1313  }
1314 
1315  if ($account->update(DolibarrApiAccess::$user) < 0) {
1316  throw new RestException(500, 'Error updating values');
1317  }
1318 
1319  return $this->_cleanObjectDatas($account);
1320  }
1321 
1332  public function deleteCompanyBankAccount($id, $bankaccount_id)
1333  {
1334  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1335  throw new RestException(401);
1336  }
1337 
1338  $account = new CompanyBankAccount($this->db);
1339 
1340  $account->fetch($bankaccount_id);
1341 
1342  if (!$account->socid == $id) {
1343  throw new RestException(401);
1344  }
1345 
1346  return $account->delete(DolibarrApiAccess::$user);
1347  }
1348 
1359  public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
1360  {
1361  global $conf, $langs;
1362 
1363  $langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals"));
1364 
1365  if ($this->company->fetch($id) <= 0) {
1366  throw new RestException(404, 'Thirdparty not found');
1367  }
1368 
1369  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1370  throw new RestException(401);
1371  }
1372 
1373  $this->company->setDocModel(DolibarrApiAccess::$user, $model);
1374 
1375  $this->company->fk_bank = $this->company->fk_account;
1376 
1377  $outputlangs = $langs;
1378  $newlang = '';
1379 
1380  //if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
1381  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1382  if (isset($this->company->thirdparty->default_lang)) {
1383  $newlang = $this->company->thirdparty->default_lang; // for proposal, order, invoice, ...
1384  } elseif (isset($this->company->default_lang)) {
1385  $newlang = $this->company->default_lang; // for thirdparty
1386  }
1387  }
1388  if (!empty($newlang)) {
1389  $outputlangs = new Translate("", $conf);
1390  $outputlangs->setDefaultLang($newlang);
1391  }
1392 
1393  $sql = "SELECT rowid";
1394  $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1395  if ($id) {
1396  $sql .= " WHERE fk_soc = ".((int) $id);
1397  }
1398  if ($companybankid) {
1399  $sql .= " AND rowid = ".((int) $companybankid);
1400  }
1401 
1402  $i = 0;
1403  $accounts = array();
1404 
1405  $result = $this->db->query($sql);
1406  if ($result) {
1407  if ($this->db->num_rows($result) == 0) {
1408  throw new RestException(404, 'Bank account not found');
1409  }
1410 
1411  $num = $this->db->num_rows($result);
1412  while ($i < $num) {
1413  $obj = $this->db->fetch_object($result);
1414 
1415  $account = new CompanyBankAccount($this->db);
1416  if ($account->fetch($obj->rowid)) {
1417  $accounts[] = $account;
1418  }
1419  $i++;
1420  }
1421  } else {
1422  throw new RestException(500, 'Sql error '.$this->db->lasterror());
1423  }
1424 
1425  $moreparams = array(
1426  'use_companybankid' => $accounts[0]->id,
1427  'force_dir_output' => $conf->societe->multidir_output[$this->company->entity].'/'.dol_sanitizeFileName($this->company->id)
1428  );
1429 
1430  $result = $this->company->generateDocument($model, $outputlangs, 0, 0, 0, $moreparams);
1431 
1432  if ($result > 0) {
1433  return array("success" => $result);
1434  } else {
1435  throw new RestException(500, 'Error generating the document '.$this->company->error);
1436  }
1437  }
1438 
1451  public function getSocieteAccounts($id, $site = null)
1452  {
1453  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1454  throw new RestException(401);
1455  }
1456 
1457  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1458  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1459  }
1460 
1464  $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
1465  $sql .= " WHERE fk_soc = ".((int) $id);
1466  if ($site) {
1467  $sql .= " AND site ='".$this->db->escape($site)."'";
1468  }
1469 
1470  $result = $this->db->query($sql);
1471 
1472  if ($result && $this->db->num_rows($result) == 0) {
1473  throw new RestException(404, 'This thirdparty does not have any gateway attached or does not exist.');
1474  }
1475 
1476  $i = 0;
1477 
1478  $accounts = array();
1479 
1480  $num = $this->db->num_rows($result);
1481  while ($i < $num) {
1482  $obj = $this->db->fetch_object($result);
1483  $account = new SocieteAccount($this->db);
1484 
1485  if ($account->fetch($obj->rowid)) {
1486  $accounts[] = $account;
1487  }
1488  $i++;
1489  }
1490 
1491  $fields = array('id', 'fk_soc', 'key_account', 'site', 'date_creation', 'tms');
1492 
1493  $returnAccounts = array();
1494 
1495  foreach ($accounts as $account) {
1496  $object = array();
1497  foreach ($account as $key => $value) {
1498  if (in_array($key, $fields)) {
1499  $object[$key] = $value;
1500  }
1501  }
1502  $returnAccounts[] = $object;
1503  }
1504 
1505  return $returnAccounts;
1506  }
1507 
1527  public function createSocieteAccount($id, $request_data = null)
1528  {
1529  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1530  throw new RestException(401);
1531  }
1532 
1533  if (!isset($request_data['site'])) {
1534  throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !');
1535  }
1536 
1537  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."'";
1538  $result = $this->db->query($sql);
1539 
1540  if ($result && $this->db->num_rows($result) == 0) {
1541  $account = new SocieteAccount($this->db);
1542  if (!isset($request_data['login'])) {
1543  $account->login = "";
1544  }
1545  $account->fk_soc = $id;
1546 
1547  foreach ($request_data as $field => $value) {
1548  $account->$field = $value;
1549  }
1550 
1551  if ($account->create(DolibarrApiAccess::$user) < 0) {
1552  throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!');
1553  }
1554 
1555  $this->_cleanObjectDatas($account);
1556 
1557  return $account;
1558  } else {
1559  throw new RestException(409, 'A SocieteAccount entity already exists for this company and site.');
1560  }
1561  }
1562 
1585  public function putSocieteAccount($id, $site, $request_data = null)
1586  {
1587  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1588  throw new RestException(401);
1589  }
1590 
1591  $sql = "SELECT rowid, fk_user_creat, date_creation FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
1592  $result = $this->db->query($sql);
1593 
1594  // We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one.
1595  if ($result && $this->db->num_rows == 0) {
1596  if (!isset($request_data['key_account'])) {
1597  throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !');
1598  }
1599  $account = new SocieteAccount($this->db);
1600  if (!isset($request_data['login'])) {
1601  $account->login = "";
1602  }
1603 
1604  foreach ($request_data as $field => $value) {
1605  $account->$field = $value;
1606  }
1607 
1608  $account->fk_soc = $id;
1609  $account->site = $site;
1610 
1611  if ($account->create(DolibarrApiAccess::$user) < 0) {
1612  throw new RestException(500, 'Error creating SocieteAccount entity.');
1613  }
1614  // We found an existing SocieteAccount entity, we are replacing it
1615  } else {
1616  if (isset($request_data['site']) && $request_data['site'] !== $site) {
1617  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
1618  $result = $this->db->query($sql);
1619 
1620  if ($result && $this->db->num_rows($result) !== 0) {
1621  throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) from $site to ".$request_data['site']." but another SocieteAccount entity already exists with this site key.");
1622  }
1623  }
1624 
1625  $obj = $this->db->fetch_object($result);
1626 
1627  $account = new SocieteAccount($this->db);
1628  $account->id = $obj->rowid;
1629  $account->fk_soc = $id;
1630  $account->site = $site;
1631  if (!isset($request_data['login'])) {
1632  $account->login = "";
1633  }
1634  $account->fk_user_creat = $obj->fk_user_creat;
1635  $account->date_creation = $obj->date_creation;
1636 
1637  foreach ($request_data as $field => $value) {
1638  $account->$field = $value;
1639  }
1640 
1641  if ($account->update(DolibarrApiAccess::$user) < 0) {
1642  throw new RestException(500, 'Error updating SocieteAccount entity.');
1643  }
1644  }
1645 
1646  $this->_cleanObjectDatas($account);
1647 
1648  return $account;
1649  }
1650 
1667  public function patchSocieteAccount($id, $site, $request_data = null)
1668  {
1669  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1670  throw new RestException(401);
1671  }
1672 
1673  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
1674  $result = $this->db->query($sql);
1675 
1676  if ($result && $this->db->num_rows($result) == 0) {
1677  throw new RestException(404, "This thirdparty does not have $site gateway attached or does not exist.");
1678  } else {
1679  // If the user tries to edit the site member, we check first if
1680  if (isset($request_data['site']) && $request_data['site'] !== $site) {
1681  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
1682  $result = $this->db->query($sql);
1683 
1684  if ($result && $this->db->num_rows($result) !== 0) {
1685  throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) site member from ".$site." to ".$request_data['site']." but another SocieteAccount entity already exists for this thirdparty with this site key.");
1686  }
1687  }
1688 
1689  $obj = $this->db->fetch_object($result);
1690  $account = new SocieteAccount($this->db);
1691  $account->fetch($obj->rowid);
1692 
1693  foreach ($request_data as $field => $value) {
1694  $account->$field = $value;
1695  }
1696 
1697  if ($account->update(DolibarrApiAccess::$user) < 0) {
1698  throw new RestException(500, 'Error updating SocieteAccount account');
1699  }
1700 
1701  $this->_cleanObjectDatas($account);
1702 
1703  return $account;
1704  }
1705  }
1706 
1720  public function deleteSocieteAccount($id, $site)
1721  {
1722  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1723  throw new RestException(401);
1724  }
1725 
1726  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
1727  $result = $this->db->query($sql);
1728 
1729  if ($result && $this->db->num_rows($result) == 0) {
1730  throw new RestException(404);
1731  } else {
1732  $obj = $this->db->fetch_object($result);
1733  $account = new SocieteAccount($this->db);
1734  $account->fetch($obj->rowid);
1735 
1736  if ($account->delete(DolibarrApiAccess::$user) < 0) {
1737  throw new RestException(500, "Error while deleting $site gateway attached to this third party");
1738  }
1739  }
1740  }
1741 
1754  public function deleteSocieteAccounts($id)
1755  {
1756  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1757  throw new RestException(401);
1758  }
1759 
1764  $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms";
1765  $sql .= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id);
1766 
1767  $result = $this->db->query($sql);
1768 
1769  if ($result && $this->db->num_rows($result) == 0) {
1770  throw new RestException(404, 'This third party does not have any gateway attached or does not exist.');
1771  } else {
1772  $i = 0;
1773 
1774  $num = $this->db->num_rows($result);
1775  while ($i < $num) {
1776  $obj = $this->db->fetch_object($result);
1777  $account = new SocieteAccount($this->db);
1778  $account->fetch($obj->rowid);
1779 
1780  if ($account->delete(DolibarrApiAccess::$user) < 0) {
1781  throw new RestException(500, 'Error while deleting gateways attached to this third party');
1782  }
1783  $i++;
1784  }
1785  }
1786  }
1787 
1788  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1795  protected function _cleanObjectDatas($object)
1796  {
1797  // phpcs:enable
1798  $object = parent::_cleanObjectDatas($object);
1799 
1800  unset($object->nom); // ->name already defined and nom deprecated
1801  unset($object->name_bis); // ->name_alias already defined
1802  unset($object->note); // ->note_private and note_public already defined
1803  unset($object->departement);
1804  unset($object->departement_code);
1805  unset($object->pays);
1806  unset($object->particulier);
1807  unset($object->prefix_comm);
1808 
1809  unset($object->siren);
1810  unset($object->siret);
1811  unset($object->ape);
1812 
1813  unset($object->commercial_id); // This property is used in create/update only. It does not exists in read mode because there is several sales representatives.
1814 
1815  unset($object->total_ht);
1816  unset($object->total_tva);
1817  unset($object->total_localtax1);
1818  unset($object->total_localtax2);
1819  unset($object->total_ttc);
1820 
1821  unset($object->lines);
1822  unset($object->thirdparty);
1823 
1824  unset($object->fk_delivery_address); // deprecated feature
1825 
1826  unset($object->skype);
1827  unset($object->twitter);
1828  unset($object->facebook);
1829  unset($object->linkedin);
1830  unset($object->instagram);
1831  unset($object->snapchat);
1832  unset($object->googleplus);
1833  unset($object->youtube);
1834  unset($object->whatsapp);
1835 
1836  return $object;
1837  }
1838 
1847  private function _validate($data)
1848  {
1849  $thirdparty = array();
1850  foreach (Thirdparties::$FIELDS as $field) {
1851  if (!isset($data[$field])) {
1852  throw new RestException(400, "$field field missing");
1853  }
1854  $thirdparty[$field] = $data[$field];
1855  }
1856  return $thirdparty;
1857  }
1858 
1880  private function _fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1881  {
1882  global $conf;
1883 
1884  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1885  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on thirdparties.');
1886  }
1887 
1888  if ($rowid === 0) {
1889  $result = $this->company->initAsSpecimen();
1890  } else {
1891  $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
1892  }
1893  if (!$result) {
1894  throw new RestException(404, 'Thirdparty not found');
1895  }
1896 
1897  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
1898  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.' on this thirdparty');
1899  }
1900  if (isModEnabled('mailing')) {
1901  $this->company->getNoEmail();
1902  }
1903 
1904  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
1905  $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1906  $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1907  } else {
1908  $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
1909  $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
1910  }
1911 
1912  $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount);
1913  $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote);
1914  $this->company->absolute_discount = price2num($absolute_discount, 'MT');
1915  $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
1916 
1917  return $this->_cleanObjectDatas($this->company);
1918  }
1919 }
Class to manage withdrawal receipts.
Class to manage categories.
Class to manage bank accounts description of third parties.
Class for API REST v1.
Definition: api.class.php:31
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
Definition: api.class.php:283
Class to manage invoices.
Class for SocieteAccount.
Class to manage third parties objects (customers, suppliers, prospects...)
setThirdpartyPriceLevel($id, $priceLevel)
Set new price level for the given thirdparty.
_cleanObjectDatas($object)
Clean sensible object datas.
getSupplierCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get supplier categories for a thirdparty.
getSocieteAccounts($id, $site=null)
Get a specific gateway attached to a thirdparty (by specifying the site key)
getOutStandingOrder($id, $mode='customer')
Get outstanding orders of thirdparty.
getByBarcode($barcode)
Get properties of a thirdparty object by barcode.
generateBankAccountDocument($id, $companybankid=null, $model='sepamandate')
Generate a Document from a bank account record (like SEPA mandate)
addCategory($id, $category_id)
Add a customer category to a thirdparty.
getCompanyBankAccount($id)
Get CompanyBankAccount objects for thirdparty.
getInvoicesQualifiedForReplacement($id)
Return list of invoices qualified to be replaced by another invoice.
post($request_data=null)
Create thirdparty object.
put($id, $request_data=null)
Update thirdparty.
getByEmail($email)
Get properties of a thirdparty object by email.
_validate($data)
Validate fields before create or update object.
addSupplierCategory($id, $category_id)
Add a supplier category to a thirdparty.
merge($id, $idtodelete)
Merge a thirdparty into another one.
deleteSocieteAccounts($id)
Delete all gateways attached to a thirdparty.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $mode=0, $category=0, $sqlfilters='')
List thirdparties.
__construct()
Constructor.
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get customer categories for a thirdparty.
deleteSupplierCategory($id, $category_id)
Remove the link between a category and the thirdparty.
putSocieteAccount($id, $site, $request_data=null)
Create and attach a new (or replace an existing) specific site gateway to a thirdparty.
updateCompanyBankAccount($id, $bankaccount_id, $request_data=null)
Update CompanyBankAccount object for thirdparty.
deleteSocieteAccount($id, $site)
Delete a specific site gateway attached to a thirdparty (by gateway id)
getInvoicesQualifiedForCreditNote($id)
Return list of invoices qualified to be corrected by a credit note.
patchSocieteAccount($id, $site, $request_data=null)
Update specified values of a specific gateway attached to a thirdparty.
getFixedAmountDiscounts($id, $filter="none", $sortfield="f.type", $sortorder='ASC')
Get fixed amount discount of a thirdparty (all sources: deposit, credit note, commercial offers....
getOutStandingProposals($id, $mode='customer')
Get outstanding proposals of thirdparty.
_fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='')
Fetch properties of a thirdparty object.
getSalesRepresentatives($id, $mode=0)
Get representatives of thirdparty.
getOutStandingInvoices($id, $mode='customer')
Get outstanding invoices of thirdparty.
deleteCompanyBankAccount($id, $bankaccount_id)
Delete a bank account attached to a thirdparty.
createSocieteAccount($id, $request_data=null)
Create and attach a new gateway to an existing thirdparty.
createCompanyBankAccount($id, $request_data=null)
Create CompanyBankAccount object for thirdparty.
deleteCategory($id, $category_id)
Remove the link between a customer category and the thirdparty.
Class to manage translations.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$error='')
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
$conf db
API class for accounts.
Definition: inc.php:41