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