dolibarr 21.0.4
api_thirdparties.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2018 Pierre Chéné <pierre.chene44@gmail.com>
4 * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com>
5 * Copyright (C) 2020-2024 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2023 Alexandre Janniaux <alexandre.janniaux@gmail.com>
7 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024 Jon Bendtsen <jon.bendtsen.github@jonb.dk>
9 * Copyright (C) 2026 Benjamin Falière <benjamin@faliere.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
25use Luracast\Restler\RestException;
26
35{
40 public static $FIELDS = array(
41 'name'
42 );
43
47 public $company;
48
52 public function __construct()
53 {
54 global $db;
55 $this->db = $db;
56
57 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
58 require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
59 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
60 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
61 require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
62
63 $this->company = new Societe($this->db);
64
65 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY')) {
66 static::$FIELDS[] = 'email';
67 }
68 }
69
80 public function get($id)
81 {
82 return $this->_fetch($id);
83 }
84
97 public function getByEmail($email)
98 {
99 return $this->_fetch(null, '', '', '', '', '', '', '', '', '', $email);
100 }
101
114 public function getByBarcode($barcode)
115 {
116 return $this->_fetch(null, '', '', $barcode);
117 }
118
138 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
139 {
140 $obj_ret = array();
141
142 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
143 throw new RestException(403);
144 }
145
146 // case of external user, we force socids
147 $socids = DolibarrApiAccess::$user->socid ? (string) DolibarrApiAccess::$user->socid : '';
148
149 // If the internal user must only see his customers, force searching by him
150 $search_sale = 0;
151 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
152 $search_sale = DolibarrApiAccess::$user->id;
153 }
154
155 $sql = "SELECT t.rowid";
156 $sql .= " FROM ".MAIN_DB_PREFIX."societe as t";
157 $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
158 if ($category > 0) {
159 if ($mode != 4) {
160 $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c";
161 }
162 if (!in_array($mode, array(1, 2, 3))) {
163 $sql .= ", ".MAIN_DB_PREFIX."categorie_fournisseur as cc";
164 }
165 }
166 $sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st";
167 $sql .= " WHERE t.entity IN (".getEntity('societe').")";
168 $sql .= " AND t.fk_stcomm = st.id";
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 // Select thirdparties of given category
179 if ($category > 0) {
180 if (!empty($mode) && $mode != 4) {
181 $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid";
182 } elseif (!empty($mode) && $mode == 4) {
183 $sql .= " AND cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid";
184 } else {
185 $sql .= " AND ((c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid) OR (cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid))";
186 }
187 }
188 if ($socids) {
189 $sql .= " AND t.rowid IN (".$this->db->sanitize($socids).")";
190 }
191 // Search on sale representative
192 if ($search_sale && $search_sale != '-1') {
193 if ($search_sale == -2) {
194 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.rowid)";
195 } elseif ($search_sale > 0) {
196 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.rowid AND sc.fk_user = ".((int) $search_sale).")";
197 }
198 }
199 // Add sql filters
200 if ($sqlfilters) {
201 $errormessage = '';
202 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
203 if ($errormessage) {
204 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
205 }
206 }
207
208 //this query will return total thirdparties with the filters given
209 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
210
211 $sql .= $this->db->order($sortfield, $sortorder);
212 if ($limit) {
213 if ($page < 0) {
214 $page = 0;
215 }
216 $offset = $limit * $page;
217
218 $sql .= $this->db->plimit($limit + 1, $offset);
219 }
220
221 $result = $this->db->query($sql);
222 if ($result) {
223 $num = $this->db->num_rows($result);
224 $min = min($num, ($limit <= 0 ? $num : $limit));
225 $i = 0;
226 while ($i < $min) {
227 $obj = $this->db->fetch_object($result);
228 $soc_static = new Societe($this->db);
229 if ($soc_static->fetch($obj->rowid)) {
230 if (isModEnabled('mailing')) {
231 $soc_static->getNoEmail();
232 }
233 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($soc_static), $properties);
234 }
235 $i++;
236 }
237 } else {
238 throw new RestException(503, 'Error when retrieve thirdparties : '.$this->db->lasterror());
239 }
240 if (!count($obj_ret)) {
241 throw new RestException(404, 'Thirdparties not found');
242 }
243
244 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
245 if ($pagination_data) {
246 $totalsResult = $this->db->query($sqlTotals);
247 $total = $this->db->fetch_object($totalsResult)->total;
248
249 $tmp = $obj_ret;
250 $obj_ret = [];
251
252 $obj_ret['data'] = $tmp;
253 $obj_ret['pagination'] = [
254 'total' => (int) $total,
255 'page' => $page, //count starts from 0
256 'page_count' => ceil((int) $total / $limit),
257 'limit' => $limit
258 ];
259 }
260
261 return $obj_ret;
262 }
263
270 public function post($request_data = null)
271 {
272 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
273 throw new RestException(403);
274 }
275 // Check mandatory fields
276 $result = $this->_validate($request_data);
277
278 foreach ($request_data as $field => $value) {
279 if ($field === 'caller') {
280 // 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
281 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
282 continue;
283 }
284
285 $this->company->$field = $this->_checkValForAPI($field, $value, $this->company);
286 }
287
288 if ($this->company->create(DolibarrApiAccess::$user) < 0) {
289 throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors));
290 }
291 if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
292 $this->company->setNoEmail($this->company->no_email);
293 }
294
295 return $this->company->id;
296 }
297
309 public function put($id, $request_data = null)
310 {
311 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
312 throw new RestException(403);
313 }
314
315 $result = $this->company->fetch($id);
316 if (!$result) {
317 throw new RestException(404, 'Thirdparty not found');
318 }
319
320 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
321 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
322 }
323
324 foreach ($request_data as $field => $value) {
325 if ($field == 'id') {
326 continue;
327 }
328 if ($field === 'caller') {
329 // 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
330 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
331 continue;
332 }
333 if ($field == 'array_options' && is_array($value)) {
334 foreach ($value as $index => $val) {
335 $this->company->array_options[$index] = $this->_checkValForAPI($field, $val, $this->company);
336 }
337 continue;
338 }
339 $this->company->$field = $this->_checkValForAPI($field, $value, $this->company);
340 }
341
342 if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
343 $this->company->setNoEmail($this->company->no_email);
344 }
345
346 if ($this->company->update($id, DolibarrApiAccess::$user, 1, 1, 1, 'update', 1) > 0) {
347 return $this->get($id);
348 } else {
349 throw new RestException(500, $this->company->error);
350 }
351 }
352
367 public function merge($id, $idtodelete)
368 {
369 if ($id == $idtodelete) {
370 throw new RestException(400, 'Try to merge a thirdparty into itself');
371 }
372
373 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
374 throw new RestException(403);
375 }
376
377 $result = $this->company->fetch($id); // include the fetch of extra fields
378 if (!$result) {
379 throw new RestException(404, 'Thirdparty not found');
380 }
381
382 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
383 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
384 }
385
386 $companytoremove = new Societe($this->db);
387 $result = $companytoremove->fetch($idtodelete); // include the fetch of extra fields
388 if (!$result) {
389 throw new RestException(404, 'Thirdparty not found');
390 }
391
392 if (!DolibarrApi::_checkAccessToResource('societe', $companytoremove->id)) {
393 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
394 }
395
396 $user = DolibarrApiAccess::$user;
397 $result = $this->company->mergeCompany($companytoremove->id);
398 if ($result < 0) {
399 throw new RestException(500, 'Error failed to merged thirdparty '.$companytoremove->id.' into '.$id.'. Enable and read log file for more information.');
400 }
401
402 return $this->get($id);
403 }
404
411 public function delete($id)
412 {
413 if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
414 throw new RestException(403);
415 }
416 $result = $this->company->fetch($id);
417 if (!$result) {
418 throw new RestException(404, 'Thirdparty not found');
419 }
420 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
421 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
422 }
423 $this->company->oldcopy = clone $this->company;
424
425 $res = $this->company->delete($id);
426 if ($res < 0) {
427 throw new RestException(500, "Can't delete, error occurs");
428 } elseif ($res == 0) {
429 throw new RestException(409, "Can't delete, that product is probably used");
430 }
431
432 return array(
433 'success' => array(
434 'code' => 200,
435 'message' => 'Object deleted'
436 )
437 );
438 }
439
455 public function setThirdpartyPriceLevel($id, $priceLevel)
456 {
457 global $conf;
458
459 if (!isModEnabled('societe')) {
460 throw new RestException(501, 'Module "Thirdparties" needed for this request');
461 }
462
463 if (!isModEnabled("product")) {
464 throw new RestException(501, 'Module "Products" needed for this request');
465 }
466
467 if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
468 throw new RestException(501, 'Multiprices features activation needed for this request');
469 }
470
471 if ($priceLevel < 1 || $priceLevel > getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT')) {
472 throw new RestException(400, 'Price level must be between 1 and ' . getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT'));
473 }
474
475 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
476 throw new RestException(403, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
477 }
478
479 $result = $this->company->fetch($id);
480 if ($result < 0) {
481 throw new RestException(404, 'Thirdparty '.$id.' not found');
482 }
483
484 if (empty($result)) {
485 throw new RestException(500, 'Error fetching thirdparty '.$id, array_merge(array($this->company->error), $this->company->errors));
486 }
487
488 if (empty(DolibarrApi::_checkAccessToResource('societe', $this->company->id))) {
489 throw new RestException(403, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
490 }
491
492 $result = $this->company->setPriceLevel($priceLevel, DolibarrApiAccess::$user);
493 if ($result <= 0) {
494 throw new RestException(500, 'Error setting new price level for thirdparty '.$id, array($this->company->db->lasterror()));
495 }
496
497 return $this->_cleanObjectDatas($this->company);
498 }
499
512 public function addRepresentative($id, $representative_id)
513 {
514 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
515 throw new RestException(403);
516 }
517 $result = $this->company->fetch($id);
518 if (!$result) {
519 throw new RestException(404, 'Thirdparty not found');
520 }
521 $usertmp = new User($this->db);
522 $result = $usertmp->fetch($representative_id);
523 if (!$result) {
524 throw new RestException(404, 'User not found');
525 }
526 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
527 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
528 }
529 $result = $this->company->add_commercial(DolibarrApiAccess::$user, $representative_id);
530
531 return $result;
532 }
533
546 public function deleteRepresentative($id, $representative_id)
547 {
548 if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
549 throw new RestException(403);
550 }
551 $result = $this->company->fetch($id);
552 if (!$result) {
553 throw new RestException(404, 'Thirdparty not found');
554 }
555 $usertmp = new User($this->db);
556 $result = $usertmp->fetch($representative_id);
557 if (!$result) {
558 throw new RestException(404, 'User not found');
559 }
560 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
561 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
562 }
563 $result = $this->company->del_commercial(DolibarrApiAccess::$user, $representative_id);
564
565 return $result;
566 }
567
580 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
581 {
582 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
583 throw new RestException(403);
584 }
585
586 $result = $this->company->fetch($id);
587 if (!$result) {
588 throw new RestException(404, 'Thirdparty not found');
589 }
590
591 $categories = new Categorie($this->db);
592
593 $arrayofcateg = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page);
594
595 if (is_numeric($arrayofcateg) && $arrayofcateg < 0) {
596 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
597 }
598
599 if (is_numeric($arrayofcateg) && $arrayofcateg >= 0) { // To fix a return of 0 instead of empty array of method getListForItem
600 return array();
601 }
602
603 return $arrayofcateg;
604 }
605
615 public function addCategory($id, $category_id)
616 {
617 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
618 throw new RestException(403);
619 }
620
621 $result = $this->company->fetch($id);
622 if (!$result) {
623 throw new RestException(404, 'Thirdparty not found');
624 }
625 $category = new Categorie($this->db);
626 $result = $category->fetch($category_id);
627 if (!$result) {
628 throw new RestException(404, 'category not found');
629 }
630
631 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
632 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
633 }
634 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
635 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
636 }
637
638 $category->add_type($this->company, 'customer');
639
640 return $this->_cleanObjectDatas($this->company);
641 }
642
653 public function deleteCategory($id, $category_id)
654 {
655 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
656 throw new RestException(403);
657 }
658
659 $result = $this->company->fetch($id);
660 if (!$result) {
661 throw new RestException(404, 'Thirdparty not found');
662 }
663 $category = new Categorie($this->db);
664 $result = $category->fetch($category_id);
665 if (!$result) {
666 throw new RestException(404, 'category not found');
667 }
668
669 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
670 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
671 }
672 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
673 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
674 }
675
676 $category->del_type($this->company, 'customer');
677
678 return $this->_cleanObjectDatas($this->company);
679 }
680
694 public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
695 {
696 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
697 throw new RestException(403);
698 }
699
700 $result = $this->company->fetch($id);
701 if (!$result) {
702 throw new RestException(404, 'Thirdparty not found');
703 }
704
705 $categories = new Categorie($this->db);
706
707 $result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page);
708
709 if (is_numeric($result) && $result < 0) {
710 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
711 }
712
713 if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
714 return array();
715 }
716
717 return $result;
718 }
719
730 public function addSupplierCategory($id, $category_id)
731 {
732 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
733 throw new RestException(403);
734 }
735
736 $result = $this->company->fetch($id);
737 if (!$result) {
738 throw new RestException(404, 'Thirdparty not found');
739 }
740 $category = new Categorie($this->db);
741 $result = $category->fetch($category_id);
742 if (!$result) {
743 throw new RestException(404, 'category not found');
744 }
745
746 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
747 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
748 }
749 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
750 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
751 }
752
753 $category->add_type($this->company, 'supplier');
754
755 return $this->_cleanObjectDatas($this->company);
756 }
757
768 public function deleteSupplierCategory($id, $category_id)
769 {
770 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
771 throw new RestException(403);
772 }
773
774 $result = $this->company->fetch($id);
775 if (!$result) {
776 throw new RestException(404, 'Thirdparty not found');
777 }
778 $category = new Categorie($this->db);
779 $result = $category->fetch($category_id);
780 if (!$result) {
781 throw new RestException(404, 'category not found');
782 }
783
784 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
785 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
786 }
787 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
788 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
789 }
790
791 $category->del_type($this->company, 'supplier');
792
793 return $this->_cleanObjectDatas($this->company);
794 }
795
796
811 public function getOutStandingProposals($id, $mode = 'customer')
812 {
813 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
814 throw new RestException(403);
815 }
816
817 if (empty($id)) {
818 throw new RestException(400, 'Thirdparty ID is mandatory');
819 }
820
821 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
822 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
823 }
824
825 $result = $this->company->fetch($id);
826 if (!$result) {
827 throw new RestException(404, 'Thirdparty not found');
828 }
829
830 $result = $this->company->getOutstandingProposals($mode);
831
832 unset($result['total_ht']);
833 unset($result['total_ttc']);
834
835 return $result;
836 }
837
838
853 public function getOutStandingOrder($id, $mode = 'customer')
854 {
855 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
856 throw new RestException(403);
857 }
858
859 if (empty($id)) {
860 throw new RestException(400, 'Thirdparty ID is mandatory');
861 }
862
863 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
864 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
865 }
866
867 $result = $this->company->fetch($id);
868 if (!$result) {
869 throw new RestException(404, 'Thirdparty not found');
870 }
871
872 $result = $this->company->getOutstandingOrders($mode);
873
874 unset($result['total_ht']);
875 unset($result['total_ttc']);
876
877 return $result;
878 }
879
894 public function getOutStandingInvoices($id, $mode = 'customer')
895 {
896 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
897 throw new RestException(403);
898 }
899
900 if (empty($id)) {
901 throw new RestException(400, 'Thirdparty ID is mandatory');
902 }
903
904 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
905 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
906 }
907
908 $result = $this->company->fetch($id);
909 if (!$result) {
910 throw new RestException(404, 'Thirdparty not found');
911 }
912
913 $result = $this->company->getOutstandingBills($mode);
914
915 unset($result['total_ht']);
916 unset($result['total_ttc']);
917
918 return $result;
919 }
920
935 public function getSalesRepresentatives($id, $mode = 0)
936 {
937 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
938 throw new RestException(403);
939 }
940
941 if (empty($id)) {
942 throw new RestException(400, 'Thirdparty ID is mandatory');
943 }
944
945 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
946 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
947 }
948
949 $result = $this->company->fetch($id);
950 if (!$result) {
951 throw new RestException(404, 'Thirdparty not found');
952 }
953
954 $result = $this->company->getSalesRepresentatives(DolibarrApiAccess::$user, $mode);
955
956 return $result;
957 }
958
976 public function getFixedAmountDiscounts($id, $filter = "none", $sortfield = "f.type", $sortorder = 'ASC')
977 {
978 $obj_ret = array();
979
980 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
981 throw new RestException(403);
982 }
983
984 if (empty($id)) {
985 throw new RestException(400, 'Thirdparty ID is mandatory');
986 }
987
988 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
989 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
990 }
991
992 $result = $this->company->fetch($id);
993 if (!$result) {
994 throw new RestException(404, 'Thirdparty not found');
995 }
996
997
998 $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";
999 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1000 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = re.fk_facture_source";
1001 $sql .= " WHERE re.fk_soc = ".((int) $id);
1002 if ($filter == "available") {
1003 $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL";
1004 }
1005 if ($filter == "used") {
1006 $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)";
1007 }
1008
1009 $sql .= $this->db->order($sortfield, $sortorder);
1010
1011 $result = $this->db->query($sql);
1012 if (!$result) {
1013 throw new RestException(503, $this->db->lasterror());
1014 } else {
1015 $num = $this->db->num_rows($result);
1016 while ($obj = $this->db->fetch_object($result)) {
1017 $obj_ret[] = $obj;
1018 }
1019 }
1020
1021 return $obj_ret;
1022 }
1023
1024
1025
1040 {
1041 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1042 throw new RestException(403);
1043 }
1044 if (empty($id)) {
1045 throw new RestException(400, 'Thirdparty ID is mandatory');
1046 }
1047
1048 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1049 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1050 }
1051
1052 /*$result = $this->thirdparty->fetch($id);
1053 if( ! $result ) {
1054 throw new RestException(404, 'Thirdparty not found');
1055 }*/
1056
1057 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1058 $invoice = new Facture($this->db);
1059 $result = $invoice->list_replacable_invoices($id);
1060 if ($result < 0) {
1061 throw new RestException(405, $invoice->error);
1062 }
1063
1064 return $result;
1065 }
1066
1084 {
1085 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1086 throw new RestException(403);
1087 }
1088 if (empty($id)) {
1089 throw new RestException(400, 'Thirdparty ID is mandatory');
1090 }
1091
1092 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1093 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1094 }
1095
1096 /*$result = $this->thirdparty->fetch($id);
1097 if( ! $result ) {
1098 throw new RestException(404, 'Thirdparty not found');
1099 }*/
1100
1101 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1102 $invoice = new Facture($this->db);
1103 $result = $invoice->list_qualified_avoir_invoices($id);
1104 if ($result < 0) {
1105 throw new RestException(405, $invoice->error);
1106 }
1107
1108 return $result;
1109 }
1110
1121 {
1122 if (empty($id)) {
1123 throw new RestException(400, 'Thirdparty ID is mandatory');
1124 }
1125 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1126 throw new RestException(403);
1127 }
1128 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1129 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1130 }
1131
1136 $sql = "SELECT rowid as id, fk_action as event, fk_soc as socid, fk_contact as contact_id, type, datec, tms";
1137 $sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1138 if ($id) {
1139 $sql .= " WHERE fk_soc = ".((int) $id);
1140 }
1141
1142 $result = $this->db->query($sql);
1143 if ($this->db->num_rows($result) == 0) {
1144 throw new RestException(404, 'Notification not found');
1145 }
1146
1147 $i = 0;
1148
1149 $notifications = array();
1150
1151 if ($result) {
1152 $num = $this->db->num_rows($result);
1153 while ($i < $num) {
1154 $obj = $this->db->fetch_object($result);
1155 $notifications[] = $obj;
1156 $i++;
1157 }
1158 } else {
1159 throw new RestException(404, 'No notifications found');
1160 }
1161
1162 $fields = array('id', 'socid', 'event', 'contact_id', 'datec', 'tms', 'type');
1163
1164 $returnNotifications = array();
1165
1166 foreach ($notifications as $notification) {
1167 $object = array();
1168 foreach ($notification as $key => $value) {
1169 if (in_array($key, $fields)) {
1170 $object[$key] = $value;
1171 }
1172 }
1173 $returnNotifications[] = $object;
1174 }
1175
1176 return $returnNotifications;
1177 }
1178
1188 public function createCompanyNotification($id, $request_data = null)
1189 {
1190 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1191 throw new RestException(403, "User has no right to update thirdparties");
1192 }
1193 if ($this->company->fetch($id) <= 0) {
1194 throw new RestException(404, 'Error creating Thirdparty Notification, Thirdparty doesn\'t exists');
1195 }
1196 $notification = new Notify($this->db);
1197
1198 $notification->socid = $id;
1199
1200 foreach ($request_data as $field => $value) {
1201 $notification->$field = $value;
1202 }
1203
1204 $event = $notification->event;
1205 if (!$event) {
1206 throw new RestException(500, 'Error creating Thirdparty Notification, request_data missing event');
1207 }
1208 $socid = $notification->socid;
1209 $contact_id = $notification->contact_id;
1210
1211 $exists_sql = "SELECT rowid, fk_action as event, fk_soc as socid, fk_contact as contact_id, type, datec, tms as datem";
1212 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1213 $exists_sql .= " WHERE fk_action = '".$this->db->escape($event)."'";
1214 $exists_sql .= " AND fk_soc = '".$this->db->escape($socid)."'";
1215 $exists_sql .= " AND fk_contact = '".$this->db->escape($contact_id)."'";
1216
1217 $exists_result = $this->db->query($exists_sql);
1218 if ($this->db->num_rows($exists_result) > 0) {
1219 throw new RestException(403, 'Notification already exists');
1220 }
1221
1222 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1223 throw new RestException(500, 'Error creating Thirdparty Notification');
1224 }
1225
1226 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1227 throw new RestException(500, 'Error updating values');
1228 }
1229
1230 return $this->_cleanObjectDatas($notification);
1231 }
1232
1244 public function createCompanyNotificationByCode($id, $code, $request_data = null)
1245 {
1246 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1247 throw new RestException(403, "User has no right to update thirdparties");
1248 }
1249 if ($this->company->fetch($id) <= 0) {
1250 throw new RestException(404, 'Error creating Thirdparty Notification, Thirdparty doesn\'t exists');
1251 }
1252 $notification = new Notify($this->db);
1253 $notification->socid = $id;
1254
1255 $sql = "SELECT t.rowid as id FROM ".MAIN_DB_PREFIX."c_action_trigger as t";
1256 $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
1257
1258 $result = $this->db->query($sql);
1259 if ($this->db->num_rows($result) == 0) {
1260 throw new RestException(404, 'Action Trigger code not found');
1261 }
1262
1263 $notification->event = $this->db->fetch_row($result)[0];
1264 foreach ($request_data as $field => $value) {
1265 if ($field === 'event') {
1266 throw new RestException(500, 'Error creating Thirdparty Notification, request_data contains event key');
1267 }
1268 if ($field === 'fk_action') {
1269 throw new RestException(500, 'Error creating Thirdparty Notification, request_data contains fk_action key');
1270 }
1271 $notification->$field = $value;
1272 }
1273
1274 $event = $notification->event;
1275 $socid = $notification->socid;
1276 $contact_id = $notification->contact_id;
1277
1278 $exists_sql = "SELECT rowid, fk_action as event, fk_soc as socid, fk_contact as contact_id, type, datec, tms as datem";
1279 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1280 $exists_sql .= " WHERE fk_action = '".$this->db->escape($event)."'";
1281 $exists_sql .= " AND fk_soc = '".$this->db->escape($socid)."'";
1282 $exists_sql .= " AND fk_contact = '".$this->db->escape($contact_id)."'";
1283
1284 $exists_result = $this->db->query($exists_sql);
1285 if ($this->db->num_rows($exists_result) > 0) {
1286 throw new RestException(403, 'Notification already exists');
1287 }
1288
1289 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1290 throw new RestException(500, 'Error creating Thirdparty Notification, are request_data well formed?');
1291 }
1292
1293 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1294 throw new RestException(500, 'Error updating values');
1295 }
1296
1297 return $this->_cleanObjectDatas($notification);
1298 }
1299
1310 public function deleteCompanyNotification($id, $notification_id)
1311 {
1312 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1313 throw new RestException(403);
1314 }
1315
1316 $notification = new Notify($this->db);
1317
1318 $notification->fetch($notification_id);
1319
1320 $socid = (int) $notification->socid;
1321
1322 if ($socid == $id) {
1323 return $notification->delete(DolibarrApiAccess::$user);
1324 } else {
1325 throw new RestException(403, "Not allowed due to bad consistency of input data");
1326 }
1327 }
1328
1340 public function updateCompanyNotification($id, $notification_id, $request_data = null)
1341 {
1342 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1343 throw new RestException(403, "User has no right to update thirdparties");
1344 }
1345 if ($this->company->fetch($id) <= 0) {
1346 throw new RestException(404, 'Error creating Company Notification, Company doesn\'t exists');
1347 }
1348 $notification = new Notify($this->db);
1349
1350 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1351 $notification->fetch($notification_id, $id);
1352
1353 if ($notification->socid != $id) {
1354 throw new RestException(403, "Not allowed due to bad consistency of input data");
1355 }
1356
1357 foreach ($request_data as $field => $value) {
1358 $notification->$field = $value;
1359 }
1360
1361 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1362 throw new RestException(500, 'Error updating values');
1363 }
1364
1365 return $this->_cleanObjectDatas($notification);
1366 }
1367
1378 {
1379 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1380 throw new RestException(403);
1381 }
1382 if (empty($id)) {
1383 throw new RestException(400, 'Thirdparty ID is mandatory');
1384 }
1385
1386 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1387 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1388 }
1389
1394 $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation as address, proprio,";
1395 $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur";
1396 $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1397 if ($id) {
1398 $sql .= " WHERE fk_soc = ".((int) $id);
1399 }
1400
1401 $result = $this->db->query($sql);
1402
1403 if ($this->db->num_rows($result) == 0) {
1404 throw new RestException(404, 'Account not found');
1405 }
1406
1407 $i = 0;
1408
1409 $accounts = array();
1410
1411 if ($result) {
1412 $num = $this->db->num_rows($result);
1413 while ($i < $num) {
1414 $obj = $this->db->fetch_object($result);
1415
1416 $account = new CompanyBankAccount($this->db);
1417 if ($account->fetch($obj->rowid)) {
1418 $accounts[] = $account;
1419 }
1420 $i++;
1421 }
1422 } else {
1423 throw new RestException(404, 'Account not found');
1424 }
1425
1426
1427 $fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum');
1428
1429 $returnAccounts = array();
1430
1431 foreach ($accounts as $account) {
1432 $object = array();
1433 foreach ($account as $key => $value) {
1434 if (in_array($key, $fields)) {
1435 if ($key == 'iban') {
1436 $object[$key] = dolDecrypt($value);
1437 } else {
1438 $object[$key] = $value;
1439 }
1440 }
1441 }
1442 $returnAccounts[] = $object;
1443 }
1444
1445 return $returnAccounts;
1446 }
1447
1457 public function createCompanyBankAccount($id, $request_data = null)
1458 {
1459 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1460 throw new RestException(403);
1461 }
1462 if ($this->company->fetch($id) <= 0) {
1463 throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1464 }
1465 $account = new CompanyBankAccount($this->db);
1466
1467 $account->socid = $id;
1468
1469 foreach ($request_data as $field => $value) {
1470 if ($field === 'caller') {
1471 // 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
1472 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1473 continue;
1474 }
1475
1476 $account->$field = $this->_checkValForAPI('extrafields', $value, $account);
1477 }
1478
1479 if ($account->create(DolibarrApiAccess::$user) < 0) {
1480 throw new RestException(500, 'Error creating Company Bank account');
1481 }
1482
1483 if (empty($account->rum)) {
1484 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1485 $prelevement = new BonPrelevement($this->db);
1486 $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1487 $account->date_rum = dol_now();
1488 }
1489
1490 if ($account->update(DolibarrApiAccess::$user) < 0) {
1491 throw new RestException(500, 'Error updating values');
1492 }
1493
1494 return $this->_cleanObjectDatas($account);
1495 }
1496
1508 public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
1509 {
1510 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1511 throw new RestException(403);
1512 }
1513 if ($this->company->fetch($id) <= 0) {
1514 throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1515 }
1516 $account = new CompanyBankAccount($this->db);
1517
1518 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1519 $account->fetch($bankaccount_id, '', $id, -1, '');
1520
1521 if ($account->socid != $id) {
1522 throw new RestException(403);
1523 }
1524
1525
1526 foreach ($request_data as $field => $value) {
1527 if ($field === 'caller') {
1528 // 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
1529 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1530 continue;
1531 }
1532
1533 $account->$field = $this->_checkValForAPI($field, $value, $account);
1534 }
1535
1536 if (empty($account->rum)) {
1537 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1538 $prelevement = new BonPrelevement($this->db);
1539 $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1540 $account->date_rum = dol_now();
1541 }
1542
1543 if ($account->update(DolibarrApiAccess::$user) < 0) {
1544 throw new RestException(500, 'Error updating values');
1545 }
1546
1547 return $this->_cleanObjectDatas($account);
1548 }
1549
1560 public function deleteCompanyBankAccount($id, $bankaccount_id)
1561 {
1562 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1563 throw new RestException(403);
1564 }
1565
1566 $account = new CompanyBankAccount($this->db);
1567
1568 $account->fetch($bankaccount_id);
1569
1570 $socid = (int) $account->socid;
1571
1572 if ($socid == $id) {
1573 return $account->delete(DolibarrApiAccess::$user);
1574 } else {
1575 throw new RestException(403, "Not allowed due to bad consistency of input data");
1576 }
1577 }
1578
1589 public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
1590 {
1591 global $conf, $langs;
1592
1593 $langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals"));
1594
1595 if ($this->company->fetch($id) <= 0) {
1596 throw new RestException(404, 'Thirdparty not found');
1597 }
1598
1599 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1600 throw new RestException(403);
1601 }
1602
1603 $this->company->setDocModel(DolibarrApiAccess::$user, $model);
1604
1605 $this->company->fk_bank = $this->company->fk_account;
1606 // $this->company->fk_account = $this->company->fk_account;
1607
1608 $outputlangs = $langs;
1609 $newlang = '';
1610
1611 //if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
1612 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1613 if (isset($this->company->thirdparty->default_lang)) {
1614 $newlang = $this->company->thirdparty->default_lang; // for proposal, order, invoice, ...
1615 } elseif (isset($this->company->default_lang)) {
1616 $newlang = $this->company->default_lang; // for thirdparty
1617 }
1618 }
1619 if (!empty($newlang)) {
1620 $outputlangs = new Translate("", $conf);
1621 $outputlangs->setDefaultLang($newlang);
1622 }
1623
1624 $sql = "SELECT rowid";
1625 $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1626 if ($id) {
1627 $sql .= " WHERE fk_soc = ".((int) $id);
1628 }
1629 if ($companybankid) {
1630 $sql .= " AND rowid = ".((int) $companybankid);
1631 }
1632
1633 $i = 0;
1634 $accounts = array();
1635
1636 $result = $this->db->query($sql);
1637 if ($result) {
1638 if ($this->db->num_rows($result) == 0) {
1639 throw new RestException(404, 'Bank account not found');
1640 }
1641
1642 $num = $this->db->num_rows($result);
1643 while ($i < $num) {
1644 $obj = $this->db->fetch_object($result);
1645
1646 $account = new CompanyBankAccount($this->db);
1647 if ($account->fetch($obj->rowid)) {
1648 $accounts[] = $account;
1649 }
1650 $i++;
1651 }
1652 } else {
1653 throw new RestException(500, 'Sql error '.$this->db->lasterror());
1654 }
1655
1656 $moreparams = array(
1657 'use_companybankid' => $accounts[0]->id,
1658 'force_dir_output' => $conf->societe->multidir_output[$this->company->entity].'/'.dol_sanitizeFileName((string) $this->company->id)
1659 );
1660
1661 $result = $this->company->generateDocument($model, $outputlangs, 0, 0, 0, $moreparams);
1662
1663 if ($result > 0) {
1664 return array("success" => $result);
1665 } else {
1666 throw new RestException(500, 'Error generating the document '.$this->company->error);
1667 }
1668 }
1669
1682 public function getSocieteAccounts($id, $site = null)
1683 {
1684 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1685 throw new RestException(403);
1686 }
1687
1688 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1689 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1690 }
1691
1695 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
1696 $sql .= " WHERE fk_soc = ".((int) $id);
1697 if ($site) {
1698 $sql .= " AND site ='".$this->db->escape($site)."'";
1699 }
1700
1701 $result = $this->db->query($sql);
1702
1703 if ($result && $this->db->num_rows($result) == 0) {
1704 throw new RestException(404, 'This thirdparty does not have any account attached or does not exist.');
1705 }
1706
1707 $i = 0;
1708
1709 $accounts = array();
1710
1711 $num = $this->db->num_rows($result);
1712 while ($i < $num) {
1713 $obj = $this->db->fetch_object($result);
1714 $account = new SocieteAccount($this->db);
1715
1716 if ($account->fetch($obj->rowid)) {
1717 $accounts[] = $account;
1718 }
1719 $i++;
1720 }
1721
1722 $fields = array('id', 'fk_soc', 'key_account', 'site', 'date_creation', 'tms');
1723
1724 $returnAccounts = array();
1725
1726 foreach ($accounts as $account) {
1727 $object = array();
1728 foreach ($account as $key => $value) {
1729 if (in_array($key, $fields)) {
1730 $object[$key] = $value;
1731 }
1732 }
1733 $returnAccounts[] = $object;
1734 }
1735
1736 return $returnAccounts;
1737 }
1738
1751 public function getSocieteByAccounts($site, $key_account)
1752 {
1753 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1754 throw new RestException(403);
1755 }
1756
1757 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
1758 $sql .= " WHERE site = '".$this->db->escape($site)."' AND key_account = '".$this->db->escape($key_account)."'";
1759 $sql .= " AND entity IN (".getEntity('societe').")";
1760
1761 $result = $this->db->query($sql);
1762
1763 if ($result && $this->db->num_rows($result) == 1) {
1764 $obj = $this->db->fetch_object($result);
1765 $returnThirdparty = $this->_fetch($obj->fk_soc);
1766 } else {
1767 throw new RestException(404, 'This account have many thirdparties attached or does not exist.');
1768 }
1769
1770 if (!DolibarrApi::_checkAccessToResource('societe', $returnThirdparty->id)) {
1771 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1772 }
1773
1774 return $returnThirdparty;
1775 }
1776
1796 public function createSocieteAccount($id, $request_data = null)
1797 {
1798 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1799 throw new RestException(403);
1800 }
1801
1802 if (!isset($request_data['site'])) {
1803 throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !');
1804 }
1805
1806 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."'";
1807 $result = $this->db->query($sql);
1808
1809 if ($result && $this->db->num_rows($result) == 0) {
1810 $account = new SocieteAccount($this->db);
1811 if (!isset($request_data['login'])) {
1812 $account->login = "";
1813 }
1814 $account->fk_soc = $id;
1815
1816 foreach ($request_data as $field => $value) {
1817 if ($field === 'caller') {
1818 // 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
1819 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1820 continue;
1821 }
1822
1823 $account->$field = $this->_checkValForAPI($field, $value, $account);
1824 }
1825
1826 if ($account->create(DolibarrApiAccess::$user) < 0) {
1827 throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!');
1828 }
1829
1830 $this->_cleanObjectDatas($account);
1831
1832 return $account;
1833 } else {
1834 throw new RestException(409, 'A SocieteAccount entity already exists for this company and site.');
1835 }
1836 }
1837
1860 public function putSocieteAccount($id, $site, $request_data = null)
1861 {
1862 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1863 throw new RestException(403);
1864 }
1865
1866 $sql = "SELECT rowid, fk_user_creat, date_creation FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
1867 $result = $this->db->query($sql);
1868
1869 // We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one.
1870 if ($result && $this->db->num_rows($result) == 0) {
1871 if (!isset($request_data['key_account'])) {
1872 throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !');
1873 }
1874 $account = new SocieteAccount($this->db);
1875 if (!isset($request_data['login'])) {
1876 $account->login = "";
1877 }
1878
1879 foreach ($request_data as $field => $value) {
1880 if ($field === 'caller') {
1881 // 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
1882 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1883 continue;
1884 }
1885
1886 $account->$field = $this->_checkValForAPI($field, $value, $account);
1887 }
1888
1889 $account->fk_soc = $id;
1890 $account->site = $site;
1891
1892 if ($account->create(DolibarrApiAccess::$user) < 0) {
1893 throw new RestException(500, 'Error creating SocieteAccount entity.');
1894 }
1895 // We found an existing SocieteAccount entity, we are replacing it
1896 } else {
1897 if (isset($request_data['site']) && $request_data['site'] !== $site) {
1898 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
1899 $result = $this->db->query($sql);
1900
1901 if ($result && $this->db->num_rows($result) !== 0) {
1902 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.");
1903 }
1904 }
1905
1906 $obj = $this->db->fetch_object($result);
1907
1908 $account = new SocieteAccount($this->db);
1909 $account->id = $obj->rowid;
1910 $account->fk_soc = $id;
1911 $account->site = $site;
1912 if (!isset($request_data['login'])) {
1913 $account->login = "";
1914 }
1915 $account->fk_user_creat = $obj->fk_user_creat;
1916 $account->date_creation = $obj->date_creation;
1917
1918 foreach ($request_data as $field => $value) {
1919 if ($field === 'caller') {
1920 // 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
1921 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1922 continue;
1923 }
1924
1925 $account->$field = $this->_checkValForAPI($field, $value, $account);
1926 }
1927
1928 if ($account->update(DolibarrApiAccess::$user) < 0) {
1929 throw new RestException(500, 'Error updating SocieteAccount entity.');
1930 }
1931 }
1932
1933 $this->_cleanObjectDatas($account);
1934
1935 return $account;
1936 }
1937
1954 public function patchSocieteAccount($id, $site, $request_data = null)
1955 {
1956 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1957 throw new RestException(403);
1958 }
1959
1960 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
1961 $result = $this->db->query($sql);
1962
1963 if ($result && $this->db->num_rows($result) == 0) {
1964 throw new RestException(404, "This thirdparty does not have $site account attached or does not exist.");
1965 } else {
1966 // If the user tries to edit the site member, we check first if
1967 if (isset($request_data['site']) && $request_data['site'] !== $site) {
1968 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
1969 $result = $this->db->query($sql);
1970
1971 if ($result && $this->db->num_rows($result) !== 0) {
1972 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.");
1973 }
1974 }
1975
1976 $obj = $this->db->fetch_object($result);
1977 $account = new SocieteAccount($this->db);
1978 $account->fetch($obj->rowid);
1979
1980 foreach ($request_data as $field => $value) {
1981 if ($field === 'caller') {
1982 // 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
1983 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1984 continue;
1985 }
1986
1987 $account->$field = $this->_checkValForAPI($field, $value, $account);
1988 }
1989
1990 if ($account->update(DolibarrApiAccess::$user) < 0) {
1991 throw new RestException(500, 'Error updating SocieteAccount account');
1992 }
1993
1994 $this->_cleanObjectDatas($account);
1995
1996 return $account;
1997 }
1998 }
1999
2013 public function deleteSocieteAccount($id, $site)
2014 {
2015 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2016 throw new RestException(403);
2017 }
2018
2019 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
2020 $result = $this->db->query($sql);
2021
2022 if ($result && $this->db->num_rows($result) == 0) {
2023 throw new RestException(404);
2024 } else {
2025 $obj = $this->db->fetch_object($result);
2026 $account = new SocieteAccount($this->db);
2027 $account->fetch($obj->rowid);
2028
2029 if ($account->delete(DolibarrApiAccess::$user) < 0) {
2030 throw new RestException(500, "Error while deleting $site account attached to this third party");
2031 }
2032 }
2033 }
2034
2048 {
2049 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2050 throw new RestException(403);
2051 }
2052
2057 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms";
2058 $sql .= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id);
2059
2060 $result = $this->db->query($sql);
2061
2062 if ($result && $this->db->num_rows($result) == 0) {
2063 throw new RestException(404, 'This third party does not have any account attached or does not exist.');
2064 } else {
2065 $i = 0;
2066
2067 $num = $this->db->num_rows($result);
2068 while ($i < $num) {
2069 $obj = $this->db->fetch_object($result);
2070 $account = new SocieteAccount($this->db);
2071 $account->fetch($obj->rowid);
2072
2073 if ($account->delete(DolibarrApiAccess::$user) < 0) {
2074 throw new RestException(500, 'Error while deleting account attached to this third party');
2075 }
2076 $i++;
2077 }
2078 }
2079 }
2080
2081 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2088 protected function _cleanObjectDatas($object)
2089 {
2090 // phpcs:enable
2091 $object = parent::_cleanObjectDatas($object);
2092
2093 unset($object->nom); // ->name already defined and nom deprecated
2094 unset($object->name_bis); // ->name_alias already defined
2095 unset($object->note); // ->note_private and note_public already defined
2096 unset($object->departement);
2097 unset($object->departement_code);
2098 unset($object->pays);
2099 unset($object->particulier);
2100 unset($object->prefix_comm);
2101
2102 unset($object->siren);
2103 unset($object->siret);
2104 unset($object->ape);
2105
2106 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.
2107
2108 unset($object->total_ht);
2109 unset($object->total_tva);
2110 unset($object->total_localtax1);
2111 unset($object->total_localtax2);
2112 unset($object->total_ttc);
2113
2114 unset($object->lines);
2115 unset($object->thirdparty);
2116
2117 unset($object->fk_delivery_address); // deprecated feature
2118
2119 return $object;
2120 }
2121
2130 private function _validate($data)
2131 {
2132 $thirdparty = array();
2133 foreach (Thirdparties::$FIELDS as $field) {
2134 if (!isset($data[$field])) {
2135 throw new RestException(400, "$field field missing");
2136 }
2137 $thirdparty[$field] = $data[$field];
2138 }
2139 return $thirdparty;
2140 }
2141
2163 private function _fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
2164 {
2165 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
2166 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on thirdparties.');
2167 }
2168
2169 if ($rowid === 0) {
2170 $result = $this->company->initAsSpecimen();
2171 } else {
2172 $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
2173 }
2174 if (!$result) {
2175 throw new RestException(404, 'Thirdparty not found');
2176 }
2177
2178 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
2179 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.' on this thirdparty');
2180 }
2181 if (isModEnabled('mailing')) {
2182 $this->company->getNoEmail();
2183 }
2184
2185 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
2186 $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
2187 $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
2188 } else {
2189 $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
2190 $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
2191 }
2192
2193 $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount);
2194 $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote);
2195 $this->company->absolute_discount = price2num($absolute_discount, 'MT');
2196 $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
2197
2198 return $this->_cleanObjectDatas($this->company);
2199 }
2200}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
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
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:96
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 CompanyNotification object for thirdparty.
setThirdpartyPriceLevel($id, $priceLevel)
Set new price level for the given thirdparty.
_cleanObjectDatas($object)
Clean sensible object datas.
getSocieteByAccounts($site, $key_account)
Get a specific thirdparty by account.
getSupplierCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get supplier categories for a thirdparty.
deleteCompanyNotification($id, $notification_id)
Delete a CompanyNotification attached to a thirdparty.
getSocieteAccounts($id, $site=null)
Get a specific account attached to a thirdparty (by specifying the site key)
getOutStandingOrder($id, $mode='customer')
Get outstanding orders of thirdparty.
addRepresentative($id, $representative_id)
Add a customer representative to a 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)
createCompanyNotificationByCode($id, $code, $request_data=null)
Create CompanyNotification object for thirdparty using action trigger code.
getCompanyNotification($id)
Get CompanyNotification objects for thirdparty.
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 third party into another one.
deleteSocieteAccounts($id)
Delete all accounts attached to a thirdparty.
__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.
deleteRepresentative($id, $representative_id)
Delete a customer representative to a thirdparty.
createCompanyNotification($id, $request_data=null)
Create CompanyNotification object for thirdparty.
putSocieteAccount($id, $site, $request_data=null)
Create and attach a new (or replace an existing) specific site account to a thirdparty.
updateCompanyBankAccount($id, $bankaccount_id, $request_data=null)
Update CompanyBankAccount object for thirdparty.
deleteSocieteAccount($id, $site)
Delete a specific site account attached to a thirdparty (by account 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 account 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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $mode=0, $category=0, $sqlfilters='', $properties='', $pagination_data=false)
List thirdparties.
deleteCompanyBankAccount($id, $bankaccount_id)
Delete a bank account attached to a thirdparty.
createSocieteAccount($id, $request_data=null)
Create and attach a new account 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.
Class to manage Dolibarr users.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.