dolibarr 25.0.0-alpha
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-2026 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2023 Alexandre Janniaux <alexandre.janniaux@gmail.com>
7 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024 Jon Bendtsen <jon.bendtsen.github@jonb.dk>
9 * Copyright (C) 2025 William Mead <william@m34d.com>
10 * Copyright (C) 2025 Charlene Benke <charlene@patas-monkey.com>
11 * Copyright (C) 2026 Benjamin Falière <benjamin@faliere.com>
12 * Copyright (C) 2026 Noé Cendrier <noe.cendrier@altairis.fr>
13 * Copyright (C) 2026 Nick Fragoulis
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27 */
28
29use Luracast\Restler\RestException;
30
31require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
32
42{
46 public static $FIELDS = array(
47 'name'
48 );
49
53 public $company;
54
58 public function __construct()
59 {
60 global $db;
61 $this->db = $db;
62
63 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
64 require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
65 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
66 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
67 require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
68
69 $this->company = new Societe($this->db);
70
71 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY')) {
72 static::$FIELDS[] = 'email';
73 }
74 }
75
88 public function get($id)
89 {
90 return $this->_fetch($id);
91 }
92
109 public function getByEmail($email)
110 {
111 return $this->_fetch(null, '', '', '', '', '', '', '', '', '', $email);
112 }
113
128 public function getByBarcode($barcode)
129 {
130 return $this->_fetch(null, '', '', $barcode);
131 }
132
159 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
160 {
161 $obj_ret = array();
162
163 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
164 throw new RestException(403);
165 }
166
167 // case of external user, we force socids
168 $socids = DolibarrApiAccess::$user->socid ? (string) DolibarrApiAccess::$user->socid : '';
169
170 // If the internal user must only see his customers, force searching by him
171 $search_sale = 0;
172 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
173 $search_sale = DolibarrApiAccess::$user->id;
174 }
175
176 $sql = "SELECT t.rowid";
177 $sql .= " FROM ".MAIN_DB_PREFIX."societe as t";
178 $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
179 if ($category > 0) {
180 if ($mode != 4) {
181 $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c";
182 }
183 if (!in_array($mode, array(1, 2, 3))) {
184 $sql .= ", ".MAIN_DB_PREFIX."categorie_fournisseur as cc";
185 }
186 }
187 $sql .= " WHERE t.entity IN (".getEntity('societe').")";
188 if ($mode == 1) {
189 $sql .= " AND t.client IN (1, 3)";
190 } elseif ($mode == 2) {
191 $sql .= " AND t.client IN (2, 3)";
192 } elseif ($mode == 3) {
193 $sql .= " AND t.client IN (0)";
194 } elseif ($mode == 4) {
195 $sql .= " AND t.fournisseur IN (1)";
196 }
197 // Select third parties of a given category
198 if ($category > 0) {
199 if (!empty($mode) && $mode != 4) {
200 $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid";
201 } elseif (!empty($mode) && $mode == 4) {
202 $sql .= " AND cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid";
203 } else {
204 $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))";
205 }
206 }
207 if ($socids) {
208 $sql .= " AND t.rowid IN (".$this->db->sanitize($socids).")";
209 }
210 // Search on sale representative
211 if ($search_sale && $search_sale != '-1') {
212 if ($search_sale == -2) {
213 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.rowid', 0, 1);
214 } elseif ($search_sale > 0) {
215 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.rowid', (int) $search_sale);
216 }
217 }
218 // Add sql filters
219 if ($sqlfilters) {
220 $errormessage = '';
221 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
222 if ($errormessage) {
223 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
224 }
225 }
226
227 //this query will return total thirdparties with the filters given
228 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
229
230 $sql .= $this->db->order($sortfield, $sortorder);
231 if ($limit) {
232 if ($page < 0) {
233 $page = 0;
234 }
235 $offset = $limit * $page;
236
237 $sql .= $this->db->plimit($limit + 1, $offset);
238 }
239
240 $result = $this->db->query($sql);
241 if ($result) {
242 $num = $this->db->num_rows($result);
243 $min = min($num, ($limit <= 0 ? $num : $limit));
244 $i = 0;
245 while ($i < $min) {
246 $obj = $this->db->fetch_object($result);
247 $soc_static = new Societe($this->db);
248 if ($soc_static->fetch($obj->rowid)) {
249 if (isModEnabled('mailing')) {
250 $soc_static->getNoEmail();
251 }
252 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($soc_static), $properties);
253 }
254 $i++;
255 }
256 } else {
257 throw new RestException(503, 'Error when retrieve third parties : '.$this->db->lasterror());
258 }
259 if (!count($obj_ret)) {
260 $message = '';
261 switch ($mode) {
262 case 0:
263 $message = 'No third parties found';
264 break;
265 case 1:
266 $message = 'No customers found';
267 break;
268 case 2:
269 $message = 'No prospects found';
270 break;
271 case 3:
272 $message = 'No other third parties found';
273 break;
274 case 4:
275 $message = 'No suppliers found';
276 }
277 throw new RestException(404, $message);
278 }
279
280 //if $pagination_data is true, the response will contain element data with all values and element pagination with pagination data(total,page,limit)
281 if ($pagination_data) {
282 $totalsResult = $this->db->query($sqlTotals);
283 $total = $this->db->fetch_object($totalsResult)->total;
284
285 $tmp = $obj_ret;
286 $obj_ret = [];
287
288 $obj_ret['data'] = $tmp;
289 $obj_ret['pagination'] = [
290 'total' => (int) $total,
291 'page' => $page, //count starts from 0
292 'page_count' => ceil((int) $total / $limit),
293 'limit' => $limit
294 ];
295 }
296
297 return $obj_ret;
298 }
299
312 public function post($request_data = null)
313 {
314 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
315 throw new RestException(403);
316 }
317
318 // External api user does not know internal country ID
319 if (!isset($request_data['country_id']) && isset($request_data['country_code'])) {
320 $field = strlen($request_data['country_code']) > 2 ? 'code_iso' : 'code';
321 $id = dol_getIdFromCode($this->db, $request_data['country_code'], "c_country", $field, "rowid");
322 if ($id < 0) {
323 throw new RestException(404, 'Country code not found in database: ' . $this->db->lasterror());
324 }
325 $request_data['country_id'] = $id;
326 }
327
328 // Check mandatory fields
329 $result = $this->_validate($request_data);
330
331 foreach ($request_data as $field => $value) {
332 if ($field === 'caller') {
333 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
334 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
335 continue;
336 }
337 if ($field == 'array_options' && is_array($value)) {
338 $this->company->fetch_optionals(); // To force the load of the extrafields definition by fetch_name_optionals_label()
339
340 foreach ($value as $index => $val) {
341 $this->company->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->company);
342 }
343 continue;
344 }
345
346 $this->company->$field = $this->_checkValForAPI($field, $value, $this->company);
347 }
348
349 if ($this->company->create(DolibarrApiAccess::$user) < 0) {
350 throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors));
351 }
352 if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
353 $this->company->setNoEmail($this->company->no_email);
354 }
355
356 return $this->company->id;
357 }
358
376 public function put($id, $request_data = null)
377 {
378 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
379 throw new RestException(403);
380 }
381
382 $result = $this->company->fetch($id);
383 if (!$result) {
384 throw new RestException(404, 'Thirdparty not found');
385 }
386
387 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
388 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
389 }
390
391 foreach ($request_data as $field => $value) {
392 if ($field == 'id') {
393 continue;
394 }
395 if ($field === 'caller') {
396 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
397 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
398 continue;
399 }
400 if ($field == 'array_options' && is_array($value)) {
401 foreach ($value as $index => $val) {
402 $this->company->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->company);
403 }
404 continue;
405 }
406 $this->company->$field = $this->_checkValForAPI($field, $value, $this->company);
407 }
408
409 if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
410 $this->company->setNoEmail($this->company->no_email);
411 }
412
413 if ($this->company->update($id, DolibarrApiAccess::$user, 1, 1, 1, 'update', 1) > 0) {
414 return $this->get($id);
415 } else {
416 throw new RestException(500, $this->company->errorsToString());
417 }
418 }
419
441 public function merge($id, $idtodelete)
442 {
443 if ($id == $idtodelete) {
444 throw new RestException(400, 'Try to merge a thirdparty into itself');
445 }
446
447 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
448 throw new RestException(403);
449 }
450
451 $result = $this->company->fetch($id); // include the fetch of extra fields
452 if (!$result) {
453 throw new RestException(404, 'Thirdparty not found');
454 }
455
456 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
457 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
458 }
459
460 $companytoremove = new Societe($this->db);
461 $result = $companytoremove->fetch($idtodelete); // include the fetch of extra fields
462 if (!$result) {
463 throw new RestException(404, 'Thirdparty not found');
464 }
465
466 if (!DolibarrApi::_checkAccessToResource('societe', $companytoremove->id)) {
467 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
468 }
469
470 $user = DolibarrApiAccess::$user;
471 $result = $this->company->mergeCompany($companytoremove->id);
472 if ($result < 0) {
473 throw new RestException(500, 'Error failed to merged thirdparty '.$companytoremove->id.' into '.$id.'. Enable and read log file for more information.');
474 }
475
476 return $this->get($id);
477 }
478
491 public function delete($id)
492 {
493 if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
494 throw new RestException(403);
495 }
496 $result = $this->company->fetch($id);
497 if (!$result) {
498 throw new RestException(404, 'Thirdparty not found');
499 }
500 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
501 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
502 }
503 $this->company->oldcopy = clone $this->company; // @phan-suppress-current-line PhanTypeMismatchProperty
504
505 $res = $this->company->delete($id);
506 if ($res < 0) {
507 throw new RestException(500, "Can't delete, error occurs");
508 } elseif ($res == 0) {
509 throw new RestException(409, "Can't delete, that product is probably used");
510 }
511
512 return array(
513 'success' => array(
514 'code' => 200,
515 'message' => 'Object deleted'
516 )
517 );
518 }
519
537 public function setThirdpartyPriceLevel($id, $priceLevel)
538 {
539 global $conf;
540
541 if (!isModEnabled('societe')) {
542 throw new RestException(501, 'Module "Thirdparties" needed for this request');
543 }
544
545 if (!isModEnabled("product")) {
546 throw new RestException(501, 'Module "Products" needed for this request');
547 }
548
549 if (!getDolGlobalString('PRODUIT_MULTIPRICES') && !getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) {
550 throw new RestException(501, 'Multiprices features activation needed for this request');
551 }
552
553 if ($priceLevel < 1 || $priceLevel > getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT')) {
554 throw new RestException(400, 'Price level must be between 1 and ' . getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT'));
555 }
556
557 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
558 throw new RestException(403, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
559 }
560
561 $result = $this->company->fetch($id);
562 if ($result < 0) {
563 throw new RestException(404, 'Thirdparty '.$id.' not found');
564 }
565
566 if (empty($result)) {
567 throw new RestException(500, 'Error fetching thirdparty '.$id, array_merge(array($this->company->error), $this->company->errors));
568 }
569
570 if (empty(DolibarrApi::_checkAccessToResource('societe', $this->company->id))) {
571 throw new RestException(403, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
572 }
573
574 $result = $this->company->setPriceLevel($priceLevel, DolibarrApiAccess::$user);
575 if ($result <= 0) {
576 throw new RestException(500, 'Error setting new price level for thirdparty '.$id, array($this->company->db->lasterror()));
577 }
578
579 return $this->_cleanObjectDatas($this->company);
580 }
581
595 public function getRepresentative($id)
596 {
597 if (!DolibarrApiAccess::$user->hasRight('societe', 'reader')) {
598 throw new RestException(403);
599 }
600 $result = $this->company->fetch($id);
601 if (!$result) {
602 throw new RestException(404, 'Thirdparty not found');
603 }
604 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
605 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
606 }
607 $result = $this->company->getSalesRepresentatives(DolibarrApiAccess::$user);
610 return $result;
611 }
612
627 public function addRepresentative($id, $representative_id)
628 {
629 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
630 throw new RestException(403);
631 }
632 $result = $this->company->fetch($id);
633 if (!$result) {
634 throw new RestException(404, 'Thirdparty not found');
635 }
636 $usertmp = new User($this->db);
637 $result = $usertmp->fetch($representative_id);
638 if (!$result) {
639 throw new RestException(404, 'User not found');
640 }
641 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
642 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
643 }
644 $result = $this->company->add_commercial(DolibarrApiAccess::$user, $representative_id);
645
646 return $result;
647 }
648
663 public function deleteRepresentative($id, $representative_id)
664 {
665 if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
666 throw new RestException(403);
667 }
668 $result = $this->company->fetch($id);
669 if (!$result) {
670 throw new RestException(404, 'Thirdparty not found');
671 }
672 $usertmp = new User($this->db);
673 $result = $usertmp->fetch($representative_id);
674 if (!$result) {
675 throw new RestException(404, 'User not found');
676 }
677 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
678 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
679 }
680 $result = $this->company->del_commercial(DolibarrApiAccess::$user, $representative_id);
681
682 return $result;
683 }
684
703 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
704 {
705 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
706 throw new RestException(403);
707 }
708
709 $result = $this->company->fetch($id);
710 if (!$result) {
711 throw new RestException(404, 'Thirdparty not found');
712 }
713
714 // Check that user has permission on thirdparty ID
715 if (!DolibarrApi::_checkAccessToResource('societe', $this->company)) {
716 throw new RestException(404, 'Third party not allowed for login '.DolibarrApiAccess::$user->login);
717 }
718
719 $categories = new Categorie($this->db);
720
721 $arrayofcateg = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page);
722
723 if (is_numeric($arrayofcateg) && $arrayofcateg < 0) {
724 throw new RestException(503, 'Error when retrieve category list : '.$categories->errorsToString());
725 }
726
727 if (is_numeric($arrayofcateg) && $arrayofcateg >= 0) { // To fix a return of 0 instead of empty array of method getListForItem
728 return array();
729 }
730
731 return $arrayofcateg;
732 }
733
750 public function addCategory($id, $category_id)
751 {
752 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
753 throw new RestException(403);
754 }
755
756 $result = $this->company->fetch($id);
757 if (!$result) {
758 throw new RestException(404, 'Third party not found');
759 }
760 $category = new Categorie($this->db);
761 $result = $category->fetch($category_id);
762 if (!$result) {
763 throw new RestException(404, 'category not found');
764 }
765
766 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
767 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
768 }
769 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
770 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
771 }
772
773 $category->add_type($this->company, 'customer');
774
775 return $this->_cleanObjectDatas($this->company);
776 }
777
794 public function deleteCategory($id, $category_id)
795 {
796 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
797 throw new RestException(403);
798 }
799
800 $result = $this->company->fetch($id);
801 if (!$result) {
802 throw new RestException(404, 'Thirdparty not found');
803 }
804 $category = new Categorie($this->db);
805 $result = $category->fetch($category_id);
806 if (!$result) {
807 throw new RestException(404, 'category not found');
808 }
809
810 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
811 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
812 }
813 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
814 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
815 }
816
817 $category->del_type($this->company, 'customer');
818
819 return $this->_cleanObjectDatas($this->company);
820 }
821
841 public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
842 {
843 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
844 throw new RestException(403);
845 }
846
847 $result = $this->company->fetch($id);
848 if (!$result) {
849 throw new RestException(404, 'Thirdparty not found');
850 }
851
852 // Check that user has permission on thirdparty ID
853 if (!DolibarrApi::_checkAccessToResource('societe', $this->company)) {
854 throw new RestException(404, 'Third party not allowed for login '.DolibarrApiAccess::$user->login);
855 }
856
857 $categories = new Categorie($this->db);
858
859 $result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page);
860
861 if (is_numeric($result) && $result < 0) {
862 throw new RestException(503, 'Error when retrieve category list : '.$categories->errorsToString());
863 }
864
865 if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
866 return array();
867 }
868
869 return $result;
870 }
871
888 public function addSupplierCategory($id, $category_id)
889 {
890 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
891 throw new RestException(403);
892 }
893
894 $result = $this->company->fetch($id);
895 if (!$result) {
896 throw new RestException(404, 'Thirdparty not found');
897 }
898 $category = new Categorie($this->db);
899 $result = $category->fetch($category_id);
900 if (!$result) {
901 throw new RestException(404, 'category not found');
902 }
903
904 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
905 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
906 }
907 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
908 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
909 }
910
911 $category->add_type($this->company, 'supplier');
912
913 return $this->_cleanObjectDatas($this->company);
914 }
915
932 public function deleteSupplierCategory($id, $category_id)
933 {
934 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
935 throw new RestException(403);
936 }
937
938 $result = $this->company->fetch($id);
939 if (!$result) {
940 throw new RestException(404, 'Thirdparty not found');
941 }
942 $category = new Categorie($this->db);
943 $result = $category->fetch($category_id);
944 if (!$result) {
945 throw new RestException(404, 'category not found');
946 }
947
948 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
949 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
950 }
951 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
952 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
953 }
954
955 $category->del_type($this->company, 'supplier');
956
957 return $this->_cleanObjectDatas($this->company);
958 }
959
960
979 public function getOutStandingProposals($id, $mode = 'customer')
980 {
981 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
982 throw new RestException(403);
983 }
984
985 if (empty($id)) {
986 throw new RestException(400, 'Thirdparty ID is mandatory');
987 }
988
989 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
990 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
991 }
992
993 $result = $this->company->fetch($id);
994 if (!$result) {
995 throw new RestException(404, 'Thirdparty not found');
996 }
997
998 $result = $this->company->getOutstandingProposals($mode);
999
1000 unset($result['total_ht']);
1001 unset($result['total_ttc']);
1002
1003 return $result;
1004 }
1005
1006
1025 public function getOutStandingOrder($id, $mode = 'customer')
1026 {
1027 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1028 throw new RestException(403);
1029 }
1030
1031 if (empty($id)) {
1032 throw new RestException(400, 'Thirdparty ID is mandatory');
1033 }
1034
1035 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1036 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1037 }
1038
1039 $result = $this->company->fetch($id);
1040 if (!$result) {
1041 throw new RestException(404, 'Thirdparty not found');
1042 }
1043
1044 $result = $this->company->getOutstandingOrders($mode);
1045
1046 unset($result['total_ht']);
1047 unset($result['total_ttc']);
1048
1049 return $result;
1050 }
1051
1070 public function getOutStandingInvoices($id, $mode = 'customer')
1071 {
1072 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1073 throw new RestException(403);
1074 }
1075
1076 if (empty($id)) {
1077 throw new RestException(400, 'Thirdparty ID is mandatory');
1078 }
1079
1080 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1081 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1082 }
1083
1084 $result = $this->company->fetch($id);
1085 if (!$result) {
1086 throw new RestException(404, 'Thirdparty not found');
1087 }
1088
1089 $result = $this->company->getOutstandingBills($mode);
1090
1091 unset($result['total_ht']);
1092 unset($result['total_ttc']);
1093
1094 return $result;
1095 }
1096
1115 public function getSalesRepresentatives($id, $mode = 0)
1116 {
1117 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1118 throw new RestException(403);
1119 }
1120
1121 if (empty($id)) {
1122 throw new RestException(400, 'Thirdparty ID is mandatory');
1123 }
1124
1125 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1126 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1127 }
1128
1129 $result = $this->company->fetch($id);
1130 if ($result <= 0) {
1131 throw new RestException(404, 'Thirdparty not found');
1132 }
1133
1134 $result = $this->company->getSalesRepresentatives(DolibarrApiAccess::$user, $mode);
1135
1136 return $result;
1137 }
1138
1163 public function getFixedAmountDiscounts($id, $mode = 'customer', $filter = "none", $sortfield = "f.type", $sortorder = 'ASC')
1164 {
1165 $obj_ret = array();
1166
1167 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1168 throw new RestException(403);
1169 }
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(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1177 }
1178
1179 $result = $this->company->fetch($id);
1180 if (!$result) {
1181 throw new RestException(404, 'Thirdparty not found');
1182 }
1183
1184 $sql = '';
1185 if ($mode === 'customer') {
1186 $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";
1187 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1188 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = re.fk_facture_source";
1189 $sql .= " WHERE re.fk_soc = ".((int) $id);
1190 if ($filter == "available") {
1191 $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL";
1192 }
1193 if ($filter == "used") {
1194 $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)";
1195 }
1196 } elseif ($mode === 'supplier') {
1197 $sql = "SELECT f.ref, f.type as factype, re.fk_invoice_supplier_source, re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc, re.description, re.fk_invoice_supplier, re.fk_invoice_supplier_line";
1198 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1199 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as f ON f.rowid = re.fk_invoice_supplier_source";
1200 $sql .= " WHERE f.rowid = re.fk_invoice_supplier_source AND re.fk_soc = ".((int) $id);
1201 if ($filter == "available") {
1202 $sql .= " AND re.fk_invoice_supplier IS NULL AND re.fk_invoice_supplier_line IS NULL";
1203 }
1204 if ($filter == "used") {
1205 $sql .= " AND (re.fk_invoice_supplier IS NOT NULL OR re.fk_invoice_supplier_line IS NOT NULL)";
1206 }
1207 }
1208
1209 $sql .= $this->db->order($sortfield, $sortorder);
1210
1211 $result = $this->db->query($sql);
1212 if (!$result) {
1213 throw new RestException(503, $this->db->lasterror());
1214 } else {
1215 //$num = $this->db->num_rows($result);
1216 while ($obj = $this->db->fetch_object($result)) {
1217 $obj_ret[] = $obj;
1218 }
1219 }
1220
1221 return $obj_ret;
1222 }
1223
1248 public function createFixedAmountDiscount($id, $request_data = null)
1249 {
1250 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1251 throw new RestException(403);
1252 }
1253
1254 // Check mandatory fields
1255 if (empty($id)) {
1256 throw new RestException(400, 'Thirdparty ID is mandatory');
1257 }
1258 if (!isset($request_data['amount'])) {
1259 throw new RestException(400, 'Missing required field: amount');
1260 }
1261 if (!isset($request_data['description'])) {
1262 throw new RestException(400, 'Missing required field: description');
1263 }
1264
1265 // Check access to resource
1266 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1267 throw new RestException(401, 'Access not allowed for login'.DolibarrApiAccess::$user->login);
1268 }
1269
1270 // Fetch thirdparty to verify it exists
1271 if ($this->company->fetch($id) <= 0) {
1272 throw new RestException(404, 'Error creating discount, thirdparty not found');
1273 }
1274
1275
1276 // Validate amount
1277 if (!is_numeric($request_data['amount']) || $request_data['amount'] <= 0) {
1278 throw new RestException(400, 'Invalid amount_ht: must be a positive number');
1279 }
1280 $amount = (float) $request_data['amount'];
1281
1282 // Validate VAT rate
1283 if (isset($request_data['tva_tx']) && (!is_numeric($request_data['tva_tx']) || $request_data['tva_tx'] < 0)) {
1284 throw new RestException(400, 'Invalid tva_tx: must be a positive number or zero');
1285 }
1286 $tva_tx = isset($request_data['tva_tx']) ? (float) $request_data['tva_tx'] : 0;
1287
1288 // Get price base type (HT or TTC) : HT as default
1289 $price_base_type = 'HT';
1290 if (isset($request_data['price_base_type'])) {
1291 $price_base_type = strtoupper($request_data['price_base_type']);
1292 if ($price_base_type !== 'HT' && $price_base_type !== 'TTC') {
1293 throw new RestException(400, 'Invalid price_base_type: must be "HT" or "TTC"');
1294 }
1295 }
1296
1297 // Get discount type (0 = customer, 1 = supplier): 0 as default
1298 $discount_type = 0;
1299 if (isset($request_data['discount_type'])) {
1300 $discount_type = (int) $request_data['discount_type'];
1301 if ($discount_type !== 0 && $discount_type !== 1) {
1302 throw new RestException(400, 'Invalid discount_type: must be 0 (customer) or 1 (supplier)');
1303 }
1304 }
1305
1306 // Get description
1307 $description = $request_data['description'];
1308 if (empty(trim($description))) {
1309 throw new RestException(400, 'Description cannot be empty');
1310 }
1311
1312 // Prepare VAT rate with code if provided
1313 $vatrate = (string) $tva_tx;
1314 if (isset($request_data['vat_src_code']) && !empty($request_data['vat_src_code'])) {
1315 $vatrate = $tva_tx . ' (' . $request_data['vat_src_code'] . ')';
1316 }
1317
1318 // Create the discount using Societe::set_remise_except()
1319 $this->db->begin();
1320
1321 $result = $this->company->set_remise_except($amount, DolibarrApiAccess::$user, $description, $vatrate, $discount_type, $price_base_type);
1322
1323 if ($result > 0) {
1324 $this->db->commit();
1325 return $result;
1326 } else {
1327 $this->db->rollback();
1328 throw new RestException(500, 'Error creating discount: '.$this->company->error, array_merge(array($this->company->error), $this->company->errors));
1329 }
1330 }
1331
1355 public function splitdiscount($id, $discountid, $amount_ttc_1, $amount_ttc_2)
1356 {
1357 $obj_ret = array();
1358
1359 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer') || !DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1360 throw new RestException(403);
1361 }
1362
1363 if (empty($id)) {
1364 throw new RestException(400, 'Thirdparty ID is mandatory');
1365 }
1366 if (empty($discountid)) {
1367 throw new RestException(400, 'Discount ID is mandatory');
1368 }
1369 if (empty($amount_ttc_1) || empty($amount_ttc_2)) {
1370 throw new RestException(400, 'Amount are mandatory');
1371 }
1372
1373 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1374 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1375 }
1376
1377 $result = $this->company->fetch($id);
1378 if (!$result) {
1379 throw new RestException(404, 'Thirdparty not found');
1380 }
1381 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1382 $discount = new DiscountAbsolute($this->db);
1383 $res = $discount->fetch($discountid);
1384 if (!($res > 0)) {
1385 throw new RestException(404, 'Discount not found');
1386 }
1387 if ($discount->socid != $id) {
1388 throw new RestException(405, 'Discount not owned by this thirdpartie');
1389 }
1390
1391 if (price2num((float) $amount_ttc_1 + (float) $amount_ttc_2) != $discount->amount_ttc) {
1392 throw new RestException(405, 'Sum of the 2 discounts is different that the original discount');
1393 }
1394 if ($discount->fk_facture_line) {
1395 throw new RestException(409, 'Discount is already used');
1396 }
1397
1398 $newdiscount1 = new DiscountAbsolute($this->db);
1399 $newdiscount2 = new DiscountAbsolute($this->db);
1400
1401 $newdiscount1->fk_facture_source = $discount->fk_facture_source;
1402 $newdiscount2->fk_facture_source = $discount->fk_facture_source;
1403 $newdiscount1->fk_facture = $discount->fk_facture;
1404 $newdiscount2->fk_facture = $discount->fk_facture;
1405 $newdiscount1->fk_facture_line = $discount->fk_facture_line;
1406 $newdiscount2->fk_facture_line = $discount->fk_facture_line;
1407 $newdiscount1->fk_invoice_supplier_source = $discount->fk_invoice_supplier_source;
1408 $newdiscount2->fk_invoice_supplier_source = $discount->fk_invoice_supplier_source;
1409 $newdiscount1->fk_invoice_supplier = $discount->fk_invoice_supplier;
1410 $newdiscount2->fk_invoice_supplier = $discount->fk_invoice_supplier;
1411 $newdiscount1->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line;
1412 $newdiscount2->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line;
1413 if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)') {
1414 $newdiscount1->description = $discount->description;
1415 $newdiscount2->description = $discount->description;
1416 } else {
1417 $newdiscount1->description = $discount->description.' (1)';
1418 $newdiscount2->description = $discount->description.' (2)';
1419 }
1420
1421 $newdiscount1->fk_user = $discount->fk_user;
1422 $newdiscount2->fk_user = $discount->fk_user;
1423 $newdiscount1->fk_soc = $discount->fk_soc;
1424 $newdiscount1->socid = $discount->socid;
1425 $newdiscount2->fk_soc = $discount->fk_soc;
1426 $newdiscount2->socid = $discount->socid;
1427 $newdiscount1->discount_type = $discount->discount_type;
1428 $newdiscount2->discount_type = $discount->discount_type;
1429 $newdiscount1->datec = $discount->datec;
1430 $newdiscount2->datec = $discount->datec;
1431 $newdiscount1->tva_tx = $discount->tva_tx;
1432 $newdiscount2->tva_tx = $discount->tva_tx;
1433 $newdiscount1->vat_src_code = $discount->vat_src_code;
1434 $newdiscount2->vat_src_code = $discount->vat_src_code;
1435 $newdiscount1->amount_ttc = $amount_ttc_1;
1436 $newdiscount2->amount_ttc = price2num($discount->amount_ttc - $newdiscount1->amount_ttc);
1437 $newdiscount1->amount_ht = price2num($newdiscount1->amount_ttc / (1 + $newdiscount1->tva_tx / 100), 'MT');
1438 $newdiscount2->amount_ht = price2num($newdiscount2->amount_ttc / (1 + $newdiscount2->tva_tx / 100), 'MT');
1439 $newdiscount1->amount_tva = price2num($newdiscount1->amount_ttc - $newdiscount1->amount_ht);
1440 $newdiscount2->amount_tva = price2num($newdiscount2->amount_ttc - $newdiscount2->amount_ht);
1441
1442 $newdiscount1->multicurrency_amount_ttc = (float) $amount_ttc_1 * ($discount->multicurrency_amount_ttc / $discount->amount_ttc);
1443 $newdiscount2->multicurrency_amount_ttc = price2num($discount->multicurrency_amount_ttc - $newdiscount1->multicurrency_amount_ttc);
1444 $newdiscount1->multicurrency_amount_ht = price2num($newdiscount1->multicurrency_amount_ttc / (1 + $newdiscount1->tva_tx / 100), 'MT');
1445 $newdiscount2->multicurrency_amount_ht = price2num($newdiscount2->multicurrency_amount_ttc / (1 + $newdiscount2->tva_tx / 100), 'MT');
1446 $newdiscount1->multicurrency_amount_tva = price2num($newdiscount1->multicurrency_amount_ttc - $newdiscount1->multicurrency_amount_ht);
1447 $newdiscount2->multicurrency_amount_tva = price2num($newdiscount2->multicurrency_amount_ttc - $newdiscount2->multicurrency_amount_ht);
1448
1449 // DiscountAbsolute->amount_ttc ->amount_ht ->amount_tva are marked as @deprecated but seems to yet be in use so we fill ->amout_xxx and ->total_xxx
1450 // the same for multicurrency_amount_xxx and multicurrency_total_xxx
1451 $newdiscount1->total_ttc = (float) price2num($newdiscount1->amount_ttc);
1452 $newdiscount1->total_ht = (float) price2num($newdiscount1->amount_ht);
1453 $newdiscount1->total_tva = (float) price2num($newdiscount1->amount_tva);
1454 $newdiscount2->total_ttc = (float) price2num($newdiscount2->amount_ttc);
1455 $newdiscount2->total_ht = (float) price2num($newdiscount2->amount_ht);
1456 $newdiscount2->total_tva = (float) price2num($newdiscount2->amount_tva);
1457 $newdiscount1->multicurrency_total_ttc = (float) price2num($newdiscount1->multicurrency_amount_ttc);
1458 $newdiscount1->multicurrency_total_ht = (float) price2num($newdiscount1->multicurrency_amount_ht);
1459 $newdiscount1->multicurrency_total_tva = (float) price2num($newdiscount1->multicurrency_amount_tva);
1460 $newdiscount2->multicurrency_total_ttc = (float) price2num($newdiscount2->multicurrency_amount_ttc);
1461 $newdiscount2->multicurrency_total_ht = (float) price2num($newdiscount2->multicurrency_amount_ht);
1462 $newdiscount2->multicurrency_total_tva = (float) price2num($newdiscount2->multicurrency_amount_tva);
1463
1464 $this->db->begin();
1465
1466 $discount->fk_facture_source = 0; // This is to delete only the require record (that we will recreate with two records) and not all family with same fk_facture_source
1467 // This is to delete only the require record (that we will recreate with two records) and not all family with same fk_invoice_supplier_source
1468 $discount->fk_invoice_supplier_source = 0;
1469 $res = $discount->delete(DolibarrApiAccess::$user);
1470 $newid1 = $newdiscount1->create(DolibarrApiAccess::$user);
1471 $newid2 = $newdiscount2->create(DolibarrApiAccess::$user);
1472 if ($res <= 0 || $newid1 <= 0 || $newid2 <= 0) {
1473 $this->db->rollback();
1474 throw new RestException(500, 'Operation fail');
1475 }
1476
1477 $this->db->commit();
1478
1479 $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";
1480 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re, ".MAIN_DB_PREFIX."facture as f";
1481 $sql .= " WHERE re.rowid IN (".((int) $newid1).",".((int) $newid2).") AND f.rowid = re.fk_facture_source AND re.fk_soc = ".((int) $id);
1482
1483 $sql .= $this->db->order("f.type", "ASC");
1484
1485 $result = $this->db->query($sql);
1486 if (!$result) {
1487 throw new RestException(503, $this->db->lasterror());
1488 } else {
1489 // $num = $this->db->num_rows($result);
1490 while ($obj = $this->db->fetch_object($result)) {
1491 $obj_ret[] = $obj;
1492 }
1493 }
1494
1495 return $obj_ret;
1496 }
1497
1498
1517 {
1518 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1519 throw new RestException(403);
1520 }
1521 if (empty($id)) {
1522 throw new RestException(400, 'Thirdparty ID is mandatory');
1523 }
1524
1525 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1526 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1527 }
1528
1529 /*$result = $this->thirdparty->fetch($id);
1530 if( ! $result ) {
1531 throw new RestException(404, 'Thirdparty not found');
1532 }*/
1533
1534 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1535 $invoice = new Facture($this->db);
1536 $result = $invoice->list_replacable_invoices($id);
1537 if ($result < 0) {
1538 throw new RestException(405, $invoice->errorsToString());
1539 }
1540
1541 return $result;
1542 }
1543
1566 {
1567 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1568 throw new RestException(403);
1569 }
1570 if (empty($id)) {
1571 throw new RestException(400, 'Thirdparty ID is mandatory');
1572 }
1573
1574 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1575 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1576 }
1577
1578 /*$result = $this->thirdparty->fetch($id);
1579 if( ! $result ) {
1580 throw new RestException(404, 'Thirdparty not found');
1581 }*/
1582
1583 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1584 $invoice = new Facture($this->db);
1585 $result = $invoice->list_qualified_avoir_invoices($id);
1586 if (!is_array($result) && $result < 0) {
1587 throw new RestException(405, $invoice->errorsToString());
1588 }
1589
1590 return $result;
1591 }
1592
1609 {
1610 if (empty($id)) {
1611 throw new RestException(400, 'Thirdparty ID is mandatory');
1612 }
1613 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1614 throw new RestException(403);
1615 }
1616 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1617 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1618 }
1619
1624 $sql = "SELECT rowid as id, fk_action as event, fk_soc as socid, fk_contact as contact_id, type, datec, tms";
1625 $sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1626 if ($id) {
1627 $sql .= " WHERE fk_soc = ".((int) $id);
1628 }
1629
1630 $result = $this->db->query($sql);
1631 if ($this->db->num_rows($result) == 0) {
1632 throw new RestException(404, 'Notification not found');
1633 }
1634
1635 $i = 0;
1636
1637 $notifications = array();
1638
1639 if ($result) {
1640 $i = 0;
1641 $num = $this->db->num_rows($result);
1642 //$min = min($num, ($limit <= 0 ? $num : $limit));
1643 $min = $num;
1644 while ($i < $min) {
1645 $obj = $this->db->fetch_object($result);
1646 $notifications[] = $obj;
1647 $i++;
1648 }
1649 } else {
1650 throw new RestException(404, 'No notifications found');
1651 }
1652
1653 $fields = array('id', 'socid', 'event', 'contact_id', 'datec', 'tms', 'type');
1654
1655 $returnNotifications = array();
1656
1657 foreach ($notifications as $notification) {
1658 $object = array();
1659 foreach ($notification as $key => $value) {
1660 if (in_array($key, $fields)) {
1661 $object[$key] = $value;
1662 }
1663 }
1664 $returnNotifications[] = $object;
1665 }
1666
1667 // Too complex for phan ?: @phan-suppress-next-line PhanTypeMismatchReturn
1668 return $returnNotifications;
1669 }
1670
1687 public function createCompanyNotification($id, $request_data = null)
1688 {
1689 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1690 throw new RestException(403, "User has no right to update thirdparties");
1691 }
1692
1693 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1694 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1695 }
1696
1697 if ($this->company->fetch($id) <= 0) {
1698 throw new RestException(404, 'Error creating Thirdparty Notification, Thirdparty doesn\'t exists');
1699 }
1700 $notification = new Notify($this->db);
1701
1702 $notification->socid = $id;
1703
1704 foreach ($request_data as $field => $value) {
1705 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1706 }
1707
1708 $event = $notification->event;
1709 if (!$event) {
1710 throw new RestException(500, 'Error creating Thirdparty Notification, request_data missing event');
1711 }
1712 $socid = $notification->socid;
1713 $contact_id = $notification->contact_id;
1714
1715 $exists_sql = "SELECT rowid, fk_action as event, fk_soc as socid, fk_contact as contact_id, type, datec, tms as datem";
1716 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1717 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1718 $exists_sql .= " AND fk_soc = '".$this->db->escape((string) $socid)."'";
1719 $exists_sql .= " AND fk_contact = '".$this->db->escape((string) $contact_id)."'";
1720
1721 $exists_result = $this->db->query($exists_sql);
1722 if ($this->db->num_rows($exists_result) > 0) {
1723 throw new RestException(403, 'Notification already exists');
1724 }
1725
1726 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1727 throw new RestException(500, 'Error creating Thirdparty Notification');
1728 }
1729
1730 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1731 throw new RestException(500, 'Error updating values');
1732 }
1733
1734 return $this->_cleanObjectDatas($notification);
1735 }
1736
1755 public function createCompanyNotificationByCode($id, $code, $request_data = null)
1756 {
1757 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1758 throw new RestException(403, "User has no right to update thirdparties");
1759 }
1760
1761 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1762 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1763 }
1764
1765 if ($this->company->fetch($id) <= 0) {
1766 throw new RestException(404, 'Error creating Thirdparty Notification, Thirdparty doesn\'t exists');
1767 }
1768 $notification = new Notify($this->db);
1769 $notification->socid = $id;
1770
1771 $sql = "SELECT t.rowid as id FROM ".MAIN_DB_PREFIX."c_action_trigger as t";
1772 $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
1773
1774 $result = $this->db->query($sql);
1775 if ($this->db->num_rows($result) == 0) {
1776 throw new RestException(404, 'Action Trigger code not found');
1777 }
1778
1779 $notification->event = $this->db->fetch_row($result)[0];
1780 foreach ($request_data as $field => $value) {
1781 if ($field === 'event') {
1782 throw new RestException(500, 'Error creating Thirdparty Notification, request_data contains event key');
1783 }
1784 if ($field === 'fk_action') {
1785 throw new RestException(500, 'Error creating Thirdparty Notification, request_data contains fk_action key');
1786 }
1787 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1788 }
1789
1790 $event = $notification->event;
1791 $socid = $notification->socid;
1792 $contact_id = $notification->contact_id;
1793
1794 $exists_sql = "SELECT rowid, fk_action as event, fk_soc as socid, fk_contact as contact_id, type, datec, tms as datem";
1795 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1796 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1797 $exists_sql .= " AND fk_soc = '".$this->db->escape((string) $socid)."'";
1798 $exists_sql .= " AND fk_contact = '".$this->db->escape((string) $contact_id)."'";
1799
1800 $exists_result = $this->db->query($exists_sql);
1801 if ($this->db->num_rows($exists_result) > 0) {
1802 throw new RestException(403, 'Notification already exists');
1803 }
1804
1805 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1806 throw new RestException(500, 'Error creating Thirdparty Notification, are request_data well formed?');
1807 }
1808
1809 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1810 throw new RestException(500, 'Error updating values');
1811 }
1812
1813 return $this->_cleanObjectDatas($notification);
1814 }
1815
1830 public function deleteCompanyNotification($id, $notification_id)
1831 {
1832 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1833 throw new RestException(403);
1834 }
1835
1836 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1837 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1838 }
1839
1840 $notification = new Notify($this->db);
1841
1842 $notification->fetch($notification_id);
1843
1844 $socid = (int) $notification->socid;
1845
1846 if ($socid == $id) {
1847 return $notification->delete(DolibarrApiAccess::$user);
1848 } else {
1849 throw new RestException(403, "Not allowed due to bad consistency of input data");
1850 }
1851 }
1852
1870 public function updateCompanyNotification($id, $notification_id, $request_data = null)
1871 {
1872 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1873 throw new RestException(403, "User has no right to update thirdparties");
1874 }
1875
1876 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1877 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1878 }
1879
1880 if ($this->company->fetch($id) <= 0) {
1881 throw new RestException(404, 'Error creating Company Notification, Company doesn\'t exists');
1882 }
1883 $notification = new Notify($this->db);
1884
1885 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1886 $notification->fetch($notification_id, $id);
1887
1888 if ($notification->socid != $id) {
1889 throw new RestException(403, "Not allowed due to bad consistency of input data");
1890 }
1891
1892 foreach ($request_data as $field => $value) {
1893 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1894 }
1895
1896 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1897 throw new RestException(500, 'Error updating values');
1898 }
1899
1900 return $this->_cleanObjectDatas($notification);
1901 }
1902
1919 {
1920 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1921 throw new RestException(403);
1922 }
1923 if (empty($id)) {
1924 throw new RestException(400, 'Thirdparty ID is mandatory');
1925 }
1926
1927 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1928 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1929 }
1930
1935 $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation as address, proprio,";
1936 $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur";
1937 $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1938 if ($id) {
1939 $sql .= " WHERE fk_soc = ".((int) $id);
1940 }
1941
1942 $result = $this->db->query($sql);
1943
1944 if ($this->db->num_rows($result) == 0) {
1945 throw new RestException(404, 'Account not found');
1946 }
1947
1948 $i = 0;
1949
1950 $accounts = array();
1951
1952 if ($result) {
1953 $i = 0;
1954 $num = $this->db->num_rows($result);
1955 //$min = min($num, ($limit <= 0 ? $num : $limit));
1956 $min = $num;
1957 while ($i < $min) {
1958 $obj = $this->db->fetch_object($result);
1959
1960 $account = new CompanyBankAccount($this->db);
1961 if ($account->fetch($obj->rowid)) {
1962 $accounts[] = $account;
1963 }
1964 $i++;
1965 }
1966 } else {
1967 throw new RestException(404, 'Account not found');
1968 }
1969
1970
1971 $fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum', 'payment_reference');
1972
1973 $returnAccounts = array();
1974
1975 foreach ($accounts as $account) {
1976 $object = array();
1977 foreach ($account as $key => $value) {
1978 if (in_array($key, $fields)) {
1979 if ($key == 'iban') {
1980 $object[$key] = dolDecrypt($value);
1981 } else {
1982 $object[$key] = $value;
1983 }
1984 }
1985 }
1986 $returnAccounts[] = $object;
1987 }
1988
1989 return $returnAccounts;
1990 }
1991
2008 public function createCompanyBankAccount($id, $request_data = null)
2009 {
2010 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2011 throw new RestException(403);
2012 }
2013 if ($this->company->fetch($id) <= 0) {
2014 throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
2015 }
2016
2017 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2018 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2019 }
2020
2021 $account = new CompanyBankAccount($this->db);
2022
2023 $account->socid = $id;
2024
2025 foreach ($request_data as $field => $value) {
2026 if ($field === 'caller') {
2027 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
2028 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2029 continue;
2030 }
2031
2032 $account->$field = $this->_checkValForAPI('extrafields', $value, $account);
2033 }
2034
2035 if ($account->create(DolibarrApiAccess::$user) < 0) {
2036 throw new RestException(500, 'Error creating Company Bank account');
2037 }
2038
2039 if (empty($account->rum)) {
2040 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
2041 $prelevement = new BonPrelevement($this->db);
2042 $account->rum = $prelevement->buildRumNumber((string) $this->company->code_client, $account->datec, (string) $account->id);
2043 $account->date_rum = dol_now();
2044 }
2045
2046 if ($account->update(DolibarrApiAccess::$user) < 0) {
2047 throw new RestException(500, 'Error updating values');
2048 }
2049
2050 return $this->_cleanObjectDatas($account);
2051 }
2052
2070 public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
2071 {
2072 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2073 throw new RestException(403);
2074 }
2075 if ($this->company->fetch($id) <= 0) {
2076 throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
2077 }
2078
2079 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2080 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2081 }
2082
2083 $account = new CompanyBankAccount($this->db);
2084
2085 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
2086 $account->fetch($bankaccount_id, '', $id, -1, '');
2087
2088 if ($account->socid != $id) {
2089 throw new RestException(403);
2090 }
2091
2092
2093 foreach ($request_data as $field => $value) {
2094 if ($field === 'caller') {
2095 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
2096 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2097 continue;
2098 }
2099
2100 $account->$field = $this->_checkValForAPI($field, $value, $account);
2101 }
2102
2103 if (empty($account->rum)) {
2104 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
2105 $prelevement = new BonPrelevement($this->db);
2106 $account->rum = $prelevement->buildRumNumber((string) $this->company->code_client, $account->datec, (string) $account->id);
2107 $account->date_rum = dol_now();
2108 }
2109
2110 if ($account->update(DolibarrApiAccess::$user) < 0) {
2111 throw new RestException(500, 'Error updating values');
2112 }
2113
2114 return $this->_cleanObjectDatas($account);
2115 }
2116
2131 public function deleteCompanyBankAccount($id, $bankaccount_id)
2132 {
2133 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2134 throw new RestException(403);
2135 }
2136
2137 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2138 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2139 }
2140
2141 $account = new CompanyBankAccount($this->db);
2142
2143 $account->fetch($bankaccount_id);
2144
2145 $socid = (int) $account->socid;
2146
2147 if ($socid == $id) {
2148 return $account->delete(DolibarrApiAccess::$user);
2149 } else {
2150 throw new RestException(403, "Not allowed due to bad consistency of input data");
2151 }
2152 }
2153
2172 public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
2173 {
2174 global $conf, $langs;
2175
2176 $langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals"));
2177
2178 if ($this->company->fetch($id) <= 0) {
2179 throw new RestException(404, 'Thirdparty not found');
2180 }
2181
2182 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2183 throw new RestException(403);
2184 }
2185
2186 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2187 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2188 }
2189
2190 $this->company->setDocModel(DolibarrApiAccess::$user, $model);
2191
2192 $this->company->fk_bank = $this->company->fk_account;
2193 // $this->company->fk_account = $this->company->fk_account;
2194
2195 $outputlangs = $langs;
2196 $newlang = '';
2197
2198 //if (getDolGlobalInt('MAIN_MULTILANGS') && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
2199 if (getDolGlobalInt('MAIN_MULTILANGS')) {
2200 if (isset($this->company->thirdparty->default_lang)) {
2201 $newlang = $this->company->thirdparty->default_lang; // for proposal, order, invoice, ...
2202 } elseif (isset($this->company->default_lang)) {
2203 $newlang = $this->company->default_lang; // for thirdparty
2204 }
2205 }
2206 if (!empty($newlang)) {
2207 $outputlangs = new Translate("", $conf);
2208 $outputlangs->setDefaultLang($newlang);
2209 }
2210
2211 $sql = "SELECT rowid";
2212 $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
2213 if ($id) {
2214 $sql .= " WHERE fk_soc = ".((int) $id);
2215 }
2216 if ($companybankid) {
2217 $sql .= " AND rowid = ".((int) $companybankid);
2218 }
2219
2220 $i = 0;
2221 $accounts = array();
2222
2223 $result = $this->db->query($sql);
2224 if ($result) {
2225 if ($this->db->num_rows($result) == 0) {
2226 throw new RestException(404, 'Bank account not found');
2227 }
2228
2229 $num = $this->db->num_rows($result);
2230 //$min = min($num, ($limit <= 0 ? $num : $limit));
2231 $min = $num;
2232 while ($i < $min) {
2233 $obj = $this->db->fetch_object($result);
2234
2235 $account = new CompanyBankAccount($this->db);
2236 if ($account->fetch($obj->rowid)) {
2237 $accounts[] = $account;
2238 }
2239 $i++;
2240 }
2241 } else {
2242 throw new RestException(500, 'Sql error '.$this->db->lasterror());
2243 }
2244
2245 $moreparams = array(
2246 'use_companybankid' => $accounts[0]->id,
2247 'force_dir_output' => $conf->societe->multidir_output[$this->company->entity].'/'.dol_sanitizeFileName((string) $this->company->id)
2248 );
2249
2250 $result = $this->company->generateDocument($model, $outputlangs, 0, 0, 0, $moreparams);
2251
2252 if ($result > 0) {
2253 return array("success" => $result);
2254 } else {
2255 throw new RestException(500, 'Error generating the document '.$this->company->errorsToString());
2256 }
2257 }
2258
2276 public function getSocieteAccounts($id, $site = null)
2277 {
2278 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
2279 throw new RestException(403);
2280 }
2281
2282 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2283 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2284 }
2285
2289 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
2290 $sql .= " WHERE fk_soc = ".((int) $id);
2291 if ($site) {
2292 $sql .= " AND site ='".$this->db->escape($site)."'";
2293 }
2294
2295 $result = $this->db->query($sql);
2296
2297 if ($result && $this->db->num_rows($result) == 0) {
2298 throw new RestException(404, 'This thirdparty does not have any account attached or does not exist.');
2299 }
2300
2301 $i = 0;
2302
2303 $accounts = array();
2304
2305 $i = 0;
2306 $num = $this->db->num_rows($result);
2307 //$min = min($num, ($limit <= 0 ? $num : $limit));
2308 $min = $num;
2309 while ($i < $min) {
2310 $obj = $this->db->fetch_object($result);
2311 $account = new SocieteAccount($this->db);
2312
2313 if ($account->fetch($obj->rowid)) {
2314 $accounts[] = $account;
2315 }
2316 $i++;
2317 }
2318
2319 $fields = array('id', 'fk_soc', 'key_account', 'site', 'date_creation', 'tms');
2320
2321 $returnAccounts = array();
2322
2323 foreach ($accounts as $account) {
2324 $object = array();
2325 foreach ($account as $key => $value) {
2326 if (in_array($key, $fields)) {
2327 $object[$key] = $value;
2328 }
2329 }
2330 $returnAccounts[] = $object;
2331 }
2332
2333 return $returnAccounts;
2334 }
2335
2353 public function getSocieteByAccounts($site, $key_account)
2354 {
2355 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
2356 throw new RestException(403);
2357 }
2358
2359 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
2360 $sql .= " WHERE site = '".$this->db->escape($site)."' AND key_account = '".$this->db->escape($key_account)."'";
2361 $sql .= " AND entity IN (".getEntity('societe').")";
2362
2363 $result = $this->db->query($sql);
2364
2365 if ($result && $this->db->num_rows($result) == 1) {
2366 $obj = $this->db->fetch_object($result);
2367 $returnThirdparty = $this->_fetch($obj->fk_soc);
2368 } else {
2369 throw new RestException(404, 'This account have many thirdparties attached or does not exist.');
2370 }
2371
2372 if (!DolibarrApi::_checkAccessToResource('societe', $returnThirdparty->id)) {
2373 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2374 }
2375
2376 return $returnThirdparty;
2377 }
2378
2402 public function createSocieteAccount($id, $request_data = null)
2403 {
2404 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2405 throw new RestException(403);
2406 }
2407
2408 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2409 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2410 }
2411
2412 if (!isset($request_data['site'])) {
2413 throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !');
2414 }
2415
2416 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."'";
2417 $result = $this->db->query($sql);
2418
2419 if ($result && $this->db->num_rows($result) == 0) {
2420 $account = new SocieteAccount($this->db);
2421 if (!isset($request_data['login'])) {
2422 $account->login = "";
2423 }
2424 $account->fk_soc = $id;
2425
2426 foreach ($request_data as $field => $value) {
2427 if ($field === 'caller') {
2428 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
2429 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2430 continue;
2431 }
2432
2433 $account->$field = $this->_checkValForAPI($field, $value, $account);
2434 }
2435
2436 if ($account->create(DolibarrApiAccess::$user) < 0) {
2437 throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!');
2438 }
2439
2440 $this->_cleanObjectDatas($account);
2441
2442 return $account;
2443 } else {
2444 throw new RestException(409, 'A SocieteAccount entity already exists for this company and site.');
2445 }
2446 }
2447
2474 public function postSocieteAccount($id, $site, $request_data = null)
2475 {
2476 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2477 throw new RestException(403);
2478 }
2479
2480 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2481 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2482 }
2483
2484 $sql = "SELECT rowid, fk_user_creat, date_creation FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
2485 $result = $this->db->query($sql);
2486
2487 // We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one.
2488 if ($result && $this->db->num_rows($result) == 0) {
2489 if (!isset($request_data['key_account'])) {
2490 throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !');
2491 }
2492 $account = new SocieteAccount($this->db);
2493 if (!isset($request_data['login'])) {
2494 $account->login = "";
2495 }
2496
2497 foreach ($request_data as $field => $value) {
2498 if ($field === 'caller') {
2499 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
2500 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2501 continue;
2502 }
2503
2504 $account->$field = $this->_checkValForAPI($field, $value, $account);
2505 }
2506
2507 $account->fk_soc = $id;
2508 $account->site = $site;
2509
2510 if ($account->create(DolibarrApiAccess::$user) < 0) {
2511 throw new RestException(500, 'Error creating SocieteAccount entity.');
2512 }
2513 // We found an existing SocieteAccount entity, we are replacing it
2514 } else {
2515 if (isset($request_data['site']) && $request_data['site'] !== $site) {
2516 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
2517 $result = $this->db->query($sql);
2518
2519 if ($result && $this->db->num_rows($result) !== 0) {
2520 throw new RestException(409, "You are trying to update this thirdparty Account for $site to ".$request_data['site']." but another Account already exists with this site key.");
2521 }
2522 }
2523
2524 $obj = $this->db->fetch_object($result);
2525
2526 $account = new SocieteAccount($this->db);
2527 $account->id = $obj->rowid;
2528 $account->fk_soc = $id;
2529 $account->site = $site;
2530 if (!isset($request_data['login'])) {
2531 $account->login = "";
2532 }
2533 $account->fk_user_creat = $obj->fk_user_creat;
2534 $account->date_creation = $obj->date_creation;
2535
2536 foreach ($request_data as $field => $value) {
2537 if ($field === 'caller') {
2538 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
2539 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2540 continue;
2541 }
2542
2543 $account->$field = $this->_checkValForAPI($field, $value, $account);
2544 }
2545
2546 if ($account->update(DolibarrApiAccess::$user) < 0) {
2547 throw new RestException(500, 'Error updating SocieteAccount entity.');
2548 }
2549 }
2550
2551 $this->_cleanObjectDatas($account);
2552
2553 return $account;
2554 }
2555
2576 public function putSocieteAccount($id, $site, $request_data = null)
2577 {
2578 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2579 throw new RestException(403);
2580 }
2581
2582 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2583 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2584 }
2585
2586 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
2587 $result = $this->db->query($sql);
2588
2589 if ($result && $this->db->num_rows($result) == 0) {
2590 throw new RestException(404, "This thirdparty does not have $site account attached or does not exist.");
2591 } else {
2592 // If the user tries to edit the site member, we check first if
2593 if (isset($request_data['site']) && $request_data['site'] !== $site) {
2594 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
2595 $result = $this->db->query($sql);
2596
2597 if ($result && $this->db->num_rows($result) !== 0) {
2598 throw new RestException(409, "You are trying to update this thirdparty Account for ".$site." to ".$request_data['site']." but another Account already exists for this thirdparty with this site key.");
2599 }
2600 }
2601
2602 $obj = $this->db->fetch_object($result);
2603 $account = new SocieteAccount($this->db);
2604 $account->fetch($obj->rowid);
2605
2606 foreach ($request_data as $field => $value) {
2607 if ($field === 'caller') {
2608 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
2609 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2610 continue;
2611 }
2612
2613 $account->$field = $this->_checkValForAPI($field, $value, $account);
2614 }
2615
2616 if ($account->update(DolibarrApiAccess::$user) < 0) {
2617 throw new RestException(500, 'Error updating SocieteAccount account');
2618 }
2619
2620 $this->_cleanObjectDatas($account);
2621
2622 return $account;
2623 }
2624 }
2625
2644 public function deleteSocieteAccount($id, $site)
2645 {
2646 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2647 throw new RestException(403);
2648 }
2649
2650 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2651 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2652 }
2653
2654 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
2655 $result = $this->db->query($sql);
2656
2657 if ($result && $this->db->num_rows($result) == 0) {
2658 throw new RestException(404);
2659 } else {
2660 $obj = $this->db->fetch_object($result);
2661 $account = new SocieteAccount($this->db);
2662 $account->fetch($obj->rowid);
2663
2664 if ($account->delete(DolibarrApiAccess::$user) < 0) {
2665 throw new RestException(500, "Error while deleting $site account attached to this third party");
2666 }
2667 }
2668 }
2669
2686 {
2687 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2688 throw new RestException(403);
2689 }
2690
2691 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
2692 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2693 }
2694
2699 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms";
2700 $sql .= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id);
2701
2702 $result = $this->db->query($sql);
2703
2704 if ($result && $this->db->num_rows($result) == 0) {
2705 throw new RestException(404, 'This third party does not have any account attached or does not exist.');
2706 } else {
2707 $i = 0;
2708
2709 $i = 0;
2710 $num = $this->db->num_rows($result);
2711 //$min = min($num, ($limit <= 0 ? $num : $limit));
2712 $min = $num;
2713 while ($i < $min) {
2714 $obj = $this->db->fetch_object($result);
2715 $account = new SocieteAccount($this->db);
2716 $account->fetch($obj->rowid);
2717
2718 if ($account->delete(DolibarrApiAccess::$user) < 0) {
2719 throw new RestException(500, 'Error while deleting account attached to this third party');
2720 }
2721 $i++;
2722 }
2723 }
2724 }
2725
2726 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2736 protected function _cleanObjectDatas($object)
2737 {
2738 // phpcs:enable
2739 $object = parent::_cleanObjectDatas($object);
2740
2741 unset($object->nom); // ->name already defined and nom deprecated
2742 unset($object->name_bis); // ->name_alias already defined
2743 unset($object->note); // ->note_private and note_public already defined
2744 unset($object->departement);
2745 unset($object->departement_code);
2746 unset($object->pays);
2747 unset($object->particulier);
2748 unset($object->prefix_comm);
2749
2750 unset($object->siren);
2751 unset($object->siret);
2752 unset($object->ape);
2753
2754 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.
2755
2756 unset($object->total_ht);
2757 unset($object->total_tva);
2758 unset($object->total_localtax1);
2759 unset($object->total_localtax2);
2760 unset($object->total_ttc);
2761
2762 unset($object->lines);
2763 unset($object->thirdparty);
2764
2765 unset($object->fk_delivery_address); // deprecated feature
2766
2767 return $object;
2768 }
2769
2778 private function _validate($data)
2779 {
2780 if ($data === null) {
2781 $data = array();
2782 }
2783 $thirdparty = array();
2784 foreach (Thirdparties::$FIELDS as $field) {
2785 if (!isset($data[$field])) {
2786 throw new RestException(400, "$field field missing");
2787 }
2788 $thirdparty[$field] = $data[$field];
2789 }
2790 return $thirdparty;
2791 }
2792
2816 private function _fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
2817 {
2818 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
2819 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on thirdparties.');
2820 }
2821
2822 if ($rowid === 0) {
2823 $result = $this->company->initAsSpecimen();
2824 } else {
2825 $result = $this->company->fetch((int) $rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
2826 }
2827 if (!$result) {
2828 throw new RestException(404, 'Thirdparty not found');
2829 }
2830
2831 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
2832 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.' on this thirdparty');
2833 }
2834 if (isModEnabled('mailing')) {
2835 $this->company->getNoEmail();
2836 }
2837
2838 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
2839 $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
2840 $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
2841 } else {
2842 $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
2843 $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
2844 }
2845
2846 $absolute_discount = $this->company->getAvailableDiscounts(null, $filterabsolutediscount);
2847 $absolute_creditnote = $this->company->getAvailableDiscounts(null, $filtercreditnote);
2848 $this->company->absolute_discount = price2num($absolute_discount, 'MT');
2849 $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
2850
2851 return $this->_cleanObjectDatas($this->company);
2852 }
2853}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage withdrawal receipts.
Class to manage categories.
Class to manage bank accounts description of third parties.
Class to manage absolute discounts.
Class for API REST v1.
Definition api.class.php:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
Class to manage invoices.
Class to manage the table of subscription to notifications.
Class for SocieteAccount.
Class to manage third parties objects (customers, suppliers, prospects...)
updateCompanyNotification($id, $notification_id, $request_data=null)
Update a company notification for a third party.
setThirdpartyPriceLevel($id, $priceLevel)
Set a new price level for the given third party.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
getSocieteByAccounts($site, $key_account)
Get a specific third party by account.
getSupplierCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get supplier categories for a third party.
deleteCompanyNotification($id, $notification_id)
Delete a company notification attached to a third party.
getSocieteAccounts($id, $site=null)
Get a specific account attached to a third party.
getOutStandingOrder($id, $mode='customer')
Get outstanding orders for a third party.
addRepresentative($id, $representative_id)
Add a customer representative to a third party.
getByBarcode($barcode)
Get a third party by barcode.
generateBankAccountDocument($id, $companybankid=null, $model='sepamandate')
Generate a document from a bank account record.
createCompanyNotificationByCode($id, $code, $request_data=null)
Create a company notification for a third party using action trigger code.
getCompanyNotification($id)
Get company notifications for a third party.
addCategory($id, $category_id)
Add a customer category to a third party.
getCompanyBankAccount($id)
Get company bank accounts of a third party.
getInvoicesQualifiedForReplacement($id)
Return invoices qualified to be replaced by another invoice.
post($request_data=null)
Create a third party.
put($id, $request_data=null)
Update third party.
getByEmail($email)
Get properties of a third party by email.
_validate($data)
Validate fields before create or update object.
getFixedAmountDiscounts($id, $mode='customer', $filter="none", $sortfield="f.type", $sortorder='ASC')
Get fixed amount discount of a third party.
addSupplierCategory($id, $category_id)
Add a supplier category to a third party.
merge($id, $idtodelete)
Merge a third party into another third party.
deleteSocieteAccounts($id)
Delete all accounts attached to a third party.
__construct()
Constructor.
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get customer categories for a third party.
postSocieteAccount($id, $site, $request_data=null)
Create and attach a new (or replace an existing) specific site account for a third party.
deleteSupplierCategory($id, $category_id)
Remove the link between a category and the third party.
createFixedAmountDiscount($id, $request_data=null)
Create a fixed amount discount for a thirdparty.
deleteRepresentative($id, $representative_id)
Remove the link between a customer representative and a third party.
createCompanyNotification($id, $request_data=null)
Create a company notification for a third party.
putSocieteAccount($id, $site, $request_data=null)
Update specified values of a specific account attached to a third party.
updateCompanyBankAccount($id, $bankaccount_id, $request_data=null)
Update a company bank account of a third party.
deleteSocieteAccount($id, $site)
Delete a specific site account attached to a third party.
getInvoicesQualifiedForCreditNote($id)
Return invoices qualified to be corrected by a credit note.
getOutStandingProposals($id, $mode='customer')
Get outstanding proposals for a third party.
_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 a third party.
getOutStandingInvoices($id, $mode='customer')
Get outstanding invoices for a third party.
splitdiscount($id, $discountid, $amount_ttc_1, $amount_ttc_2)
Split a discount in 2 smaller discount.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $mode=0, $category=0, $sqlfilters='', $properties='', $pagination_data=false)
List third parties.
deleteCompanyBankAccount($id, $bankaccount_id)
Delete a bank account attached to a third party.
createSocieteAccount($id, $request_data=null)
Create and attach a new account to an existing third party.
createCompanyBankAccount($id, $request_data=null)
Create a company bank account for a third party.
deleteCategory($id, $category_id)
Remove the link between a customer category and the third party.
Class to manage translations.
Class to manage Dolibarr users.
dol_now($mode='gmt')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.