dolibarr 21.0.0-alpha
api_thirdparties.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2018 Pierre Chéné <pierre.chene44@gmail.com>
4 * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com>
5 * Copyright (C) 2020-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, '', '', '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 $account = new CompanyBankAccount($this->db);
1414 if ($account->fetch($obj->rowid)) {
1415 $accounts[] = $account;
1416 }
1417 $i++;
1418 }
1419 } else {
1420 throw new RestException(404, 'Account not found');
1421 }
1422
1423
1424 $fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum');
1425
1426 $returnAccounts = array();
1427
1428 foreach ($accounts as $account) {
1429 $object = array();
1430 foreach ($account as $key => $value) {
1431 if (in_array($key, $fields)) {
1432 if ($key == 'iban') {
1433 $object[$key] = dolDecrypt($value);
1434 } else {
1435 $object[$key] = $value;
1436 }
1437 }
1438 }
1439 $returnAccounts[] = $object;
1440 }
1441
1442 return $returnAccounts;
1443 }
1444
1454 public function createCompanyBankAccount($id, $request_data = null)
1455 {
1456 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1457 throw new RestException(403);
1458 }
1459 if ($this->company->fetch($id) <= 0) {
1460 throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1461 }
1462 $account = new CompanyBankAccount($this->db);
1463
1464 $account->socid = $id;
1465
1466 foreach ($request_data as $field => $value) {
1467 if ($field === 'caller') {
1468 // 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
1469 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1470 continue;
1471 }
1472
1473 $account->$field = $this->_checkValForAPI('extrafields', $value, $account);
1474 }
1475
1476 if ($account->create(DolibarrApiAccess::$user) < 0) {
1477 throw new RestException(500, 'Error creating Company Bank account');
1478 }
1479
1480 if (empty($account->rum)) {
1481 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1482 $prelevement = new BonPrelevement($this->db);
1483 $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1484 $account->date_rum = dol_now();
1485 }
1486
1487 if ($account->update(DolibarrApiAccess::$user) < 0) {
1488 throw new RestException(500, 'Error updating values');
1489 }
1490
1491 return $this->_cleanObjectDatas($account);
1492 }
1493
1505 public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
1506 {
1507 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1508 throw new RestException(403);
1509 }
1510 if ($this->company->fetch($id) <= 0) {
1511 throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1512 }
1513 $account = new CompanyBankAccount($this->db);
1514
1515 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1516 $account->fetch($bankaccount_id, '', $id, -1, '');
1517
1518 if ($account->socid != $id) {
1519 throw new RestException(403);
1520 }
1521
1522
1523 foreach ($request_data as $field => $value) {
1524 if ($field === 'caller') {
1525 // 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
1526 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1527 continue;
1528 }
1529
1530 $account->$field = $this->_checkValForAPI($field, $value, $account);
1531 }
1532
1533 if (empty($account->rum)) {
1534 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1535 $prelevement = new BonPrelevement($this->db);
1536 $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, $account->id);
1537 $account->date_rum = dol_now();
1538 }
1539
1540 if ($account->update(DolibarrApiAccess::$user) < 0) {
1541 throw new RestException(500, 'Error updating values');
1542 }
1543
1544 return $this->_cleanObjectDatas($account);
1545 }
1546
1557 public function deleteCompanyBankAccount($id, $bankaccount_id)
1558 {
1559 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1560 throw new RestException(403);
1561 }
1562
1563 $account = new CompanyBankAccount($this->db);
1564
1565 $account->fetch($bankaccount_id);
1566
1567 $socid = (int) $account->socid;
1568
1569 if ($socid == $id) {
1570 return $account->delete(DolibarrApiAccess::$user);
1571 } else {
1572 throw new RestException(403, "Not allowed due to bad consistency of input data");
1573 }
1574 }
1575
1586 public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
1587 {
1588 global $conf, $langs;
1589
1590 $langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals"));
1591
1592 if ($this->company->fetch($id) <= 0) {
1593 throw new RestException(404, 'Thirdparty not found');
1594 }
1595
1596 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1597 throw new RestException(403);
1598 }
1599
1600 $this->company->setDocModel(DolibarrApiAccess::$user, $model);
1601
1602 $this->company->fk_bank = $this->company->fk_account;
1603 // $this->company->fk_account = $this->company->fk_account;
1604
1605 $outputlangs = $langs;
1606 $newlang = '';
1607
1608 //if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
1609 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1610 if (isset($this->company->thirdparty->default_lang)) {
1611 $newlang = $this->company->thirdparty->default_lang; // for proposal, order, invoice, ...
1612 } elseif (isset($this->company->default_lang)) {
1613 $newlang = $this->company->default_lang; // for thirdparty
1614 }
1615 }
1616 if (!empty($newlang)) {
1617 $outputlangs = new Translate("", $conf);
1618 $outputlangs->setDefaultLang($newlang);
1619 }
1620
1621 $sql = "SELECT rowid";
1622 $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1623 if ($id) {
1624 $sql .= " WHERE fk_soc = ".((int) $id);
1625 }
1626 if ($companybankid) {
1627 $sql .= " AND rowid = ".((int) $companybankid);
1628 }
1629
1630 $i = 0;
1631 $accounts = array();
1632
1633 $result = $this->db->query($sql);
1634 if ($result) {
1635 if ($this->db->num_rows($result) == 0) {
1636 throw new RestException(404, 'Bank account not found');
1637 }
1638
1639 $num = $this->db->num_rows($result);
1640 while ($i < $num) {
1641 $obj = $this->db->fetch_object($result);
1642
1643 $account = new CompanyBankAccount($this->db);
1644 if ($account->fetch($obj->rowid)) {
1645 $accounts[] = $account;
1646 }
1647 $i++;
1648 }
1649 } else {
1650 throw new RestException(500, 'Sql error '.$this->db->lasterror());
1651 }
1652
1653 $moreparams = array(
1654 'use_companybankid' => $accounts[0]->id,
1655 'force_dir_output' => $conf->societe->multidir_output[$this->company->entity].'/'.dol_sanitizeFileName((string) $this->company->id)
1656 );
1657
1658 $result = $this->company->generateDocument($model, $outputlangs, 0, 0, 0, $moreparams);
1659
1660 if ($result > 0) {
1661 return array("success" => $result);
1662 } else {
1663 throw new RestException(500, 'Error generating the document '.$this->company->error);
1664 }
1665 }
1666
1679 public function getSocieteAccounts($id, $site = null)
1680 {
1681 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1682 throw new RestException(403);
1683 }
1684
1685 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1686 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1687 }
1688
1692 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
1693 $sql .= " WHERE fk_soc = ".((int) $id);
1694 if ($site) {
1695 $sql .= " AND site ='".$this->db->escape($site)."'";
1696 }
1697
1698 $result = $this->db->query($sql);
1699
1700 if ($result && $this->db->num_rows($result) == 0) {
1701 throw new RestException(404, 'This thirdparty does not have any account attached or does not exist.');
1702 }
1703
1704 $i = 0;
1705
1706 $accounts = array();
1707
1708 $num = $this->db->num_rows($result);
1709 while ($i < $num) {
1710 $obj = $this->db->fetch_object($result);
1711 $account = new SocieteAccount($this->db);
1712
1713 if ($account->fetch($obj->rowid)) {
1714 $accounts[] = $account;
1715 }
1716 $i++;
1717 }
1718
1719 $fields = array('id', 'fk_soc', 'key_account', 'site', 'date_creation', 'tms');
1720
1721 $returnAccounts = array();
1722
1723 foreach ($accounts as $account) {
1724 $object = array();
1725 foreach ($account as $key => $value) {
1726 if (in_array($key, $fields)) {
1727 $object[$key] = $value;
1728 }
1729 }
1730 $returnAccounts[] = $object;
1731 }
1732
1733 return $returnAccounts;
1734 }
1735
1748 public function getSocieteByAccounts($site, $key_account)
1749 {
1750 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1751 throw new RestException(403);
1752 }
1753
1754 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
1755 $sql .= " WHERE site = '".$this->db->escape($site)."' AND key_account = '".$this->db->escape($key_account)."'";
1756 $sql .= " AND entity IN (".getEntity('societe').")";
1757
1758 $result = $this->db->query($sql);
1759
1760 if ($result && $this->db->num_rows($result) == 1) {
1761 $obj = $this->db->fetch_object($result);
1762 $returnThirdparty = $this->_fetch($obj->fk_soc);
1763 } else {
1764 throw new RestException(404, 'This account have many thirdparties attached or does not exist.');
1765 }
1766
1767 if (!DolibarrApi::_checkAccessToResource('societe', $returnThirdparty->id)) {
1768 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1769 }
1770
1771 return $returnThirdparty;
1772 }
1773
1793 public function createSocieteAccount($id, $request_data = null)
1794 {
1795 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1796 throw new RestException(403);
1797 }
1798
1799 if (!isset($request_data['site'])) {
1800 throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !');
1801 }
1802
1803 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."'";
1804 $result = $this->db->query($sql);
1805
1806 if ($result && $this->db->num_rows($result) == 0) {
1807 $account = new SocieteAccount($this->db);
1808 if (!isset($request_data['login'])) {
1809 $account->login = "";
1810 }
1811 $account->fk_soc = $id;
1812
1813 foreach ($request_data as $field => $value) {
1814 if ($field === 'caller') {
1815 // 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
1816 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1817 continue;
1818 }
1819
1820 $account->$field = $this->_checkValForAPI($field, $value, $account);
1821 }
1822
1823 if ($account->create(DolibarrApiAccess::$user) < 0) {
1824 throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!');
1825 }
1826
1827 $this->_cleanObjectDatas($account);
1828
1829 return $account;
1830 } else {
1831 throw new RestException(409, 'A SocieteAccount entity already exists for this company and site.');
1832 }
1833 }
1834
1857 public function putSocieteAccount($id, $site, $request_data = null)
1858 {
1859 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1860 throw new RestException(403);
1861 }
1862
1863 $sql = "SELECT rowid, fk_user_creat, date_creation FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
1864 $result = $this->db->query($sql);
1865
1866 // We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one.
1867 if ($result && $this->db->num_rows == 0) {
1868 if (!isset($request_data['key_account'])) {
1869 throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !');
1870 }
1871 $account = new SocieteAccount($this->db);
1872 if (!isset($request_data['login'])) {
1873 $account->login = "";
1874 }
1875
1876 foreach ($request_data as $field => $value) {
1877 if ($field === 'caller') {
1878 // 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
1879 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1880 continue;
1881 }
1882
1883 $account->$field = $this->_checkValForAPI($field, $value, $account);
1884 }
1885
1886 $account->fk_soc = $id;
1887 $account->site = $site;
1888
1889 if ($account->create(DolibarrApiAccess::$user) < 0) {
1890 throw new RestException(500, 'Error creating SocieteAccount entity.');
1891 }
1892 // We found an existing SocieteAccount entity, we are replacing it
1893 } else {
1894 if (isset($request_data['site']) && $request_data['site'] !== $site) {
1895 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
1896 $result = $this->db->query($sql);
1897
1898 if ($result && $this->db->num_rows($result) !== 0) {
1899 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.");
1900 }
1901 }
1902
1903 $obj = $this->db->fetch_object($result);
1904
1905 $account = new SocieteAccount($this->db);
1906 $account->id = $obj->rowid;
1907 $account->fk_soc = $id;
1908 $account->site = $site;
1909 if (!isset($request_data['login'])) {
1910 $account->login = "";
1911 }
1912 $account->fk_user_creat = $obj->fk_user_creat;
1913 $account->date_creation = $obj->date_creation;
1914
1915 foreach ($request_data as $field => $value) {
1916 if ($field === 'caller') {
1917 // 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
1918 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1919 continue;
1920 }
1921
1922 $account->$field = $this->_checkValForAPI($field, $value, $account);
1923 }
1924
1925 if ($account->update(DolibarrApiAccess::$user) < 0) {
1926 throw new RestException(500, 'Error updating SocieteAccount entity.');
1927 }
1928 }
1929
1930 $this->_cleanObjectDatas($account);
1931
1932 return $account;
1933 }
1934
1951 public function patchSocieteAccount($id, $site, $request_data = null)
1952 {
1953 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1954 throw new RestException(403);
1955 }
1956
1957 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
1958 $result = $this->db->query($sql);
1959
1960 if ($result && $this->db->num_rows($result) == 0) {
1961 throw new RestException(404, "This thirdparty does not have $site account attached or does not exist.");
1962 } else {
1963 // If the user tries to edit the site member, we check first if
1964 if (isset($request_data['site']) && $request_data['site'] !== $site) {
1965 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
1966 $result = $this->db->query($sql);
1967
1968 if ($result && $this->db->num_rows($result) !== 0) {
1969 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.");
1970 }
1971 }
1972
1973 $obj = $this->db->fetch_object($result);
1974 $account = new SocieteAccount($this->db);
1975 $account->fetch($obj->rowid);
1976
1977 foreach ($request_data as $field => $value) {
1978 if ($field === 'caller') {
1979 // 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
1980 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1981 continue;
1982 }
1983
1984 $account->$field = $this->_checkValForAPI($field, $value, $account);
1985 }
1986
1987 if ($account->update(DolibarrApiAccess::$user) < 0) {
1988 throw new RestException(500, 'Error updating SocieteAccount account');
1989 }
1990
1991 $this->_cleanObjectDatas($account);
1992
1993 return $account;
1994 }
1995 }
1996
2010 public function deleteSocieteAccount($id, $site)
2011 {
2012 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2013 throw new RestException(403);
2014 }
2015
2016 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
2017 $result = $this->db->query($sql);
2018
2019 if ($result && $this->db->num_rows($result) == 0) {
2020 throw new RestException(404);
2021 } else {
2022 $obj = $this->db->fetch_object($result);
2023 $account = new SocieteAccount($this->db);
2024 $account->fetch($obj->rowid);
2025
2026 if ($account->delete(DolibarrApiAccess::$user) < 0) {
2027 throw new RestException(500, "Error while deleting $site account attached to this third party");
2028 }
2029 }
2030 }
2031
2045 {
2046 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2047 throw new RestException(403);
2048 }
2049
2054 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms";
2055 $sql .= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id);
2056
2057 $result = $this->db->query($sql);
2058
2059 if ($result && $this->db->num_rows($result) == 0) {
2060 throw new RestException(404, 'This third party does not have any account attached or does not exist.');
2061 } else {
2062 $i = 0;
2063
2064 $num = $this->db->num_rows($result);
2065 while ($i < $num) {
2066 $obj = $this->db->fetch_object($result);
2067 $account = new SocieteAccount($this->db);
2068 $account->fetch($obj->rowid);
2069
2070 if ($account->delete(DolibarrApiAccess::$user) < 0) {
2071 throw new RestException(500, 'Error while deleting account attached to this third party');
2072 }
2073 $i++;
2074 }
2075 }
2076 }
2077
2078 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2085 protected function _cleanObjectDatas($object)
2086 {
2087 // phpcs:enable
2088 $object = parent::_cleanObjectDatas($object);
2089
2090 unset($object->nom); // ->name already defined and nom deprecated
2091 unset($object->name_bis); // ->name_alias already defined
2092 unset($object->note); // ->note_private and note_public already defined
2093 unset($object->departement);
2094 unset($object->departement_code);
2095 unset($object->pays);
2096 unset($object->particulier);
2097 unset($object->prefix_comm);
2098
2099 unset($object->siren);
2100 unset($object->siret);
2101 unset($object->ape);
2102
2103 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.
2104
2105 unset($object->total_ht);
2106 unset($object->total_tva);
2107 unset($object->total_localtax1);
2108 unset($object->total_localtax2);
2109 unset($object->total_ttc);
2110
2111 unset($object->lines);
2112 unset($object->thirdparty);
2113
2114 unset($object->fk_delivery_address); // deprecated feature
2115
2116 return $object;
2117 }
2118
2127 private function _validate($data)
2128 {
2129 $thirdparty = array();
2130 foreach (Thirdparties::$FIELDS as $field) {
2131 if (!isset($data[$field])) {
2132 throw new RestException(400, "$field field missing");
2133 }
2134 $thirdparty[$field] = $data[$field];
2135 }
2136 return $thirdparty;
2137 }
2138
2160 private function _fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
2161 {
2162 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
2163 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on thirdparties.');
2164 }
2165
2166 if ($rowid === 0) {
2167 $result = $this->company->initAsSpecimen();
2168 } else {
2169 $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
2170 }
2171 if (!$result) {
2172 throw new RestException(404, 'Thirdparty not found');
2173 }
2174
2175 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
2176 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.' on this thirdparty');
2177 }
2178 if (isModEnabled('mailing')) {
2179 $this->company->getNoEmail();
2180 }
2181
2182 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
2183 $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
2184 $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
2185 } else {
2186 $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
2187 $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
2188 }
2189
2190 $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount);
2191 $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote);
2192 $this->company->absolute_discount = price2num($absolute_discount, 'MT');
2193 $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
2194
2195 return $this->_cleanObjectDatas($this->company);
2196 }
2197}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
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.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.