dolibarr  x.y.z
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  if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
208  throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
209  }
210  $regexstring = '\‍(([^:\'\‍(\‍)]+:[^:\'\‍(\‍)]+:[^\‍(\‍)]+)\‍)';
211  $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
212  }
213 
214  $sql .= $this->db->order($sortfield, $sortorder);
215 
216  if ($limit) {
217  if ($page < 0) {
218  $page = 0;
219  }
220  $offset = $limit * $page;
221 
222  $sql .= $this->db->plimit($limit + 1, $offset);
223  }
224 
225  $result = $this->db->query($sql);
226  if ($result) {
227  $num = $this->db->num_rows($result);
228  $min = min($num, ($limit <= 0 ? $num : $limit));
229  $i = 0;
230  while ($i < $min) {
231  $obj = $this->db->fetch_object($result);
232  $soc_static = new Societe($this->db);
233  if ($soc_static->fetch($obj->rowid)) {
234  if (isModEnabled('mailing')) {
235  $soc_static->getNoEmail();
236  }
237  $obj_ret[] = $this->_cleanObjectDatas($soc_static);
238  }
239  $i++;
240  }
241  } else {
242  throw new RestException(503, 'Error when retrieve thirdparties : '.$this->db->lasterror());
243  }
244  if (!count($obj_ret)) {
245  throw new RestException(404, 'Thirdparties not found');
246  }
247  return $obj_ret;
248  }
249 
256  public function post($request_data = null)
257  {
258  if (!DolibarrApiAccess::$user->rights->societe->creer) {
259  throw new RestException(401);
260  }
261  // Check mandatory fields
262  $result = $this->_validate($request_data);
263 
264  foreach ($request_data as $field => $value) {
265  $this->company->$field = $value;
266  }
267  if ($this->company->create(DolibarrApiAccess::$user) < 0) {
268  throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors));
269  }
270  if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
271  $this->company->setNoEmail($this->company->no_email);
272  }
273 
274  return $this->company->id;
275  }
276 
284  public function put($id, $request_data = null)
285  {
286  if (!DolibarrApiAccess::$user->rights->societe->creer) {
287  throw new RestException(401);
288  }
289 
290  $result = $this->company->fetch($id);
291  if (!$result) {
292  throw new RestException(404, 'Thirdparty not found');
293  }
294 
295  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
296  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
297  }
298 
299  foreach ($request_data as $field => $value) {
300  if ($field == 'id') {
301  continue;
302  }
303  $this->company->$field = $value;
304  }
305 
306  if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
307  $this->company->setNoEmail($this->company->no_email);
308  }
309 
310  if ($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update', 1)) {
311  return $this->get($id);
312  }
313 
314  return false;
315  }
316 
331  public function merge($id, $idtodelete)
332  {
333  global $hookmanager;
334 
335  $error = 0;
336 
337  if ($id == $idtodelete) {
338  throw new RestException(400, 'Try to merge a thirdparty into itself');
339  }
340 
341  if (!DolibarrApiAccess::$user->rights->societe->creer) {
342  throw new RestException(401);
343  }
344 
345  $result = $this->company->fetch($id); // include the fetch of extra fields
346  if (!$result) {
347  throw new RestException(404, 'Thirdparty not found');
348  }
349 
350  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
351  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
352  }
353 
354  $this->companytoremove = new Societe($this->db);
355 
356  $result = $this->companytoremove->fetch($idtodelete); // include the fetch of extra fields
357  if (!$result) {
358  throw new RestException(404, 'Thirdparty not found');
359  }
360 
361  if (!DolibarrApi::_checkAccessToResource('societe', $this->companytoremove->id)) {
362  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
363  }
364 
365  $soc_origin = $this->companytoremove;
366  $object = $this->company;
367  $user = DolibarrApiAccess::$user;
368 
369 
370  // Call same code than into action 'confirm_merge'
371 
372 
373  $this->db->begin();
374 
375  // Recopy some data
376  $object->client = $object->client | $soc_origin->client;
377  $object->fournisseur = $object->fournisseur | $soc_origin->fournisseur;
378  $listofproperties = array(
379  'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode',
380  'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
381  'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
382  'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency',
383  'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
384  'model_pdf', 'fk_projet'
385  );
386  foreach ($listofproperties as $property) {
387  if (empty($object->$property)) {
388  $object->$property = $soc_origin->$property;
389  }
390  }
391 
392  // Concat some data
393  $listofproperties = array(
394  'note_public', 'note_private'
395  );
396  foreach ($listofproperties as $property) {
397  $object->$property = dol_concatdesc($object->$property, $soc_origin->$property);
398  }
399 
400  // Merge extrafields
401  if (is_array($soc_origin->array_options)) {
402  foreach ($soc_origin->array_options as $key => $val) {
403  if (empty($object->array_options[$key])) {
404  $object->array_options[$key] = $val;
405  }
406  }
407  }
408 
409  // Merge categories
410  $static_cat = new Categorie($this->db);
411  $custcats = $static_cat->containing($soc_origin->id, 'customer', 'id');
412  $object->setCategories($custcats, 'customer');
413  $suppcats = $static_cat->containing($soc_origin->id, 'supplier', 'id');
414  $object->setCategories($suppcats, 'supplier');
415 
416  // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
417  if ($soc_origin->code_client == $object->code_client
418  || $soc_origin->code_fournisseur == $object->code_fournisseur
419  || $soc_origin->barcode == $object->barcode) {
420  dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
421  $soc_origin->code_client = '';
422  $soc_origin->code_fournisseur = '';
423  $soc_origin->barcode = '';
424  $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
425  }
426 
427  // Update
428  $result = $object->update($object->id, $user, 0, 1, 1, 'merge');
429  if ($result < 0) {
430  $error++;
431  }
432 
433  // Move links
434  if (!$error) {
435  // This list is also into the societe/card.php file
436  // TODO Mutualise the list into object societe.class.php
437  $objects = array(
438  'Adherent' => '/adherents/class/adherent.class.php',
439  'Don' => '/don/class/don.class.php',
440  'Societe' => '/societe/class/societe.class.php',
441  //'Categorie' => '/categories/class/categorie.class.php',
442  'ActionComm' => '/comm/action/class/actioncomm.class.php',
443  'Propal' => '/comm/propal/class/propal.class.php',
444  'Commande' => '/commande/class/commande.class.php',
445  'Facture' => '/compta/facture/class/facture.class.php',
446  'FactureRec' => '/compta/facture/class/facture-rec.class.php',
447  'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
448  'Mo' => '/mrp/class/mo.class.php',
449  'Contact' => '/contact/class/contact.class.php',
450  'Contrat' => '/contrat/class/contrat.class.php',
451  'Expedition' => '/expedition/class/expedition.class.php',
452  'Fichinter' => '/fichinter/class/fichinter.class.php',
453  'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
454  'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
455  'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
456  'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
457  'Delivery' => '/delivery/class/delivery.class.php',
458  'Product' => '/product/class/product.class.php',
459  'Project' => '/projet/class/project.class.php',
460  'Ticket' => '/ticket/class/ticket.class.php',
461  'User' => '/user/class/user.class.php',
462  'Account' => '/compta/bank/class/account.class.php',
463  'ConferenceOrBoothAttendee' => '/eventorganization/class/conferenceorboothattendee.class.php'
464  );
465 
466  //First, all core objects must update their tables
467  foreach ($objects as $object_name => $object_file) {
468  require_once DOL_DOCUMENT_ROOT.$object_file;
469 
470  if (!$error && !$object_name::replaceThirdparty($this->db, $soc_origin->id, $object->id)) {
471  $error++;
472  //setEventMessages($this->db->lasterror(), null, 'errors');
473  }
474  }
475  }
476 
477  // External modules should update their ones too
478  if (!$error) {
479  $reshook = $hookmanager->executeHooks('replaceThirdparty', array(
480  'soc_origin' => $soc_origin->id,
481  'soc_dest' => $object->id
482  ), $soc_dest, $action);
483 
484  if ($reshook < 0) {
485  //setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
486  $error++;
487  }
488  }
489 
490 
491  if (!$error) {
492  $object->context = array('merge'=>1, 'mergefromid'=>$soc_origin->id);
493 
494  // Call trigger
495  $result = $object->call_trigger('COMPANY_MODIFY', $user);
496  if ($result < 0) {
497  //setEventMessages($object->error, $object->errors, 'errors');
498  $error++;
499  }
500  // End call triggers
501  }
502 
503  if (!$error) {
504  //We finally remove the old thirdparty
505  if ($soc_origin->delete($soc_origin->id, $user) < 1) {
506  $error++;
507  }
508  }
509 
510  // End of merge
511 
512  if ($error) {
513  $this->db->rollback();
514 
515  throw new RestException(500, 'Error failed to merged thirdparty '.$this->companytoremove->id.' into '.$id.'. Enable and read log file for more information.');
516  } else {
517  $this->db->commit();
518  }
519 
520  return $this->get($id);
521  }
522 
529  public function delete($id)
530  {
531  if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
532  throw new RestException(401);
533  }
534  $result = $this->company->fetch($id);
535  if (!$result) {
536  throw new RestException(404, 'Thirdparty not found');
537  }
538  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
539  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
540  }
541  $this->company->oldcopy = clone $this->company;
542 
543  $res = $this->company->delete($id);
544  if ($res < 0) {
545  throw new RestException(500, "Can't delete, error occurs");
546  } elseif ($res == 0) {
547  throw new RestException(409, "Can't delete, that product is probably used");
548  }
549 
550  return array(
551  'success' => array(
552  'code' => 200,
553  'message' => 'Object deleted'
554  )
555  );
556  }
557 
573  public function setThirdpartyPriceLevel($id, $priceLevel)
574  {
575  global $conf;
576 
577  if (!isModEnabled('societe')) {
578  throw new RestException(501, 'Module "Thirdparties" needed for this request');
579  }
580 
581  if (empty($conf->product->enabled)) {
582  throw new RestException(501, 'Module "Products" needed for this request');
583  }
584 
585  if (empty($conf->global->PRODUIT_MULTIPRICES)) {
586  throw new RestException(501, 'Multiprices features activation needed for this request');
587  }
588 
589  if ($priceLevel < 1 || $priceLevel > $conf->global->PRODUIT_MULTIPRICES_LIMIT) {
590  throw new RestException(400, 'Price level must be between 1 and '.$conf->global->PRODUIT_MULTIPRICES_LIMIT);
591  }
592 
593  if (empty(DolibarrApiAccess::$user->rights->societe->creer)) {
594  throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
595  }
596 
597  $result = $this->company->fetch($id);
598  if ($result < 0) {
599  throw new RestException(404, 'Thirdparty '.$id.' not found');
600  }
601 
602  if (empty($result)) {
603  throw new RestException(500, 'Error fetching thirdparty '.$id, array_merge(array($this->company->error), $this->company->errors));
604  }
605 
606  if (empty(DolibarrApi::_checkAccessToResource('societe', $this->company->id))) {
607  throw new RestException(401, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
608  }
609 
610  $result = $this->company->setPriceLevel($priceLevel, DolibarrApiAccess::$user);
611  if ($result <= 0) {
612  throw new RestException(500, 'Error setting new price level for thirdparty '.$id, array($this->company->db->lasterror()));
613  }
614 
615  return $this->_cleanObjectDatas($this->company);
616  }
617 
631  public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
632  {
633  if (!DolibarrApiAccess::$user->rights->categorie->lire) {
634  throw new RestException(401);
635  }
636 
637  $result = $this->company->fetch($id);
638  if (!$result) {
639  throw new RestException(404, 'Thirdparty not found');
640  }
641 
642  $categories = new Categorie($this->db);
643 
644  $result = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page);
645 
646  if (is_numeric($result) && $result < 0) {
647  throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
648  }
649 
650  if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
651  return array();
652  }
653 
654  return $result;
655  }
656 
667  public function addCategory($id, $category_id)
668  {
669  if (!DolibarrApiAccess::$user->rights->societe->creer) {
670  throw new RestException(401);
671  }
672 
673  $result = $this->company->fetch($id);
674  if (!$result) {
675  throw new RestException(404, 'Thirdparty not found');
676  }
677  $category = new Categorie($this->db);
678  $result = $category->fetch($category_id);
679  if (!$result) {
680  throw new RestException(404, 'category not found');
681  }
682 
683  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
684  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
685  }
686  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
687  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
688  }
689 
690  $category->add_type($this->company, 'customer');
691 
692  return $this->_cleanObjectDatas($this->company);
693  }
694 
705  public function deleteCategory($id, $category_id)
706  {
707  if (!DolibarrApiAccess::$user->rights->societe->creer) {
708  throw new RestException(401);
709  }
710 
711  $result = $this->company->fetch($id);
712  if (!$result) {
713  throw new RestException(404, 'Thirdparty not found');
714  }
715  $category = new Categorie($this->db);
716  $result = $category->fetch($category_id);
717  if (!$result) {
718  throw new RestException(404, 'category not found');
719  }
720 
721  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
722  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
723  }
724  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
725  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
726  }
727 
728  $category->del_type($this->company, 'customer');
729 
730  return $this->_cleanObjectDatas($this->company);
731  }
732 
746  public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
747  {
748  if (!DolibarrApiAccess::$user->rights->categorie->lire) {
749  throw new RestException(401);
750  }
751 
752  $result = $this->company->fetch($id);
753  if (!$result) {
754  throw new RestException(404, 'Thirdparty not found');
755  }
756 
757  $categories = new Categorie($this->db);
758 
759  $result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page);
760 
761  if (is_numeric($result) && $result < 0) {
762  throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
763  }
764 
765  if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
766  return array();
767  }
768 
769  return $result;
770  }
771 
782  public function addSupplierCategory($id, $category_id)
783  {
784  if (!DolibarrApiAccess::$user->rights->societe->creer) {
785  throw new RestException(401);
786  }
787 
788  $result = $this->company->fetch($id);
789  if (!$result) {
790  throw new RestException(404, 'Thirdparty not found');
791  }
792  $category = new Categorie($this->db);
793  $result = $category->fetch($category_id);
794  if (!$result) {
795  throw new RestException(404, 'category not found');
796  }
797 
798  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
799  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
800  }
801  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
802  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
803  }
804 
805  $category->add_type($this->company, 'supplier');
806 
807  return $this->_cleanObjectDatas($this->company);
808  }
809 
820  public function deleteSupplierCategory($id, $category_id)
821  {
822  if (!DolibarrApiAccess::$user->rights->societe->creer) {
823  throw new RestException(401);
824  }
825 
826  $result = $this->company->fetch($id);
827  if (!$result) {
828  throw new RestException(404, 'Thirdparty not found');
829  }
830  $category = new Categorie($this->db);
831  $result = $category->fetch($category_id);
832  if (!$result) {
833  throw new RestException(404, 'category not found');
834  }
835 
836  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
837  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
838  }
839  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
840  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
841  }
842 
843  $category->del_type($this->company, 'supplier');
844 
845  return $this->_cleanObjectDatas($this->company);
846  }
847 
848 
863  public function getOutStandingProposals($id, $mode = 'customer')
864  {
865  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
866  throw new RestException(401);
867  }
868 
869  if (empty($id)) {
870  throw new RestException(400, 'Thirdparty ID is mandatory');
871  }
872 
873  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
874  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
875  }
876 
877  $result = $this->company->fetch($id);
878  if (!$result) {
879  throw new RestException(404, 'Thirdparty not found');
880  }
881 
882  $result = $this->company->getOutstandingProposals($mode);
883 
884  unset($result['total_ht']);
885  unset($result['total_ttc']);
886 
887  return $result;
888  }
889 
890 
905  public function getOutStandingOrder($id, $mode = 'customer')
906  {
907  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
908  throw new RestException(401);
909  }
910 
911  if (empty($id)) {
912  throw new RestException(400, 'Thirdparty ID is mandatory');
913  }
914 
915  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
916  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
917  }
918 
919  $result = $this->company->fetch($id);
920  if (!$result) {
921  throw new RestException(404, 'Thirdparty not found');
922  }
923 
924  $result = $this->company->getOutstandingOrders($mode);
925 
926  unset($result['total_ht']);
927  unset($result['total_ttc']);
928 
929  return $result;
930  }
931 
946  public function getOutStandingInvoices($id, $mode = 'customer')
947  {
948  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
949  throw new RestException(401);
950  }
951 
952  if (empty($id)) {
953  throw new RestException(400, 'Thirdparty ID is mandatory');
954  }
955 
956  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
957  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
958  }
959 
960  $result = $this->company->fetch($id);
961  if (!$result) {
962  throw new RestException(404, 'Thirdparty not found');
963  }
964 
965  $result = $this->company->getOutstandingBills($mode);
966 
967  unset($result['total_ht']);
968  unset($result['total_ttc']);
969 
970  return $result;
971  }
972 
987  public function getSalesRepresentatives($id, $mode = 0)
988  {
989  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
990  throw new RestException(401);
991  }
992 
993  if (empty($id)) {
994  throw new RestException(400, 'Thirdparty ID is mandatory');
995  }
996 
997  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
998  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
999  }
1000 
1001  $result = $this->company->fetch($id);
1002  if (!$result) {
1003  throw new RestException(404, 'Thirdparty not found');
1004  }
1005 
1006  $result = $this->company->getSalesRepresentatives(DolibarrApiAccess::$user, $mode);
1007 
1008  return $result;
1009  }
1010 
1028  public function getFixedAmountDiscounts($id, $filter = "none", $sortfield = "f.type", $sortorder = 'ASC')
1029  {
1030  $obj_ret = array();
1031 
1032  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1033  throw new RestException(401);
1034  }
1035 
1036  if (empty($id)) {
1037  throw new RestException(400, 'Thirdparty ID is mandatory');
1038  }
1039 
1040  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1041  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1042  }
1043 
1044  $result = $this->company->fetch($id);
1045  if (!$result) {
1046  throw new RestException(404, 'Thirdparty not found');
1047  }
1048 
1049 
1050  $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";
1051  $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re, ".MAIN_DB_PREFIX."facture as f";
1052  $sql .= " WHERE f.rowid = re.fk_facture_source AND re.fk_soc = ".((int) $id);
1053  if ($filter == "available") {
1054  $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL";
1055  }
1056  if ($filter == "used") {
1057  $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)";
1058  }
1059 
1060  $sql .= $this->db->order($sortfield, $sortorder);
1061 
1062  $result = $this->db->query($sql);
1063  if (!$result) {
1064  throw new RestException(503, $this->db->lasterror());
1065  } else {
1066  $num = $this->db->num_rows($result);
1067  while ($obj = $this->db->fetch_object($result)) {
1068  $obj_ret[] = $obj;
1069  }
1070  }
1071 
1072  return $obj_ret;
1073  }
1074 
1075 
1076 
1091  {
1092  if (!DolibarrApiAccess::$user->rights->facture->lire) {
1093  throw new RestException(401);
1094  }
1095  if (empty($id)) {
1096  throw new RestException(400, 'Thirdparty ID is mandatory');
1097  }
1098 
1099  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1100  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1101  }
1102 
1103  /*$result = $this->thirdparty->fetch($id);
1104  if( ! $result ) {
1105  throw new RestException(404, 'Thirdparty not found');
1106  }*/
1107 
1108  $invoice = new Facture($this->db);
1109  $result = $invoice->list_replacable_invoices($id);
1110  if ($result < 0) {
1111  throw new RestException(405, $invoice->error);
1112  }
1113 
1114  return $result;
1115  }
1116 
1134  {
1135  if (!DolibarrApiAccess::$user->rights->facture->lire) {
1136  throw new RestException(401);
1137  }
1138  if (empty($id)) {
1139  throw new RestException(400, 'Thirdparty ID is mandatory');
1140  }
1141 
1142  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1143  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1144  }
1145 
1146  /*$result = $this->thirdparty->fetch($id);
1147  if( ! $result ) {
1148  throw new RestException(404, 'Thirdparty not found');
1149  }*/
1150 
1151  $invoice = new Facture($this->db);
1152  $result = $invoice->list_qualified_avoir_invoices($id);
1153  if ($result < 0) {
1154  throw new RestException(405, $invoice->error);
1155  }
1156 
1157  return $result;
1158  }
1159 
1169  public function getCompanyBankAccount($id)
1170  {
1171  if (!DolibarrApiAccess::$user->rights->societe->lire) {
1172  throw new RestException(401);
1173  }
1174  if (empty($id)) {
1175  throw new RestException(400, 'Thirdparty ID is mandatory');
1176  }
1177 
1178  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1179  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1180  }
1181 
1186  $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,";
1187  $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur";
1188  $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1189  if ($id) {
1190  $sql .= " WHERE fk_soc = ".((int) $id);
1191  }
1192 
1193  $result = $this->db->query($sql);
1194 
1195  if ($this->db->num_rows($result) == 0) {
1196  throw new RestException(404, 'Account not found');
1197  }
1198 
1199  $i = 0;
1200 
1201  $accounts = array();
1202 
1203  if ($result) {
1204  $num = $this->db->num_rows($result);
1205  while ($i < $num) {
1206  $obj = $this->db->fetch_object($result);
1207  $account = new CompanyBankAccount($this->db);
1208  if ($account->fetch($obj->rowid)) {
1209  $accounts[] = $account;
1210  }
1211  $i++;
1212  }
1213  } else {
1214  throw new RestException(404, 'Account not found');
1215  }
1216 
1217 
1218  $fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum');
1219 
1220  $returnAccounts = array();
1221 
1222  foreach ($accounts as $account) {
1223  $object = array();
1224  foreach ($account as $key => $value) {
1225  if (in_array($key, $fields)) {
1226  $object[$key] = $value;
1227  }
1228  }
1229  $returnAccounts[] = $object;
1230  }
1231 
1232  return $returnAccounts;
1233  }
1234 
1244  public function createCompanyBankAccount($id, $request_data = null)
1245  {
1246  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1247  throw new RestException(401);
1248  }
1249  if ($this->company->fetch($id) <= 0) {
1250  throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1251  }
1252  $account = new CompanyBankAccount($this->db);
1253 
1254  $account->socid = $id;
1255 
1256  foreach ($request_data as $field => $value) {
1257  $account->$field = $value;
1258  }
1259 
1260  if ($account->create(DolibarrApiAccess::$user) < 0) {
1261  throw new RestException(500, 'Error creating Company Bank account');
1262  }
1263 
1264  if (empty($account->rum)) {
1265  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1266  $prelevement = new BonPrelevement($this->db);
1267  $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1268  $account->date_rum = dol_now();
1269  }
1270 
1271  if ($account->update(DolibarrApiAccess::$user) < 0) {
1272  throw new RestException(500, 'Error updating values');
1273  }
1274 
1275  return $this->_cleanObjectDatas($account);
1276  }
1277 
1289  public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
1290  {
1291  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1292  throw new RestException(401);
1293  }
1294  if ($this->company->fetch($id) <= 0) {
1295  throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1296  }
1297  $account = new CompanyBankAccount($this->db);
1298 
1299  $account->fetch($bankaccount_id, $id, -1, '');
1300 
1301  if ($account->socid != $id) {
1302  throw new RestException(401);
1303  }
1304 
1305 
1306  foreach ($request_data as $field => $value) {
1307  $account->$field = $value;
1308  }
1309 
1310  if (empty($account->rum)) {
1311  require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1312  $prelevement = new BonPrelevement($this->db);
1313  $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1314  $account->date_rum = dol_now();
1315  }
1316 
1317  if ($account->update(DolibarrApiAccess::$user) < 0) {
1318  throw new RestException(500, 'Error updating values');
1319  }
1320 
1321  return $this->_cleanObjectDatas($account);
1322  }
1323 
1334  public function deleteCompanyBankAccount($id, $bankaccount_id)
1335  {
1336  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1337  throw new RestException(401);
1338  }
1339 
1340  $account = new CompanyBankAccount($this->db);
1341 
1342  $account->fetch($bankaccount_id);
1343 
1344  if (!$account->socid == $id) {
1345  throw new RestException(401);
1346  }
1347 
1348  return $account->delete(DolibarrApiAccess::$user);
1349  }
1350 
1361  public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
1362  {
1363  global $conf, $langs;
1364 
1365  $langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals"));
1366 
1367  if ($this->company->fetch($id) <= 0) {
1368  throw new RestException(404, 'Thirdparty not found');
1369  }
1370 
1371  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1372  throw new RestException(401);
1373  }
1374 
1375  $this->company->setDocModel(DolibarrApiAccess::$user, $model);
1376 
1377  $this->company->fk_bank = $this->company->fk_account;
1378 
1379  $outputlangs = $langs;
1380  $newlang = '';
1381 
1382  //if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
1383  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1384  if (isset($this->company->thirdparty->default_lang)) {
1385  $newlang = $this->company->thirdparty->default_lang; // for proposal, order, invoice, ...
1386  } elseif (isset($this->company->default_lang)) {
1387  $newlang = $this->company->default_lang; // for thirdparty
1388  }
1389  }
1390  if (!empty($newlang)) {
1391  $outputlangs = new Translate("", $conf);
1392  $outputlangs->setDefaultLang($newlang);
1393  }
1394 
1395  $sql = "SELECT rowid";
1396  $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1397  if ($id) {
1398  $sql .= " WHERE fk_soc = ".((int) $id);
1399  }
1400  if ($companybankid) {
1401  $sql .= " AND rowid = ".((int) $companybankid);
1402  }
1403 
1404  $i = 0;
1405  $accounts = array();
1406 
1407  $result = $this->db->query($sql);
1408  if ($result) {
1409  if ($this->db->num_rows($result) == 0) {
1410  throw new RestException(404, 'Bank account not found');
1411  }
1412 
1413  $num = $this->db->num_rows($result);
1414  while ($i < $num) {
1415  $obj = $this->db->fetch_object($result);
1416 
1417  $account = new CompanyBankAccount($this->db);
1418  if ($account->fetch($obj->rowid)) {
1419  $accounts[] = $account;
1420  }
1421  $i++;
1422  }
1423  } else {
1424  throw new RestException(500, 'Sql error '.$this->db->lasterror());
1425  }
1426 
1427  $moreparams = array(
1428  'use_companybankid' => $accounts[0]->id,
1429  'force_dir_output' => $conf->societe->multidir_output[$this->company->entity].'/'.dol_sanitizeFileName($this->company->id)
1430  );
1431 
1432  $result = $this->company->generateDocument($model, $outputlangs, 0, 0, 0, $moreparams);
1433 
1434  if ($result > 0) {
1435  return array("success" => $result);
1436  } else {
1437  throw new RestException(500, 'Error generating the document '.$this->company->error);
1438  }
1439  }
1440 
1453  public function getSocieteAccounts($id, $site = null)
1454  {
1455  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1456  throw new RestException(401);
1457  }
1458 
1459  if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1460  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1461  }
1462 
1466  $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
1467  $sql .= " WHERE fk_soc = ".((int) $id);
1468  if ($site) {
1469  $sql .= " AND site ='".$this->db->escape($site)."'";
1470  }
1471 
1472  $result = $this->db->query($sql);
1473 
1474  if ($result && $this->db->num_rows($result) == 0) {
1475  throw new RestException(404, 'This thirdparty does not have any gateway attached or does not exist.');
1476  }
1477 
1478  $i = 0;
1479 
1480  $accounts = array();
1481 
1482  $num = $this->db->num_rows($result);
1483  while ($i < $num) {
1484  $obj = $this->db->fetch_object($result);
1485  $account = new SocieteAccount($this->db);
1486 
1487  if ($account->fetch($obj->rowid)) {
1488  $accounts[] = $account;
1489  }
1490  $i++;
1491  }
1492 
1493  $fields = array('id', 'fk_soc', 'key_account', 'site', 'date_creation', 'tms');
1494 
1495  $returnAccounts = array();
1496 
1497  foreach ($accounts as $account) {
1498  $object = array();
1499  foreach ($account as $key => $value) {
1500  if (in_array($key, $fields)) {
1501  $object[$key] = $value;
1502  }
1503  }
1504  $returnAccounts[] = $object;
1505  }
1506 
1507  return $returnAccounts;
1508  }
1509 
1529  public function createSocieteAccount($id, $request_data = null)
1530  {
1531  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1532  throw new RestException(401);
1533  }
1534 
1535  if (!isset($request_data['site'])) {
1536  throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !');
1537  }
1538 
1539  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."'";
1540  $result = $this->db->query($sql);
1541 
1542  if ($result && $this->db->num_rows($result) == 0) {
1543  $account = new SocieteAccount($this->db);
1544  if (!isset($request_data['login'])) {
1545  $account->login = "";
1546  }
1547  $account->fk_soc = $id;
1548 
1549  foreach ($request_data as $field => $value) {
1550  $account->$field = $value;
1551  }
1552 
1553  if ($account->create(DolibarrApiAccess::$user) < 0) {
1554  throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!');
1555  }
1556 
1557  $this->_cleanObjectDatas($account);
1558 
1559  return $account;
1560  } else {
1561  throw new RestException(409, 'A SocieteAccount entity already exists for this company and site.');
1562  }
1563  }
1564 
1587  public function putSocieteAccount($id, $site, $request_data = null)
1588  {
1589  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1590  throw new RestException(401);
1591  }
1592 
1593  $sql = "SELECT rowid, fk_user_creat, date_creation FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
1594  $result = $this->db->query($sql);
1595 
1596  // We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one.
1597  if ($result && $this->db->num_rows == 0) {
1598  if (!isset($request_data['key_account'])) {
1599  throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !');
1600  }
1601  $account = new SocieteAccount($this->db);
1602  if (!isset($request_data['login'])) {
1603  $account->login = "";
1604  }
1605 
1606  foreach ($request_data as $field => $value) {
1607  $account->$field = $value;
1608  }
1609 
1610  $account->fk_soc = $id;
1611  $account->site = $site;
1612 
1613  if ($account->create(DolibarrApiAccess::$user) < 0) {
1614  throw new RestException(500, 'Error creating SocieteAccount entity.');
1615  }
1616  // We found an existing SocieteAccount entity, we are replacing it
1617  } else {
1618  if (isset($request_data['site']) && $request_data['site'] !== $site) {
1619  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
1620  $result = $this->db->query($sql);
1621 
1622  if ($result && $this->db->num_rows($result) !== 0) {
1623  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.");
1624  }
1625  }
1626 
1627  $obj = $this->db->fetch_object($result);
1628 
1629  $account = new SocieteAccount($this->db);
1630  $account->id = $obj->rowid;
1631  $account->fk_soc = $id;
1632  $account->site = $site;
1633  if (!isset($request_data['login'])) {
1634  $account->login = "";
1635  }
1636  $account->fk_user_creat = $obj->fk_user_creat;
1637  $account->date_creation = $obj->date_creation;
1638 
1639  foreach ($request_data as $field => $value) {
1640  $account->$field = $value;
1641  }
1642 
1643  if ($account->update(DolibarrApiAccess::$user) < 0) {
1644  throw new RestException(500, 'Error updating SocieteAccount entity.');
1645  }
1646  }
1647 
1648  $this->_cleanObjectDatas($account);
1649 
1650  return $account;
1651  }
1652 
1669  public function patchSocieteAccount($id, $site, $request_data = null)
1670  {
1671  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1672  throw new RestException(401);
1673  }
1674 
1675  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
1676  $result = $this->db->query($sql);
1677 
1678  if ($result && $this->db->num_rows($result) == 0) {
1679  throw new RestException(404, "This thirdparty does not have $site gateway attached or does not exist.");
1680  } else {
1681  // If the user tries to edit the site member, we check first if
1682  if (isset($request_data['site']) && $request_data['site'] !== $site) {
1683  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
1684  $result = $this->db->query($sql);
1685 
1686  if ($result && $this->db->num_rows($result) !== 0) {
1687  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.");
1688  }
1689  }
1690 
1691  $obj = $this->db->fetch_object($result);
1692  $account = new SocieteAccount($this->db);
1693  $account->fetch($obj->rowid);
1694 
1695  foreach ($request_data as $field => $value) {
1696  $account->$field = $value;
1697  }
1698 
1699  if ($account->update(DolibarrApiAccess::$user) < 0) {
1700  throw new RestException(500, 'Error updating SocieteAccount account');
1701  }
1702 
1703  $this->_cleanObjectDatas($account);
1704 
1705  return $account;
1706  }
1707  }
1708 
1722  public function deleteSocieteAccount($id, $site)
1723  {
1724  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1725  throw new RestException(401);
1726  }
1727 
1728  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
1729  $result = $this->db->query($sql);
1730 
1731  if ($result && $this->db->num_rows($result) == 0) {
1732  throw new RestException(404);
1733  } else {
1734  $obj = $this->db->fetch_object($result);
1735  $account = new SocieteAccount($this->db);
1736  $account->fetch($obj->rowid);
1737 
1738  if ($account->delete(DolibarrApiAccess::$user) < 0) {
1739  throw new RestException(500, "Error while deleting $site gateway attached to this third party");
1740  }
1741  }
1742  }
1743 
1756  public function deleteSocieteAccounts($id)
1757  {
1758  if (!DolibarrApiAccess::$user->rights->societe->creer) {
1759  throw new RestException(401);
1760  }
1761 
1766  $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms";
1767  $sql .= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id);
1768 
1769  $result = $this->db->query($sql);
1770 
1771  if ($result && $this->db->num_rows($result) == 0) {
1772  throw new RestException(404, 'This third party does not have any gateway attached or does not exist.');
1773  } else {
1774  $i = 0;
1775 
1776  $num = $this->db->num_rows($result);
1777  while ($i < $num) {
1778  $obj = $this->db->fetch_object($result);
1779  $account = new SocieteAccount($this->db);
1780  $account->fetch($obj->rowid);
1781 
1782  if ($account->delete(DolibarrApiAccess::$user) < 0) {
1783  throw new RestException(500, 'Error while deleting gateways attached to this third party');
1784  }
1785  $i++;
1786  }
1787  }
1788  }
1789 
1790  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1797  protected function _cleanObjectDatas($object)
1798  {
1799  // phpcs:enable
1800  $object = parent::_cleanObjectDatas($object);
1801 
1802  unset($object->nom); // ->name already defined and nom deprecated
1803  unset($object->name_bis); // ->name_alias already defined
1804  unset($object->note); // ->note_private and note_public already defined
1805  unset($object->departement);
1806  unset($object->departement_code);
1807  unset($object->pays);
1808  unset($object->particulier);
1809  unset($object->prefix_comm);
1810 
1811  unset($object->siren);
1812  unset($object->siret);
1813  unset($object->ape);
1814 
1815  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.
1816 
1817  unset($object->total_ht);
1818  unset($object->total_tva);
1819  unset($object->total_localtax1);
1820  unset($object->total_localtax2);
1821  unset($object->total_ttc);
1822 
1823  unset($object->lines);
1824  unset($object->thirdparty);
1825 
1826  unset($object->fk_delivery_address); // deprecated feature
1827 
1828  unset($object->skype);
1829  unset($object->twitter);
1830  unset($object->facebook);
1831  unset($object->linkedin);
1832  unset($object->instagram);
1833  unset($object->snapchat);
1834  unset($object->googleplus);
1835  unset($object->youtube);
1836  unset($object->whatsapp);
1837 
1838  return $object;
1839  }
1840 
1849  private function _validate($data)
1850  {
1851  $thirdparty = array();
1852  foreach (Thirdparties::$FIELDS as $field) {
1853  if (!isset($data[$field])) {
1854  throw new RestException(400, "$field field missing");
1855  }
1856  $thirdparty[$field] = $data[$field];
1857  }
1858  return $thirdparty;
1859  }
1860 
1882  private function _fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1883  {
1884  global $conf;
1885 
1886  if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1887  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on thirdparties.');
1888  }
1889 
1890  if ($rowid === 0) {
1891  $result = $this->company->initAsSpecimen();
1892  } else {
1893  $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
1894  }
1895  if (!$result) {
1896  throw new RestException(404, 'Thirdparty not found');
1897  }
1898 
1899  if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
1900  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login.' on this thirdparty');
1901  }
1902  if (isModEnabled('mailing')) {
1903  $this->company->getNoEmail();
1904  }
1905 
1906  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
1907  $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1908  $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1909  } else {
1910  $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
1911  $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
1912  }
1913 
1914  $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount);
1915  $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote);
1916  $this->company->absolute_discount = price2num($absolute_discount, 'MT');
1917  $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
1918 
1919  return $this->_cleanObjectDatas($this->company);
1920  }
1921 }
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
_checkFilters($sqlfilters, &$error='')
Return if a $sqlfilters parameter is valid.
Definition: api.class.php:310
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 '.
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