dolibarr  18.0.0-beta
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  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields AS ef ON ef.fk_object = t.rowid"; // So we will be able to filter on extrafields
154  if ($category > 0) {
155  if ($mode != 4) {
156  $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c";
157  }
158  if (!in_array($mode, array(1, 2, 3))) {
159  $sql .= ", ".MAIN_DB_PREFIX."categorie_fournisseur as cc";
160  }
161  }
162  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
163  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
164  }
165  $sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st";
166  $sql .= " WHERE t.entity IN (".getEntity('societe').")";
167  $sql .= " AND t.fk_stcomm = st.id";
168 
169  if ($mode == 1) {
170  $sql .= " AND t.client IN (1, 3)";
171  } elseif ($mode == 2) {
172  $sql .= " AND t.client IN (2, 3)";
173  } elseif ($mode == 3) {
174  $sql .= " AND t.client IN (0)";
175  } elseif ($mode == 4) {
176  $sql .= " AND t.fournisseur IN (1)";
177  }
178 
179  // Select thirdparties of given category
180  if ($category > 0) {
181  if (!empty($mode) && $mode != 4) {
182  $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid";
183  } elseif (!empty($mode) && $mode == 4) {
184  $sql .= " AND cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid";
185  } else {
186  $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))";
187  }
188  }
189 
190  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
191  $sql .= " AND t.rowid = sc.fk_soc";
192  }
193  //if ($email != NULL) $sql.= " AND s.email = \"".$email."\"";
194  if ($socids) {
195  $sql .= " AND t.rowid IN (".$this->db->sanitize($socids).")";
196  }
197  if ($search_sale > 0) {
198  $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
199  }
200  // Insert sale filter
201  if ($search_sale > 0) {
202  $sql .= " AND sc.fk_user = ".((int) $search_sale);
203  }
204  // Add sql filters
205  if ($sqlfilters) {
206  $errormessage = '';
207  $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
208  if ($errormessage) {
209  throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
210  }
211  }
212 
213  $sql .= $this->db->order($sortfield, $sortorder);
214 
215  if ($limit) {
216  if ($page < 0) {
217  $page = 0;
218  }
219  $offset = $limit * $page;
220 
221  $sql .= $this->db->plimit($limit + 1, $offset);
222  }
223 
224  $result = $this->db->query($sql);
225  if ($result) {
226  $num = $this->db->num_rows($result);
227  $min = min($num, ($limit <= 0 ? $num : $limit));
228  $i = 0;
229  while ($i < $min) {
230  $obj = $this->db->fetch_object($result);
231  $soc_static = new Societe($this->db);
232  if ($soc_static->fetch($obj->rowid)) {
233  if (isModEnabled('mailing')) {
234  $soc_static->getNoEmail();
235  }
236  $obj_ret[] = $this->_cleanObjectDatas($soc_static);
237  }
238  $i++;
239  }
240  } else {
241  throw new RestException(503, 'Error when retrieve thirdparties : '.$this->db->lasterror());
242  }
243  if (!count($obj_ret)) {
244  throw new RestException(404, 'Thirdparties not found');
245  }
246  return $obj_ret;
247  }
248 
255  public function post($request_data = null)
256  {
257  if (!DolibarrApiAccess::$user->rights->societe->creer) {
258  throw new RestException(401);
259  }
260  // Check mandatory fields
261  $result = $this->_validate($request_data);
262 
263  foreach ($request_data as $field => $value) {
264  $this->company->$field = $value;
265  }
266  if ($this->company->create(DolibarrApiAccess::$user) < 0) {
267  throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors));
268  }
269  if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
270  $this->company->setNoEmail($this->company->no_email);
271  }
272 
273  return $this->company->id;
274  }
275 
283  public function put($id, $request_data = null)
284  {
285  if (!DolibarrApiAccess::$user->rights->societe->creer) {
286  throw new RestException(401);
287  }
288 
289  $result = $this->company->fetch($id);
290  if (!$result) {
291  throw new RestException(404, 'Thirdparty not found');
292  }
293 
294  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
295  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
296  }
297 
298  foreach ($request_data as $field => $value) {
299  if ($field == 'id') {
300  continue;
301  }
302  $this->company->$field = $value;
303  }
304 
305  if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
306  $this->company->setNoEmail($this->company->no_email);
307  }
308 
309  if ($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update', 1)) {
310  return $this->get($id);
311  }
312 
313  return false;
314  }
315 
330  public function merge($id, $idtodelete)
331  {
332  global $hookmanager;
333 
334  $error = 0;
335 
336  if ($id == $idtodelete) {
337  throw new RestException(400, 'Try to merge a thirdparty into itself');
338  }
339 
340  if (!DolibarrApiAccess::$user->rights->societe->creer) {
341  throw new RestException(401);
342  }
343 
344  $result = $this->company->fetch($id); // include the fetch of extra fields
345  if (!$result) {
346  throw new RestException(404, 'Thirdparty not found');
347  }
348 
349  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
350  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
351  }
352 
353  $this->companytoremove = new Societe($this->db);
354 
355  $result = $this->companytoremove->fetch($idtodelete); // include the fetch of extra fields
356  if (!$result) {
357  throw new RestException(404, 'Thirdparty not found');
358  }
359 
360  if (!DolibarrApi::_checkAccessToResource('societe', $this->companytoremove->id)) {
361  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
362  }
363 
364  $soc_origin = $this->companytoremove;
365  $object = $this->company;
366  $user = DolibarrApiAccess::$user;
367 
368 
369  // Call same code than into action 'confirm_merge'
370 
371 
372  $this->db->begin();
373 
374  // Recopy some data
375  $object->client = $object->client | $soc_origin->client;
376  $object->fournisseur = $object->fournisseur | $soc_origin->fournisseur;
377  $listofproperties = array(
378  'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode',
379  'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
380  'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
381  'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency',
382  'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
383  'model_pdf', 'fk_projet'
384  );
385  foreach ($listofproperties as $property) {
386  if (empty($object->$property)) {
387  $object->$property = $soc_origin->$property;
388  }
389  }
390 
391  // Concat some data
392  $listofproperties = array(
393  'note_public', 'note_private'
394  );
395  foreach ($listofproperties as $property) {
396  $object->$property = dol_concatdesc($object->$property, $soc_origin->$property);
397  }
398 
399  // Merge extrafields
400  if (is_array($soc_origin->array_options)) {
401  foreach ($soc_origin->array_options as $key => $val) {
402  if (empty($object->array_options[$key])) {
403  $object->array_options[$key] = $val;
404  }
405  }
406  }
407 
408  // Merge categories
409  $static_cat = new Categorie($this->db);
410  $custcats = $static_cat->containing($soc_origin->id, 'customer', 'id');
411  $object->setCategories($custcats, 'customer');
412  $suppcats = $static_cat->containing($soc_origin->id, 'supplier', 'id');
413  $object->setCategories($suppcats, 'supplier');
414 
415  // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
416  if ($soc_origin->code_client == $object->code_client
417  || $soc_origin->code_fournisseur == $object->code_fournisseur
418  || $soc_origin->barcode == $object->barcode) {
419  dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
420  $soc_origin->code_client = '';
421  $soc_origin->code_fournisseur = '';
422  $soc_origin->barcode = '';
423  $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
424  }
425 
426  // Update
427  $result = $object->update($object->id, $user, 0, 1, 1, 'merge');
428  if ($result < 0) {
429  $error++;
430  }
431 
432  // Move links
433  if (!$error) {
434  // This list is also into the societe/card.php file
435  // TODO Mutualise the list into object societe.class.php
436  $objects = array(
437  'Adherent' => '/adherents/class/adherent.class.php',
438  'Don' => '/don/class/don.class.php',
439  'Societe' => '/societe/class/societe.class.php',
440  //'Categorie' => '/categories/class/categorie.class.php',
441  'ActionComm' => '/comm/action/class/actioncomm.class.php',
442  'Propal' => '/comm/propal/class/propal.class.php',
443  'Commande' => '/commande/class/commande.class.php',
444  'Facture' => '/compta/facture/class/facture.class.php',
445  'FactureRec' => '/compta/facture/class/facture-rec.class.php',
446  'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
447  'Mo' => '/mrp/class/mo.class.php',
448  'Contact' => '/contact/class/contact.class.php',
449  'Contrat' => '/contrat/class/contrat.class.php',
450  'Expedition' => '/expedition/class/expedition.class.php',
451  'Fichinter' => '/fichinter/class/fichinter.class.php',
452  'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
453  'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
454  'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
455  'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
456  'Delivery' => '/delivery/class/delivery.class.php',
457  'Product' => '/product/class/product.class.php',
458  'Project' => '/projet/class/project.class.php',
459  'Ticket' => '/ticket/class/ticket.class.php',
460  'User' => '/user/class/user.class.php',
461  'Account' => '/compta/bank/class/account.class.php',
462  'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php'
463  );
464 
465  //First, all core objects must update their tables
466  foreach ($objects as $object_name => $object_file) {
467  require_once DOL_DOCUMENT_ROOT.$object_file;
468 
469  if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $object->id)) {
470  $error++;
471  //setEventMessages($this->db->lasterror(), null, 'errors');
472  }
473  }
474  }
475 
476  // External modules should update their ones too
477  if (!$error) {
478  $reshook = $hookmanager->executeHooks('replaceThirdparty', array(
479  'soc_origin' => $soc_origin->id,
480  'soc_dest' => $object->id
481  ), $soc_dest, $action);
482 
483  if ($reshook < 0) {
484  //setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
485  $error++;
486  }
487  }
488 
489 
490  if (!$error) {
491  $object->context = array('merge'=>1, 'mergefromid'=>$soc_origin->id);
492 
493  // Call trigger
494  $result = $object->call_trigger('COMPANY_MODIFY', $user);
495  if ($result < 0) {
496  //setEventMessages($object->error, $object->errors, 'errors');
497  $error++;
498  }
499  // End call triggers
500  }
501 
502  if (!$error) {
503  //We finally remove the old thirdparty
504  if ($soc_origin->delete($soc_origin->id, $user) < 1) {
505  $error++;
506  }
507  }
508 
509  // End of merge
510 
511  if ($error) {
512  $this->db->rollback();
513 
514  throw new RestException(500, 'Error failed to merged thirdparty '.$this->companytoremove->id.' into '.$id.'. Enable and read log file for more information.');
515  } else {
516  $this->db->commit();
517  }
518 
519  return $this->get($id);
520  }
521 
528  public function delete($id)
529  {
530  if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
531  throw new RestException(401);
532  }
533  $result = $this->company->fetch($id);
534  if (!$result) {
535  throw new RestException(404, 'Thirdparty not found');
536  }
537  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
538  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
539  }
540  $this->company->oldcopy = clone $this->company;
541 
542  $res = $this->company->delete($id);
543  if ($res < 0) {
544  throw new RestException(500, "Can't delete, error occurs");
545  } elseif ($res == 0) {
546  throw new RestException(409, "Can't delete, that product is probably used");
547  }
548 
549  return array(
550  'success' => array(
551  'code' => 200,
552  'message' => 'Object deleted'
553  )
554  );
555  }
556 
572  public function setThirdpartyPriceLevel($id, $priceLevel)
573  {
574  global $conf;
575 
576  if (!isModEnabled('societe')) {
577  throw new RestException(501, 'Module "Thirdparties" needed for this request');
578  }
579 
580  if (!isModEnabled("product")) {
581  throw new RestException(501, 'Module "Products" needed for this request');
582  }
583 
584  if (empty($conf->global->PRODUIT_MULTIPRICES)) {
585  throw new RestException(501, 'Multiprices features activation needed for this request');
586  }
587 
588  if ($priceLevel < 1 || $priceLevel > $conf->global->PRODUIT_MULTIPRICES_LIMIT) {
589  throw new RestException(400, 'Price level must be between 1 and '.$conf->global->PRODUIT_MULTIPRICES_LIMIT);
590  }
591 
592  if (empty(DolibarrApiAccess::$user->rights->societe->creer)) {
593  throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
594  }
595 
596  $result = $this->company->fetch($id);
597  if ($result < 0) {
598  throw new RestException(404, 'Thirdparty '.$id.' not found');
599  }
600 
601  if (empty($result)) {
602  throw new RestException(500, 'Error fetching thirdparty '.$id, array_merge(array($this->company->error), $this->company->errors));
603  }
604 
605  if (empty(DolibarrApi::_checkAccessToResource('societe', $this->company->id))) {
606  throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
607  }
608 
609  $result = $this->company->setPriceLevel($priceLevel, DolibarrApiAccess::$user);
610  if ($result <= 0) {
611  throw new RestException(500, 'Error setting new price level for thirdparty '.$id, array($this->company->db->lasterror()));
612  }
613 
614  return $this->_cleanObjectDatas($this->company);
615  }
616 
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  $arrayofcateg = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page);
643 
644  if (is_numeric($arrayofcateg) && $arrayofcateg < 0) {
645  throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
646  }
647 
648  if (is_numeric($arrayofcateg) && $arrayofcateg >= 0) { // To fix a return of 0 instead of empty array of method getListForItem
649  return array();
650  }
651 
652  return $arrayofcateg;
653  }
654 
664  public function addCategory($id, $category_id)
665  {
666  if (!DolibarrApiAccess::$user->rights->societe->creer) {
667  throw new RestException(401);
668  }
669 
670  $result = $this->company->fetch($id);
671  if (!$result) {
672  throw new RestException(404, 'Thirdparty not found');
673  }
674  $category = new Categorie($this->db);
675  $result = $category->fetch($category_id);
676  if (!$result) {
677  throw new RestException(404, 'category not found');
678  }
679 
680  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
681  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
682  }
683  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
684  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
685  }
686 
687  $category->add_type($this->company, 'customer');
688 
689  return $this->_cleanObjectDatas($this->company);
690  }
691 
702  public function deleteCategory($id, $category_id)
703  {
704  if (!DolibarrApiAccess::$user->rights->societe->creer) {
705  throw new RestException(401);
706  }
707 
708  $result = $this->company->fetch($id);
709  if (!$result) {
710  throw new RestException(404, 'Thirdparty not found');
711  }
712  $category = new Categorie($this->db);
713  $result = $category->fetch($category_id);
714  if (!$result) {
715  throw new RestException(404, 'category not found');
716  }
717 
718  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
719  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
720  }
721  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
722  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
723  }
724 
725  $category->del_type($this->company, 'customer');
726 
727  return $this->_cleanObjectDatas($this->company);
728  }
729 
743  public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
744  {
745  if (!DolibarrApiAccess::$user->rights->categorie->lire) {
746  throw new RestException(401);
747  }
748 
749  $result = $this->company->fetch($id);
750  if (!$result) {
751  throw new RestException(404, 'Thirdparty not found');
752  }
753 
754  $categories = new Categorie($this->db);
755 
756  $result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page);
757 
758  if (is_numeric($result) && $result < 0) {
759  throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
760  }
761 
762  if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
763  return array();
764  }
765 
766  return $result;
767  }
768 
779  public function addSupplierCategory($id, $category_id)
780  {
781  if (!DolibarrApiAccess::$user->rights->societe->creer) {
782  throw new RestException(401);
783  }
784 
785  $result = $this->company->fetch($id);
786  if (!$result) {
787  throw new RestException(404, 'Thirdparty not found');
788  }
789  $category = new Categorie($this->db);
790  $result = $category->fetch($category_id);
791  if (!$result) {
792  throw new RestException(404, 'category not found');
793  }
794 
795  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
796  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
797  }
798  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
799  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
800  }
801 
802  $category->add_type($this->company, 'supplier');
803 
804  return $this->_cleanObjectDatas($this->company);
805  }
806 
817  public function deleteSupplierCategory($id, $category_id)
818  {
819  if (!DolibarrApiAccess::$user->rights->societe->creer) {
820  throw new RestException(401);
821  }
822 
823  $result = $this->company->fetch($id);
824  if (!$result) {
825  throw new RestException(404, 'Thirdparty not found');
826  }
827  $category = new Categorie($this->db);
828  $result = $category->fetch($category_id);
829  if (!$result) {
830  throw new RestException(404, 'category not found');
831  }
832 
833  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
834  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
835  }
836  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
837  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
838  }
839 
840  $category->del_type($this->company, 'supplier');
841 
842  return $this->_cleanObjectDatas($this->company);
843  }
844 
845 
860  public function getOutStandingProposals($id, $mode = 'customer')
861  {
862  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
863  throw new RestException(401);
864  }
865 
866  if (empty($id)) {
867  throw new RestException(400, 'Thirdparty ID is mandatory');
868  }
869 
870  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
871  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
872  }
873 
874  $result = $this->company->fetch($id);
875  if (!$result) {
876  throw new RestException(404, 'Thirdparty not found');
877  }
878 
879  $result = $this->company->getOutstandingProposals($mode);
880 
881  unset($result['total_ht']);
882  unset($result['total_ttc']);
883 
884  return $result;
885  }
886 
887 
902  public function getOutStandingOrder($id, $mode = 'customer')
903  {
904  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
905  throw new RestException(401);
906  }
907 
908  if (empty($id)) {
909  throw new RestException(400, 'Thirdparty ID is mandatory');
910  }
911 
912  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
913  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
914  }
915 
916  $result = $this->company->fetch($id);
917  if (!$result) {
918  throw new RestException(404, 'Thirdparty not found');
919  }
920 
921  $result = $this->company->getOutstandingOrders($mode);
922 
923  unset($result['total_ht']);
924  unset($result['total_ttc']);
925 
926  return $result;
927  }
928 
943  public function getOutStandingInvoices($id, $mode = 'customer')
944  {
945  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
946  throw new RestException(401);
947  }
948 
949  if (empty($id)) {
950  throw new RestException(400, 'Thirdparty ID is mandatory');
951  }
952 
953  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
954  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
955  }
956 
957  $result = $this->company->fetch($id);
958  if (!$result) {
959  throw new RestException(404, 'Thirdparty not found');
960  }
961 
962  $result = $this->company->getOutstandingBills($mode);
963 
964  unset($result['total_ht']);
965  unset($result['total_ttc']);
966 
967  return $result;
968  }
969 
984  public function getSalesRepresentatives($id, $mode = 0)
985  {
986  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
987  throw new RestException(401);
988  }
989 
990  if (empty($id)) {
991  throw new RestException(400, 'Thirdparty ID is mandatory');
992  }
993 
994  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
995  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
996  }
997 
998  $result = $this->company->fetch($id);
999  if (!$result) {
1000  throw new RestException(404, 'Thirdparty not found');
1001  }
1002 
1003  $result = $this->company->getSalesRepresentatives(DolibarrApiAccess::$user, $mode);
1004 
1005  return $result;
1006  }
1007 
1025  public function getFixedAmountDiscounts($id, $filter = "none", $sortfield = "f.type", $sortorder = 'ASC')
1026  {
1027  $obj_ret = array();
1028 
1029  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1030  throw new RestException(401);
1031  }
1032 
1033  if (empty($id)) {
1034  throw new RestException(400, 'Thirdparty ID is mandatory');
1035  }
1036 
1037  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1038  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1039  }
1040 
1041  $result = $this->company->fetch($id);
1042  if (!$result) {
1043  throw new RestException(404, 'Thirdparty not found');
1044  }
1045 
1046 
1047  $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";
1048  $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re, ".MAIN_DB_PREFIX."facture as f";
1049  $sql .= " WHERE f.rowid = re.fk_facture_source AND re.fk_soc = ".((int) $id);
1050  if ($filter == "available") {
1051  $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL";
1052  }
1053  if ($filter == "used") {
1054  $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)";
1055  }
1056 
1057  $sql .= $this->db->order($sortfield, $sortorder);
1058 
1059  $result = $this->db->query($sql);
1060  if (!$result) {
1061  throw new RestException(503, $this->db->lasterror());
1062  } else {
1063  $num = $this->db->num_rows($result);
1064  while ($obj = $this->db->fetch_object($result)) {
1065  $obj_ret[] = $obj;
1066  }
1067  }
1068 
1069  return $obj_ret;
1070  }
1071 
1072 
1073 
1088  {
1089  if (!DolibarrApiAccess::$user->rights->facture->lire) {
1090  throw new RestException(401);
1091  }
1092  if (empty($id)) {
1093  throw new RestException(400, 'Thirdparty ID is mandatory');
1094  }
1095 
1096  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1097  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1098  }
1099 
1100  /*$result = $this->thirdparty->fetch($id);
1101  if( ! $result ) {
1102  throw new RestException(404, 'Thirdparty not found');
1103  }*/
1104 
1105  $invoice = new Facture($this->db);
1106  $result = $invoice->list_replacable_invoices($id);
1107  if ($result < 0) {
1108  throw new RestException(405, $invoice->error);
1109  }
1110 
1111  return $result;
1112  }
1113 
1131  {
1132  if (!DolibarrApiAccess::$user->rights->facture->lire) {
1133  throw new RestException(401);
1134  }
1135  if (empty($id)) {
1136  throw new RestException(400, 'Thirdparty ID is mandatory');
1137  }
1138 
1139  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1140  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1141  }
1142 
1143  /*$result = $this->thirdparty->fetch($id);
1144  if( ! $result ) {
1145  throw new RestException(404, 'Thirdparty not found');
1146  }*/
1147 
1148  $invoice = new Facture($this->db);
1149  $result = $invoice->list_qualified_avoir_invoices($id);
1150  if ($result < 0) {
1151  throw new RestException(405, $invoice->error);
1152  }
1153 
1154  return $result;
1155  }
1156 
1166  public function getCompanyBankAccount($id)
1167  {
1168  if (!DolibarrApiAccess::$user->rights->societe->lire) {
1169  throw new RestException(401);
1170  }
1171  if (empty($id)) {
1172  throw new RestException(400, 'Thirdparty ID is mandatory');
1173  }
1174 
1175  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1176  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1177  }
1178 
1183  $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,";
1184  $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur";
1185  $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1186  if ($id) {
1187  $sql .= " WHERE fk_soc = ".((int) $id);
1188  }
1189 
1190  $result = $this->db->query($sql);
1191 
1192  if ($this->db->num_rows($result) == 0) {
1193  throw new RestException(404, 'Account not found');
1194  }
1195 
1196  $i = 0;
1197 
1198  $accounts = array();
1199 
1200  if ($result) {
1201  $num = $this->db->num_rows($result);
1202  while ($i < $num) {
1203  $obj = $this->db->fetch_object($result);
1204  $account = new CompanyBankAccount($this->db);
1205  if ($account->fetch($obj->rowid)) {
1206  $accounts[] = $account;
1207  }
1208  $i++;
1209  }
1210  } else {
1211  throw new RestException(404, 'Account not found');
1212  }
1213 
1214 
1215  $fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum');
1216 
1217  $returnAccounts = array();
1218 
1219  foreach ($accounts as $account) {
1220  $object = array();
1221  foreach ($account as $key => $value) {
1222  if (in_array($key, $fields)) {
1223  $object[$key] = $value;
1224  }
1225  }
1226  $returnAccounts[] = $object;
1227  }
1228 
1229  return $returnAccounts;
1230  }
1231 
1241  public function createCompanyBankAccount($id, $request_data = null)
1242  {
1243  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1244  throw new RestException(401);
1245  }
1246  if ($this->company->fetch($id) <= 0) {
1247  throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1248  }
1249  $account = new CompanyBankAccount($this->db);
1250 
1251  $account->socid = $id;
1252 
1253  foreach ($request_data as $field => $value) {
1254  $account->$field = $value;
1255  }
1256 
1257  if ($account->create(DolibarrApiAccess::$user) < 0) {
1258  throw new RestException(500, 'Error creating Company Bank account');
1259  }
1260 
1261  if (empty($account->rum)) {
1262  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1263  $prelevement = new BonPrelevement($this->db);
1264  $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1265  $account->date_rum = dol_now();
1266  }
1267 
1268  if ($account->update(DolibarrApiAccess::$user) < 0) {
1269  throw new RestException(500, 'Error updating values');
1270  }
1271 
1272  return $this->_cleanObjectDatas($account);
1273  }
1274 
1286  public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
1287  {
1288  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1289  throw new RestException(401);
1290  }
1291  if ($this->company->fetch($id) <= 0) {
1292  throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1293  }
1294  $account = new CompanyBankAccount($this->db);
1295 
1296  $account->fetch($bankaccount_id, $id, -1, '');
1297 
1298  if ($account->socid != $id) {
1299  throw new RestException(401);
1300  }
1301 
1302 
1303  foreach ($request_data as $field => $value) {
1304  $account->$field = $value;
1305  }
1306 
1307  if (empty($account->rum)) {
1308  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1309  $prelevement = new BonPrelevement($this->db);
1310  $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1311  $account->date_rum = dol_now();
1312  }
1313 
1314  if ($account->update(DolibarrApiAccess::$user) < 0) {
1315  throw new RestException(500, 'Error updating values');
1316  }
1317 
1318  return $this->_cleanObjectDatas($account);
1319  }
1320 
1331  public function deleteCompanyBankAccount($id, $bankaccount_id)
1332  {
1333  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1334  throw new RestException(401);
1335  }
1336 
1337  $account = new CompanyBankAccount($this->db);
1338 
1339  $account->fetch($bankaccount_id);
1340 
1341  if (!$account->socid == $id) {
1342  throw new RestException(401);
1343  }
1344 
1345  return $account->delete(DolibarrApiAccess::$user);
1346  }
1347 
1358  public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
1359  {
1360  global $conf, $langs;
1361 
1362  $langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals"));
1363 
1364  if ($this->company->fetch($id) <= 0) {
1365  throw new RestException(404, 'Thirdparty not found');
1366  }
1367 
1368  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1369  throw new RestException(401);
1370  }
1371 
1372  $this->company->setDocModel(DolibarrApiAccess::$user, $model);
1373 
1374  $this->company->fk_bank = $this->company->fk_account;
1375  $this->company->fk_account = $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  return $object;
1827  }
1828 
1837  private function _validate($data)
1838  {
1839  $thirdparty = array();
1840  foreach (Thirdparties::$FIELDS as $field) {
1841  if (!isset($data[$field])) {
1842  throw new RestException(400, "$field field missing");
1843  }
1844  $thirdparty[$field] = $data[$field];
1845  }
1846  return $thirdparty;
1847  }
1848 
1870  private function _fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1871  {
1872  global $conf;
1873 
1874  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1875  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on thirdparties.');
1876  }
1877 
1878  if ($rowid === 0) {
1879  $result = $this->company->initAsSpecimen();
1880  } else {
1881  $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
1882  }
1883  if (!$result) {
1884  throw new RestException(404, 'Thirdparty not found');
1885  }
1886 
1887  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
1888  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.' on this thirdparty');
1889  }
1890  if (isModEnabled('mailing')) {
1891  $this->company->getNoEmail();
1892  }
1893 
1894  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
1895  $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1896  $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1897  } else {
1898  $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
1899  $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
1900  }
1901 
1902  $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount);
1903  $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote);
1904  $this->company->absolute_discount = price2num($absolute_discount, 'MT');
1905  $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
1906 
1907  return $this->_cleanObjectDatas($this->company);
1908  }
1909 }
Thirdparties\getCompanyBankAccount
getCompanyBankAccount($id)
Get CompanyBankAccount objects for thirdparty.
Definition: api_thirdparties.class.php:1166
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:51
Thirdparties\deleteSocieteAccounts
deleteSocieteAccounts($id)
Delete all gateways attached to a thirdparty.
Definition: api_thirdparties.class.php:1754
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1322
forgeSQLFromUniversalSearchCriteria
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
Definition: functions.lib.php:11899
SocieteAccount
Class for SocieteAccount.
Definition: societeaccount.class.php:35
Thirdparties\createSocieteAccount
createSocieteAccount($id, $request_data=null)
Create and attach a new gateway to an existing thirdparty.
Definition: api_thirdparties.class.php:1527
Translate
Class to manage translations.
Definition: translate.class.php:30
Thirdparties\addSupplierCategory
addSupplierCategory($id, $category_id)
Add a supplier category to a thirdparty.
Definition: api_thirdparties.class.php:779
Thirdparties\put
put($id, $request_data=null)
Update thirdparty.
Definition: api_thirdparties.class.php:283
Thirdparties\deleteCategory
deleteCategory($id, $category_id)
Remove the link between a customer category and the thirdparty.
Definition: api_thirdparties.class.php:702
Thirdparties\_fetch
_fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='')
Fetch properties of a thirdparty object.
Definition: api_thirdparties.class.php:1870
Thirdparties\getByEmail
getByEmail($email)
Get properties of a thirdparty object by email.
Definition: api_thirdparties.class.php:92
DolibarrApi\_checkAccessToResource
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:282
Categorie
Class to manage categories.
Definition: categorie.class.php:47
Facture
Class to manage invoices.
Definition: facture.class.php:60
Thirdparties\getOutStandingProposals
getOutStandingProposals($id, $mode='customer')
Get outstanding proposals of thirdparty.
Definition: api_thirdparties.class.php:860
CompanyBankAccount
Class to manage bank accounts description of third parties.
Definition: companybankaccount.class.php:34
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5943
DolibarrApi
Class for API REST v1.
Definition: api.class.php:30
dol_concatdesc
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...
Definition: functions.lib.php:7705
Thirdparties\__construct
__construct()
Constructor.
Definition: api_thirdparties.class.php:48
Thirdparties\getCategories
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get customer categories for a thirdparty.
Definition: api_thirdparties.class.php:629
BonPrelevement
Class to manage withdrawal receipts.
Definition: bonprelevement.class.php:43
Thirdparties\getFixedAmountDiscounts
getFixedAmountDiscounts($id, $filter="none", $sortfield="f.type", $sortorder='ASC')
Get fixed amount discount of a thirdparty (all sources: deposit, credit note, commercial offers....
Definition: api_thirdparties.class.php:1025
$sql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
Thirdparties\index
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $mode=0, $category=0, $sqlfilters='')
List thirdparties.
Definition: api_thirdparties.class.php:131
Thirdparties\getOutStandingInvoices
getOutStandingInvoices($id, $mode='customer')
Get outstanding invoices of thirdparty.
Definition: api_thirdparties.class.php:943
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1732
Thirdparties\deleteSocieteAccount
deleteSocieteAccount($id, $site)
Delete a specific site gateway attached to a thirdparty (by gateway id)
Definition: api_thirdparties.class.php:1720
Thirdparties\setThirdpartyPriceLevel
setThirdpartyPriceLevel($id, $priceLevel)
Set new price level for the given thirdparty.
Definition: api_thirdparties.class.php:572
Thirdparties\getSupplierCategories
getSupplierCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get supplier categories for a thirdparty.
Definition: api_thirdparties.class.php:743
Thirdparties\getOutStandingOrder
getOutStandingOrder($id, $mode='customer')
Get outstanding orders of thirdparty.
Definition: api_thirdparties.class.php:902
Thirdparties\getByBarcode
getByBarcode($barcode)
Get properties of a thirdparty object by barcode.
Definition: api_thirdparties.class.php:109
Thirdparties\getInvoicesQualifiedForCreditNote
getInvoicesQualifiedForCreditNote($id)
Return list of invoices qualified to be corrected by a credit note.
Definition: api_thirdparties.class.php:1130
Thirdparties\merge
merge($id, $idtodelete)
Merge a thirdparty into another one.
Definition: api_thirdparties.class.php:330
Thirdparties\generateBankAccountDocument
generateBankAccountDocument($id, $companybankid=null, $model='sepamandate')
Generate a Document from a bank account record (like SEPA mandate)
Definition: api_thirdparties.class.php:1358
Thirdparties\updateCompanyBankAccount
updateCompanyBankAccount($id, $bankaccount_id, $request_data=null)
Update CompanyBankAccount object for thirdparty.
Definition: api_thirdparties.class.php:1286
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:207
Thirdparties\_cleanObjectDatas
_cleanObjectDatas($object)
Clean sensible object datas.
Definition: api_thirdparties.class.php:1795
Thirdparties\getInvoicesQualifiedForReplacement
getInvoicesQualifiedForReplacement($id)
Return list of invoices qualified to be replaced by another invoice.
Definition: api_thirdparties.class.php:1087
Thirdparties\deleteSupplierCategory
deleteSupplierCategory($id, $category_id)
Remove the link between a category and the thirdparty.
Definition: api_thirdparties.class.php:817
Thirdparties\putSocieteAccount
putSocieteAccount($id, $site, $request_data=null)
Create and attach a new (or replace an existing) specific site gateway to a thirdparty.
Definition: api_thirdparties.class.php:1585
Thirdparties
Definition: api_thirdparties.class.php:30
Thirdparties\getSalesRepresentatives
getSalesRepresentatives($id, $mode=0)
Get representatives of thirdparty.
Definition: api_thirdparties.class.php:984
Thirdparties\addCategory
addCategory($id, $category_id)
Add a customer category to a thirdparty.
Definition: api_thirdparties.class.php:664
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:3046
Thirdparties\post
post($request_data=null)
Create thirdparty object.
Definition: api_thirdparties.class.php:255
Thirdparties\_validate
_validate($data)
Validate fields before create or update object.
Definition: api_thirdparties.class.php:1837
Thirdparties\getSocieteAccounts
getSocieteAccounts($id, $site=null)
Get a specific gateway attached to a thirdparty (by specifying the site key)
Definition: api_thirdparties.class.php:1451
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:156
Thirdparties\patchSocieteAccount
patchSocieteAccount($id, $site, $request_data=null)
Update specified values of a specific gateway attached to a thirdparty.
Definition: api_thirdparties.class.php:1667
Thirdparties\deleteCompanyBankAccount
deleteCompanyBankAccount($id, $bankaccount_id)
Delete a bank account attached to a thirdparty.
Definition: api_thirdparties.class.php:1331
Thirdparties\createCompanyBankAccount
createCompanyBankAccount($id, $request_data=null)
Create CompanyBankAccount object for thirdparty.
Definition: api_thirdparties.class.php:1241