dolibarr 22.0.5
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-2025 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024 Jon Bendtsen <jon.bendtsen.github@jonb.dk>
9 * Copyright (C) 2025 William Mead <william@m34d.com>
10 * Copyright (C) 2025 Charlene Benke <charlene@patas-monkey.com>
11 * Copyright (C) 2026 Benjamin Falière <benjamin@faliere.com>
12 * Copyright (C) 2026 Noé Cendrier <noe.cendrier@altairis.fr>
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26 */
27
28use Luracast\Restler\RestException;
29
39{
43 public static $FIELDS = array(
44 'name'
45 );
46
50 public $company;
51
55 public function __construct()
56 {
57 global $db;
58 $this->db = $db;
59
60 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
61 require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
62 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
63 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
64 require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
65
66 $this->company = new Societe($this->db);
67
68 if (getDolGlobalString('SOCIETE_EMAIL_MANDATORY')) {
69 static::$FIELDS[] = 'email';
70 }
71 }
72
85 public function get($id)
86 {
87 return $this->_fetch($id);
88 }
89
106 public function getByEmail($email)
107 {
108 return $this->_fetch(null, '', '', '', '', '', '', '', '', '', $email);
109 }
110
125 public function getByBarcode($barcode)
126 {
127 return $this->_fetch(null, '', '', $barcode);
128 }
129
152 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
153 {
154 $obj_ret = array();
155
156 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
157 throw new RestException(403);
158 }
159
160 // case of external user, we force socids
161 $socids = DolibarrApiAccess::$user->socid ? (string) DolibarrApiAccess::$user->socid : '';
162
163 // If the internal user must only see his customers, force searching by him
164 $search_sale = 0;
165 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
166 $search_sale = DolibarrApiAccess::$user->id;
167 }
168
169 $sql = "SELECT t.rowid";
170 $sql .= " FROM ".MAIN_DB_PREFIX."societe as t";
171 $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
172 if ($category > 0) {
173 if ($mode != 4) {
174 $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c";
175 }
176 if (!in_array($mode, array(1, 2, 3))) {
177 $sql .= ", ".MAIN_DB_PREFIX."categorie_fournisseur as cc";
178 }
179 }
180 $sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st";
181 $sql .= " WHERE t.entity IN (".getEntity('societe').")";
182 $sql .= " AND t.fk_stcomm = st.id";
183 if ($mode == 1) {
184 $sql .= " AND t.client IN (1, 3)";
185 } elseif ($mode == 2) {
186 $sql .= " AND t.client IN (2, 3)";
187 } elseif ($mode == 3) {
188 $sql .= " AND t.client IN (0)";
189 } elseif ($mode == 4) {
190 $sql .= " AND t.fournisseur IN (1)";
191 }
192 // Select thirdparties of given category
193 if ($category > 0) {
194 if (!empty($mode) && $mode != 4) {
195 $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_soc = t.rowid";
196 } elseif (!empty($mode) && $mode == 4) {
197 $sql .= " AND cc.fk_categorie = ".((int) $category)." AND cc.fk_soc = t.rowid";
198 } else {
199 $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))";
200 }
201 }
202 if ($socids) {
203 $sql .= " AND t.rowid IN (".$this->db->sanitize($socids).")";
204 }
205 // Search on sale representative
206 if ($search_sale && $search_sale != '-1') {
207 if ($search_sale == -2) {
208 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.rowid)";
209 } elseif ($search_sale > 0) {
210 $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).")";
211 }
212 }
213 // Add sql filters
214 if ($sqlfilters) {
215 $errormessage = '';
216 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
217 if ($errormessage) {
218 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
219 }
220 }
221
222 //this query will return total thirdparties with the filters given
223 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
224
225 $sql .= $this->db->order($sortfield, $sortorder);
226 if ($limit) {
227 if ($page < 0) {
228 $page = 0;
229 }
230 $offset = $limit * $page;
231
232 $sql .= $this->db->plimit($limit + 1, $offset);
233 }
234
235 $result = $this->db->query($sql);
236 if ($result) {
237 $num = $this->db->num_rows($result);
238 $min = min($num, ($limit <= 0 ? $num : $limit));
239 $i = 0;
240 while ($i < $min) {
241 $obj = $this->db->fetch_object($result);
242 $soc_static = new Societe($this->db);
243 if ($soc_static->fetch($obj->rowid)) {
244 if (isModEnabled('mailing')) {
245 $soc_static->getNoEmail();
246 }
247 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($soc_static), $properties);
248 }
249 $i++;
250 }
251 } else {
252 throw new RestException(503, 'Error when retrieve thirdparties : '.$this->db->lasterror());
253 }
254 if (!count($obj_ret)) {
255 $message = '';
256 switch ($mode) {
257 case 0:
258 $message = 'No third parties found';
259 break;
260 case 1:
261 $message = 'No customers found';
262 break;
263 case 2:
264 $message = 'No prospects found';
265 break;
266 case 3:
267 $message = 'No other third parties found';
268 break;
269 case 4:
270 $message = 'No suppliers found';
271 }
272 throw new RestException(404, $message);
273 }
274
275 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
276 if ($pagination_data) {
277 $totalsResult = $this->db->query($sqlTotals);
278 $total = $this->db->fetch_object($totalsResult)->total;
279
280 $tmp = $obj_ret;
281 $obj_ret = [];
282
283 $obj_ret['data'] = $tmp;
284 $obj_ret['pagination'] = [
285 'total' => (int) $total,
286 'page' => $page, //count starts from 0
287 'page_count' => ceil((int) $total / $limit),
288 'limit' => $limit
289 ];
290 }
291
292 return $obj_ret;
293 }
294
307 public function post($request_data = null)
308 {
309 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
310 throw new RestException(403);
311 }
312 // Check mandatory fields
313 $result = $this->_validate($request_data);
314
315 foreach ($request_data as $field => $value) {
316 if ($field === 'caller') {
317 // 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
318 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
319 continue;
320 }
321
322 $this->company->$field = $this->_checkValForAPI($field, $value, $this->company);
323 }
324
325 if ($this->company->create(DolibarrApiAccess::$user) < 0) {
326 throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors));
327 }
328 if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
329 $this->company->setNoEmail($this->company->no_email);
330 }
331
332 return $this->company->id;
333 }
334
352 public function put($id, $request_data = null)
353 {
354 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
355 throw new RestException(403);
356 }
357
358 $result = $this->company->fetch($id);
359 if (!$result) {
360 throw new RestException(404, 'Thirdparty not found');
361 }
362
363 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
364 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
365 }
366
367 foreach ($request_data as $field => $value) {
368 if ($field == 'id') {
369 continue;
370 }
371 if ($field === 'caller') {
372 // 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
373 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
374 continue;
375 }
376 if ($field == 'array_options' && is_array($value)) {
377 foreach ($value as $index => $val) {
378 $this->company->array_options[$index] = $this->_checkValForAPI($field, $val, $this->company);
379 }
380 continue;
381 }
382 $this->company->$field = $this->_checkValForAPI($field, $value, $this->company);
383 }
384
385 if (isModEnabled('mailing') && !empty($this->company->email) && isset($this->company->no_email)) {
386 $this->company->setNoEmail($this->company->no_email);
387 }
388
389 if ($this->company->update($id, DolibarrApiAccess::$user, 1, 1, 1, 'update', 1) > 0) {
390 return $this->get($id);
391 } else {
392 throw new RestException(500, $this->company->error);
393 }
394 }
395
417 public function merge($id, $idtodelete)
418 {
419 if ($id == $idtodelete) {
420 throw new RestException(400, 'Try to merge a thirdparty into itself');
421 }
422
423 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
424 throw new RestException(403);
425 }
426
427 $result = $this->company->fetch($id); // include the fetch of extra fields
428 if (!$result) {
429 throw new RestException(404, 'Thirdparty not found');
430 }
431
432 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
433 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
434 }
435
436 $companytoremove = new Societe($this->db);
437 $result = $companytoremove->fetch($idtodelete); // include the fetch of extra fields
438 if (!$result) {
439 throw new RestException(404, 'Thirdparty not found');
440 }
441
442 if (!DolibarrApi::_checkAccessToResource('societe', $companytoremove->id)) {
443 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
444 }
445
446 $user = DolibarrApiAccess::$user;
447 $result = $this->company->mergeCompany($companytoremove->id);
448 if ($result < 0) {
449 throw new RestException(500, 'Error failed to merged thirdparty '.$companytoremove->id.' into '.$id.'. Enable and read log file for more information.');
450 }
451
452 return $this->get($id);
453 }
454
467 public function delete($id)
468 {
469 if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
470 throw new RestException(403);
471 }
472 $result = $this->company->fetch($id);
473 if (!$result) {
474 throw new RestException(404, 'Thirdparty not found');
475 }
476 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
477 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
478 }
479 $this->company->oldcopy = clone $this->company; // @phan-suppress-current-line PhanTypeMismatchProperty
480
481 $res = $this->company->delete($id);
482 if ($res < 0) {
483 throw new RestException(500, "Can't delete, error occurs");
484 } elseif ($res == 0) {
485 throw new RestException(409, "Can't delete, that product is probably used");
486 }
487
488 return array(
489 'success' => array(
490 'code' => 200,
491 'message' => 'Object deleted'
492 )
493 );
494 }
495
513 public function setThirdpartyPriceLevel($id, $priceLevel)
514 {
515 global $conf;
516
517 if (!isModEnabled('societe')) {
518 throw new RestException(501, 'Module "Thirdparties" needed for this request');
519 }
520
521 if (!isModEnabled("product")) {
522 throw new RestException(501, 'Module "Products" needed for this request');
523 }
524
525 if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
526 throw new RestException(501, 'Multiprices features activation needed for this request');
527 }
528
529 if ($priceLevel < 1 || $priceLevel > getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT')) {
530 throw new RestException(400, 'Price level must be between 1 and ' . getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT'));
531 }
532
533 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
534 throw new RestException(403, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
535 }
536
537 $result = $this->company->fetch($id);
538 if ($result < 0) {
539 throw new RestException(404, 'Thirdparty '.$id.' not found');
540 }
541
542 if (empty($result)) {
543 throw new RestException(500, 'Error fetching thirdparty '.$id, array_merge(array($this->company->error), $this->company->errors));
544 }
545
546 if (empty(DolibarrApi::_checkAccessToResource('societe', $this->company->id))) {
547 throw new RestException(403, 'Access to thirdparty '.$id.' not allowed for login '.DolibarrApiAccess::$user->login);
548 }
549
550 $result = $this->company->setPriceLevel($priceLevel, DolibarrApiAccess::$user);
551 if ($result <= 0) {
552 throw new RestException(500, 'Error setting new price level for thirdparty '.$id, array($this->company->db->lasterror()));
553 }
554
555 return $this->_cleanObjectDatas($this->company);
556 }
557
572 public function addRepresentative($id, $representative_id)
573 {
574 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
575 throw new RestException(403);
576 }
577 $result = $this->company->fetch($id);
578 if (!$result) {
579 throw new RestException(404, 'Thirdparty not found');
580 }
581 $usertmp = new User($this->db);
582 $result = $usertmp->fetch($representative_id);
583 if (!$result) {
584 throw new RestException(404, 'User not found');
585 }
586 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
587 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
588 }
589 $result = $this->company->add_commercial(DolibarrApiAccess::$user, $representative_id);
590
591 return $result;
592 }
593
608 public function deleteRepresentative($id, $representative_id)
609 {
610 if (!DolibarrApiAccess::$user->hasRight('societe', 'supprimer')) {
611 throw new RestException(403);
612 }
613 $result = $this->company->fetch($id);
614 if (!$result) {
615 throw new RestException(404, 'Thirdparty not found');
616 }
617 $usertmp = new User($this->db);
618 $result = $usertmp->fetch($representative_id);
619 if (!$result) {
620 throw new RestException(404, 'User not found');
621 }
622 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
623 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
624 }
625 $result = $this->company->del_commercial(DolibarrApiAccess::$user, $representative_id);
626
627 return $result;
628 }
629
648 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
649 {
650 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
651 throw new RestException(403);
652 }
653
654 $result = $this->company->fetch($id);
655 if (!$result) {
656 throw new RestException(404, 'Thirdparty not found');
657 }
658
659 $categories = new Categorie($this->db);
660
661 $arrayofcateg = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page);
662
663 if (is_numeric($arrayofcateg) && $arrayofcateg < 0) {
664 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
665 }
666
667 if (is_numeric($arrayofcateg) && $arrayofcateg >= 0) { // To fix a return of 0 instead of empty array of method getListForItem
668 return array();
669 }
670
671 return $arrayofcateg;
672 }
673
690 public function addCategory($id, $category_id)
691 {
692 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
693 throw new RestException(403);
694 }
695
696 $result = $this->company->fetch($id);
697 if (!$result) {
698 throw new RestException(404, 'Thirdparty not found');
699 }
700 $category = new Categorie($this->db);
701 $result = $category->fetch($category_id);
702 if (!$result) {
703 throw new RestException(404, 'category not found');
704 }
705
706 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
707 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
708 }
709 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
710 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
711 }
712
713 $category->add_type($this->company, 'customer');
714
715 return $this->_cleanObjectDatas($this->company);
716 }
717
734 public function deleteCategory($id, $category_id)
735 {
736 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
737 throw new RestException(403);
738 }
739
740 $result = $this->company->fetch($id);
741 if (!$result) {
742 throw new RestException(404, 'Thirdparty not found');
743 }
744 $category = new Categorie($this->db);
745 $result = $category->fetch($category_id);
746 if (!$result) {
747 throw new RestException(404, 'category not found');
748 }
749
750 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
751 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
752 }
753 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
754 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
755 }
756
757 $category->del_type($this->company, 'customer');
758
759 return $this->_cleanObjectDatas($this->company);
760 }
761
781 public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
782 {
783 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
784 throw new RestException(403);
785 }
786
787 $result = $this->company->fetch($id);
788 if (!$result) {
789 throw new RestException(404, 'Thirdparty not found');
790 }
791
792 $categories = new Categorie($this->db);
793
794 $result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page);
795
796 if (is_numeric($result) && $result < 0) {
797 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
798 }
799
800 if (is_numeric($result) && $result == 0) { // To fix a return of 0 instead of empty array of method getListForItem
801 return array();
802 }
803
804 return $result;
805 }
806
823 public function addSupplierCategory($id, $category_id)
824 {
825 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
826 throw new RestException(403);
827 }
828
829 $result = $this->company->fetch($id);
830 if (!$result) {
831 throw new RestException(404, 'Thirdparty not found');
832 }
833 $category = new Categorie($this->db);
834 $result = $category->fetch($category_id);
835 if (!$result) {
836 throw new RestException(404, 'category not found');
837 }
838
839 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
840 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
841 }
842 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
843 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
844 }
845
846 $category->add_type($this->company, 'supplier');
847
848 return $this->_cleanObjectDatas($this->company);
849 }
850
867 public function deleteSupplierCategory($id, $category_id)
868 {
869 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
870 throw new RestException(403);
871 }
872
873 $result = $this->company->fetch($id);
874 if (!$result) {
875 throw new RestException(404, 'Thirdparty not found');
876 }
877 $category = new Categorie($this->db);
878 $result = $category->fetch($category_id);
879 if (!$result) {
880 throw new RestException(404, 'category not found');
881 }
882
883 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
884 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
885 }
886 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
887 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
888 }
889
890 $category->del_type($this->company, 'supplier');
891
892 return $this->_cleanObjectDatas($this->company);
893 }
894
895
914 public function getOutStandingProposals($id, $mode = 'customer')
915 {
916 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
917 throw new RestException(403);
918 }
919
920 if (empty($id)) {
921 throw new RestException(400, 'Thirdparty ID is mandatory');
922 }
923
924 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
925 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
926 }
927
928 $result = $this->company->fetch($id);
929 if (!$result) {
930 throw new RestException(404, 'Thirdparty not found');
931 }
932
933 $result = $this->company->getOutstandingProposals($mode);
934
935 unset($result['total_ht']);
936 unset($result['total_ttc']);
937
938 return $result;
939 }
940
941
960 public function getOutStandingOrder($id, $mode = 'customer')
961 {
962 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
963 throw new RestException(403);
964 }
965
966 if (empty($id)) {
967 throw new RestException(400, 'Thirdparty ID is mandatory');
968 }
969
970 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
971 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
972 }
973
974 $result = $this->company->fetch($id);
975 if (!$result) {
976 throw new RestException(404, 'Thirdparty not found');
977 }
978
979 $result = $this->company->getOutstandingOrders($mode);
980
981 unset($result['total_ht']);
982 unset($result['total_ttc']);
983
984 return $result;
985 }
986
1005 public function getOutStandingInvoices($id, $mode = 'customer')
1006 {
1007 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1008 throw new RestException(403);
1009 }
1010
1011 if (empty($id)) {
1012 throw new RestException(400, 'Thirdparty ID is mandatory');
1013 }
1014
1015 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1016 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1017 }
1018
1019 $result = $this->company->fetch($id);
1020 if (!$result) {
1021 throw new RestException(404, 'Thirdparty not found');
1022 }
1023
1024 $result = $this->company->getOutstandingBills($mode);
1025
1026 unset($result['total_ht']);
1027 unset($result['total_ttc']);
1028
1029 return $result;
1030 }
1031
1050 public function getSalesRepresentatives($id, $mode = 0)
1051 {
1052 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1053 throw new RestException(403);
1054 }
1055
1056 if (empty($id)) {
1057 throw new RestException(400, 'Thirdparty ID is mandatory');
1058 }
1059
1060 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1061 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1062 }
1063
1064 $result = $this->company->fetch($id);
1065 if ($result < 1) {
1066 throw new RestException(404, 'Thirdparty not found');
1067 }
1068
1069 $result = $this->company->getSalesRepresentatives(DolibarrApiAccess::$user, $mode);
1070
1071 return $result;
1072 }
1073
1097 public function getFixedAmountDiscounts($id, $filter = "none", $sortfield = "f.type", $sortorder = 'ASC')
1098 {
1099 $obj_ret = array();
1100
1101 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1102 throw new RestException(403);
1103 }
1104
1105 if (empty($id)) {
1106 throw new RestException(400, 'Thirdparty ID is mandatory');
1107 }
1108
1109 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1110 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1111 }
1112
1113 $result = $this->company->fetch($id);
1114 if (!$result) {
1115 throw new RestException(404, 'Thirdparty not found');
1116 }
1117
1118
1119 $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";
1120 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1121 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = re.fk_facture_source";
1122 $sql .= " WHERE re.fk_soc = ".((int) $id);
1123 if ($filter == "available") {
1124 $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL";
1125 }
1126 if ($filter == "used") {
1127 $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)";
1128 }
1129
1130 $sql .= $this->db->order($sortfield, $sortorder);
1131
1132 $result = $this->db->query($sql);
1133 if (!$result) {
1134 throw new RestException(503, $this->db->lasterror());
1135 } else {
1136 $num = $this->db->num_rows($result);
1137 while ($obj = $this->db->fetch_object($result)) {
1138 $obj_ret[] = $obj;
1139 }
1140 }
1141
1142 return $obj_ret;
1143 }
1144
1145
1146
1165 {
1166 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1167 throw new RestException(403);
1168 }
1169 if (empty($id)) {
1170 throw new RestException(400, 'Thirdparty ID is mandatory');
1171 }
1172
1173 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1174 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1175 }
1176
1177 /*$result = $this->thirdparty->fetch($id);
1178 if( ! $result ) {
1179 throw new RestException(404, 'Thirdparty not found');
1180 }*/
1181
1182 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1183 $invoice = new Facture($this->db);
1184 $result = $invoice->list_replacable_invoices($id);
1185 if ($result < 0) {
1186 throw new RestException(405, $invoice->error);
1187 }
1188
1189 return $result;
1190 }
1191
1214 {
1215 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1216 throw new RestException(403);
1217 }
1218 if (empty($id)) {
1219 throw new RestException(400, 'Thirdparty ID is mandatory');
1220 }
1221
1222 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1223 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1224 }
1225
1226 /*$result = $this->thirdparty->fetch($id);
1227 if( ! $result ) {
1228 throw new RestException(404, 'Thirdparty not found');
1229 }*/
1230
1231 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1232 $invoice = new Facture($this->db);
1233 $result = $invoice->list_qualified_avoir_invoices($id);
1234 if (!is_array($result) && $result < 0) {
1235 throw new RestException(405, $invoice->error);
1236 }
1237
1238 return $result;
1239 }
1240
1257 {
1258 if (empty($id)) {
1259 throw new RestException(400, 'Thirdparty ID is mandatory');
1260 }
1261 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1262 throw new RestException(403);
1263 }
1264 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1265 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1266 }
1267
1272 $sql = "SELECT rowid as id, fk_action as event, fk_soc as socid, fk_contact as contact_id, type, datec, tms";
1273 $sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1274 if ($id) {
1275 $sql .= " WHERE fk_soc = ".((int) $id);
1276 }
1277
1278 $result = $this->db->query($sql);
1279 if ($this->db->num_rows($result) == 0) {
1280 throw new RestException(404, 'Notification not found');
1281 }
1282
1283 $i = 0;
1284
1285 $notifications = array();
1286
1287 if ($result) {
1288 $num = $this->db->num_rows($result);
1289 while ($i < $num) {
1290 $obj = $this->db->fetch_object($result);
1291 $notifications[] = $obj;
1292 $i++;
1293 }
1294 } else {
1295 throw new RestException(404, 'No notifications found');
1296 }
1297
1298 $fields = array('id', 'socid', 'event', 'contact_id', 'datec', 'tms', 'type');
1299
1300 $returnNotifications = array();
1301
1302 foreach ($notifications as $notification) {
1303 $object = array();
1304 foreach ($notification as $key => $value) {
1305 if (in_array($key, $fields)) {
1306 $object[$key] = $value;
1307 }
1308 }
1309 $returnNotifications[] = $object;
1310 }
1311
1312 // Too complex for phan ?: @phan-suppress-next-line PhanTypeMismatchReturn
1313 return $returnNotifications;
1314 }
1315
1332 public function createCompanyNotification($id, $request_data = null)
1333 {
1334 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1335 throw new RestException(403, "User has no right to update thirdparties");
1336 }
1337 if ($this->company->fetch($id) <= 0) {
1338 throw new RestException(404, 'Error creating Thirdparty Notification, Thirdparty doesn\'t exists');
1339 }
1340 $notification = new Notify($this->db);
1341
1342 $notification->socid = $id;
1343
1344 foreach ($request_data as $field => $value) {
1345 $notification->$field = $value;
1346 }
1347
1348 $event = $notification->event;
1349 if (!$event) {
1350 throw new RestException(500, 'Error creating Thirdparty Notification, request_data missing event');
1351 }
1352 $socid = $notification->socid;
1353 $contact_id = $notification->contact_id;
1354
1355 $exists_sql = "SELECT rowid, fk_action as event, fk_soc as socid, fk_contact as contact_id, type, datec, tms as datem";
1356 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1357 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1358 $exists_sql .= " AND fk_soc = '".$this->db->escape((string) $socid)."'";
1359 $exists_sql .= " AND fk_contact = '".$this->db->escape((string) $contact_id)."'";
1360
1361 $exists_result = $this->db->query($exists_sql);
1362 if ($this->db->num_rows($exists_result) > 0) {
1363 throw new RestException(403, 'Notification already exists');
1364 }
1365
1366 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1367 throw new RestException(500, 'Error creating Thirdparty Notification');
1368 }
1369
1370 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1371 throw new RestException(500, 'Error updating values');
1372 }
1373
1374 return $this->_cleanObjectDatas($notification);
1375 }
1376
1395 public function createCompanyNotificationByCode($id, $code, $request_data = null)
1396 {
1397 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1398 throw new RestException(403, "User has no right to update thirdparties");
1399 }
1400 if ($this->company->fetch($id) <= 0) {
1401 throw new RestException(404, 'Error creating Thirdparty Notification, Thirdparty doesn\'t exists');
1402 }
1403 $notification = new Notify($this->db);
1404 $notification->socid = $id;
1405
1406 $sql = "SELECT t.rowid as id FROM ".MAIN_DB_PREFIX."c_action_trigger as t";
1407 $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
1408
1409 $result = $this->db->query($sql);
1410 if ($this->db->num_rows($result) == 0) {
1411 throw new RestException(404, 'Action Trigger code not found');
1412 }
1413
1414 $notification->event = $this->db->fetch_row($result)[0];
1415 foreach ($request_data as $field => $value) {
1416 if ($field === 'event') {
1417 throw new RestException(500, 'Error creating Thirdparty Notification, request_data contains event key');
1418 }
1419 if ($field === 'fk_action') {
1420 throw new RestException(500, 'Error creating Thirdparty Notification, request_data contains fk_action key');
1421 }
1422 $notification->$field = $value;
1423 }
1424
1425 $event = $notification->event;
1426 $socid = $notification->socid;
1427 $contact_id = $notification->contact_id;
1428
1429 $exists_sql = "SELECT rowid, fk_action as event, fk_soc as socid, fk_contact as contact_id, type, datec, tms as datem";
1430 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1431 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1432 $exists_sql .= " AND fk_soc = '".$this->db->escape((string) $socid)."'";
1433 $exists_sql .= " AND fk_contact = '".$this->db->escape((string) $contact_id)."'";
1434
1435 $exists_result = $this->db->query($exists_sql);
1436 if ($this->db->num_rows($exists_result) > 0) {
1437 throw new RestException(403, 'Notification already exists');
1438 }
1439
1440 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1441 throw new RestException(500, 'Error creating Thirdparty Notification, are request_data well formed?');
1442 }
1443
1444 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1445 throw new RestException(500, 'Error updating values');
1446 }
1447
1448 return $this->_cleanObjectDatas($notification);
1449 }
1450
1465 public function deleteCompanyNotification($id, $notification_id)
1466 {
1467 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1468 throw new RestException(403);
1469 }
1470
1471 $notification = new Notify($this->db);
1472
1473 $notification->fetch($notification_id);
1474
1475 $socid = (int) $notification->socid;
1476
1477 if ($socid == $id) {
1478 return $notification->delete(DolibarrApiAccess::$user);
1479 } else {
1480 throw new RestException(403, "Not allowed due to bad consistency of input data");
1481 }
1482 }
1483
1501 public function updateCompanyNotification($id, $notification_id, $request_data = null)
1502 {
1503 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1504 throw new RestException(403, "User has no right to update thirdparties");
1505 }
1506 if ($this->company->fetch($id) <= 0) {
1507 throw new RestException(404, 'Error creating Company Notification, Company doesn\'t exists');
1508 }
1509 $notification = new Notify($this->db);
1510
1511 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1512 $notification->fetch($notification_id, $id);
1513
1514 if ($notification->socid != $id) {
1515 throw new RestException(403, "Not allowed due to bad consistency of input data");
1516 }
1517
1518 foreach ($request_data as $field => $value) {
1519 $notification->$field = $value;
1520 }
1521
1522 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1523 throw new RestException(500, 'Error updating values');
1524 }
1525
1526 return $this->_cleanObjectDatas($notification);
1527 }
1528
1545 {
1546 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1547 throw new RestException(403);
1548 }
1549 if (empty($id)) {
1550 throw new RestException(400, 'Thirdparty ID is mandatory');
1551 }
1552
1553 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1554 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1555 }
1556
1561 $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation as address, proprio,";
1562 $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur";
1563 $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1564 if ($id) {
1565 $sql .= " WHERE fk_soc = ".((int) $id);
1566 }
1567
1568 $result = $this->db->query($sql);
1569
1570 if ($this->db->num_rows($result) == 0) {
1571 throw new RestException(404, 'Account not found');
1572 }
1573
1574 $i = 0;
1575
1576 $accounts = array();
1577
1578 if ($result) {
1579 $num = $this->db->num_rows($result);
1580 while ($i < $num) {
1581 $obj = $this->db->fetch_object($result);
1582
1583 $account = new CompanyBankAccount($this->db);
1584 if ($account->fetch($obj->rowid)) {
1585 $accounts[] = $account;
1586 }
1587 $i++;
1588 }
1589 } else {
1590 throw new RestException(404, 'Account not found');
1591 }
1592
1593
1594 $fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum');
1595
1596 $returnAccounts = array();
1597
1598 foreach ($accounts as $account) {
1599 $object = array();
1600 foreach ($account as $key => $value) {
1601 if (in_array($key, $fields)) {
1602 if ($key == 'iban') {
1603 $object[$key] = dolDecrypt($value);
1604 } else {
1605 $object[$key] = $value;
1606 }
1607 }
1608 }
1609 $returnAccounts[] = $object;
1610 }
1611
1612 return $returnAccounts;
1613 }
1614
1631 public function createCompanyBankAccount($id, $request_data = null)
1632 {
1633 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1634 throw new RestException(403);
1635 }
1636 if ($this->company->fetch($id) <= 0) {
1637 throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1638 }
1639 $account = new CompanyBankAccount($this->db);
1640
1641 $account->socid = $id;
1642
1643 foreach ($request_data as $field => $value) {
1644 if ($field === 'caller') {
1645 // 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
1646 $this->company->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1647 continue;
1648 }
1649
1650 $account->$field = $this->_checkValForAPI('extrafields', $value, $account);
1651 }
1652
1653 if ($account->create(DolibarrApiAccess::$user) < 0) {
1654 throw new RestException(500, 'Error creating Company Bank account');
1655 }
1656
1657 if (empty($account->rum)) {
1658 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1659 $prelevement = new BonPrelevement($this->db);
1660 $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, (string) $account->id);
1661 $account->date_rum = dol_now();
1662 }
1663
1664 if ($account->update(DolibarrApiAccess::$user) < 0) {
1665 throw new RestException(500, 'Error updating values');
1666 }
1667
1668 return $this->_cleanObjectDatas($account);
1669 }
1670
1688 public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
1689 {
1690 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1691 throw new RestException(403);
1692 }
1693 if ($this->company->fetch($id) <= 0) {
1694 throw new RestException(404, 'Error creating Company Bank account, Company doesn\'t exists');
1695 }
1696 $account = new CompanyBankAccount($this->db);
1697
1698 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1699 $account->fetch($bankaccount_id, '', $id, -1, '');
1700
1701 if ($account->socid != $id) {
1702 throw new RestException(403);
1703 }
1704
1705
1706 foreach ($request_data as $field => $value) {
1707 if ($field === 'caller') {
1708 // 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
1709 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1710 continue;
1711 }
1712
1713 $account->$field = $this->_checkValForAPI($field, $value, $account);
1714 }
1715
1716 if (empty($account->rum)) {
1717 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1718 $prelevement = new BonPrelevement($this->db);
1719 $account->rum = $prelevement->buildRumNumber($this->company->code_client, $account->datec, (string) $account->id);
1720 $account->date_rum = dol_now();
1721 }
1722
1723 if ($account->update(DolibarrApiAccess::$user) < 0) {
1724 throw new RestException(500, 'Error updating values');
1725 }
1726
1727 return $this->_cleanObjectDatas($account);
1728 }
1729
1744 public function deleteCompanyBankAccount($id, $bankaccount_id)
1745 {
1746 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1747 throw new RestException(403);
1748 }
1749
1750 $account = new CompanyBankAccount($this->db);
1751
1752 $account->fetch($bankaccount_id);
1753
1754 $socid = (int) $account->socid;
1755
1756 if ($socid == $id) {
1757 return $account->delete(DolibarrApiAccess::$user);
1758 } else {
1759 throw new RestException(403, "Not allowed due to bad consistency of input data");
1760 }
1761 }
1762
1781 public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
1782 {
1783 global $conf, $langs;
1784
1785 $langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals"));
1786
1787 if ($this->company->fetch($id) <= 0) {
1788 throw new RestException(404, 'Thirdparty not found');
1789 }
1790
1791 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
1792 throw new RestException(403);
1793 }
1794
1795 $this->company->setDocModel(DolibarrApiAccess::$user, $model);
1796
1797 $this->company->fk_bank = $this->company->fk_account;
1798 // $this->company->fk_account = $this->company->fk_account;
1799
1800 $outputlangs = $langs;
1801 $newlang = '';
1802
1803 //if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
1804 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1805 if (isset($this->company->thirdparty->default_lang)) {
1806 $newlang = $this->company->thirdparty->default_lang; // for proposal, order, invoice, ...
1807 } elseif (isset($this->company->default_lang)) {
1808 $newlang = $this->company->default_lang; // for thirdparty
1809 }
1810 }
1811 if (!empty($newlang)) {
1812 $outputlangs = new Translate("", $conf);
1813 $outputlangs->setDefaultLang($newlang);
1814 }
1815
1816 $sql = "SELECT rowid";
1817 $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib";
1818 if ($id) {
1819 $sql .= " WHERE fk_soc = ".((int) $id);
1820 }
1821 if ($companybankid) {
1822 $sql .= " AND rowid = ".((int) $companybankid);
1823 }
1824
1825 $i = 0;
1826 $accounts = array();
1827
1828 $result = $this->db->query($sql);
1829 if ($result) {
1830 if ($this->db->num_rows($result) == 0) {
1831 throw new RestException(404, 'Bank account not found');
1832 }
1833
1834 $num = $this->db->num_rows($result);
1835 while ($i < $num) {
1836 $obj = $this->db->fetch_object($result);
1837
1838 $account = new CompanyBankAccount($this->db);
1839 if ($account->fetch($obj->rowid)) {
1840 $accounts[] = $account;
1841 }
1842 $i++;
1843 }
1844 } else {
1845 throw new RestException(500, 'Sql error '.$this->db->lasterror());
1846 }
1847
1848 $moreparams = array(
1849 'use_companybankid' => $accounts[0]->id,
1850 'force_dir_output' => $conf->societe->multidir_output[$this->company->entity].'/'.dol_sanitizeFileName((string) $this->company->id)
1851 );
1852
1853 $result = $this->company->generateDocument($model, $outputlangs, 0, 0, 0, $moreparams);
1854
1855 if ($result > 0) {
1856 return array("success" => $result);
1857 } else {
1858 throw new RestException(500, 'Error generating the document '.$this->company->error);
1859 }
1860 }
1861
1879 public function getSocieteAccounts($id, $site = null)
1880 {
1881 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1882 throw new RestException(403);
1883 }
1884
1885 if (!DolibarrApi::_checkAccessToResource('societe', $id)) {
1886 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1887 }
1888
1892 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
1893 $sql .= " WHERE fk_soc = ".((int) $id);
1894 if ($site) {
1895 $sql .= " AND site ='".$this->db->escape($site)."'";
1896 }
1897
1898 $result = $this->db->query($sql);
1899
1900 if ($result && $this->db->num_rows($result) == 0) {
1901 throw new RestException(404, 'This thirdparty does not have any account attached or does not exist.');
1902 }
1903
1904 $i = 0;
1905
1906 $accounts = array();
1907
1908 $num = $this->db->num_rows($result);
1909 while ($i < $num) {
1910 $obj = $this->db->fetch_object($result);
1911 $account = new SocieteAccount($this->db);
1912
1913 if ($account->fetch($obj->rowid)) {
1914 $accounts[] = $account;
1915 }
1916 $i++;
1917 }
1918
1919 $fields = array('id', 'fk_soc', 'key_account', 'site', 'date_creation', 'tms');
1920
1921 $returnAccounts = array();
1922
1923 foreach ($accounts as $account) {
1924 $object = array();
1925 foreach ($account as $key => $value) {
1926 if (in_array($key, $fields)) {
1927 $object[$key] = $value;
1928 }
1929 }
1930 $returnAccounts[] = $object;
1931 }
1932
1933 return $returnAccounts;
1934 }
1935
1953 public function getSocieteByAccounts($site, $key_account)
1954 {
1955 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
1956 throw new RestException(403);
1957 }
1958
1959 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
1960 $sql .= " WHERE site = '".$this->db->escape($site)."' AND key_account = '".$this->db->escape($key_account)."'";
1961 $sql .= " AND entity IN (".getEntity('societe').")";
1962
1963 $result = $this->db->query($sql);
1964
1965 if ($result && $this->db->num_rows($result) == 1) {
1966 $obj = $this->db->fetch_object($result);
1967 $returnThirdparty = $this->_fetch($obj->fk_soc);
1968 } else {
1969 throw new RestException(404, 'This account have many thirdparties attached or does not exist.');
1970 }
1971
1972 if (!DolibarrApi::_checkAccessToResource('societe', $returnThirdparty->id)) {
1973 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1974 }
1975
1976 return $returnThirdparty;
1977 }
1978
2002 public function createSocieteAccount($id, $request_data = null)
2003 {
2004 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2005 throw new RestException(403);
2006 }
2007
2008 if (!isset($request_data['site'])) {
2009 throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !');
2010 }
2011
2012 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."'";
2013 $result = $this->db->query($sql);
2014
2015 if ($result && $this->db->num_rows($result) == 0) {
2016 $account = new SocieteAccount($this->db);
2017 if (!isset($request_data['login'])) {
2018 $account->login = "";
2019 }
2020 $account->fk_soc = $id;
2021
2022 foreach ($request_data as $field => $value) {
2023 if ($field === 'caller') {
2024 // 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
2025 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2026 continue;
2027 }
2028
2029 $account->$field = $this->_checkValForAPI($field, $value, $account);
2030 }
2031
2032 if ($account->create(DolibarrApiAccess::$user) < 0) {
2033 throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!');
2034 }
2035
2036 $this->_cleanObjectDatas($account);
2037
2038 return $account;
2039 } else {
2040 throw new RestException(409, 'A SocieteAccount entity already exists for this company and site.');
2041 }
2042 }
2043
2070 public function postSocieteAccount($id, $site, $request_data = null)
2071 {
2072 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2073 throw new RestException(403);
2074 }
2075
2076 $sql = "SELECT rowid, fk_user_creat, date_creation FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
2077 $result = $this->db->query($sql);
2078
2079 // We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one.
2080 if ($result && $this->db->num_rows($result) == 0) {
2081 if (!isset($request_data['key_account'])) {
2082 throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !');
2083 }
2084 $account = new SocieteAccount($this->db);
2085 if (!isset($request_data['login'])) {
2086 $account->login = "";
2087 }
2088
2089 foreach ($request_data as $field => $value) {
2090 if ($field === 'caller') {
2091 // 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
2092 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2093 continue;
2094 }
2095
2096 $account->$field = $this->_checkValForAPI($field, $value, $account);
2097 }
2098
2099 $account->fk_soc = $id;
2100 $account->site = $site;
2101
2102 if ($account->create(DolibarrApiAccess::$user) < 0) {
2103 throw new RestException(500, 'Error creating SocieteAccount entity.');
2104 }
2105 // We found an existing SocieteAccount entity, we are replacing it
2106 } else {
2107 if (isset($request_data['site']) && $request_data['site'] !== $site) {
2108 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
2109 $result = $this->db->query($sql);
2110
2111 if ($result && $this->db->num_rows($result) !== 0) {
2112 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.");
2113 }
2114 }
2115
2116 $obj = $this->db->fetch_object($result);
2117
2118 $account = new SocieteAccount($this->db);
2119 $account->id = $obj->rowid;
2120 $account->fk_soc = $id;
2121 $account->site = $site;
2122 if (!isset($request_data['login'])) {
2123 $account->login = "";
2124 }
2125 $account->fk_user_creat = $obj->fk_user_creat;
2126 $account->date_creation = $obj->date_creation;
2127
2128 foreach ($request_data as $field => $value) {
2129 if ($field === 'caller') {
2130 // 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
2131 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2132 continue;
2133 }
2134
2135 $account->$field = $this->_checkValForAPI($field, $value, $account);
2136 }
2137
2138 if ($account->update(DolibarrApiAccess::$user) < 0) {
2139 throw new RestException(500, 'Error updating SocieteAccount entity.');
2140 }
2141 }
2142
2143 $this->_cleanObjectDatas($account);
2144
2145 return $account;
2146 }
2147
2168 public function putSocieteAccount($id, $site, $request_data = null)
2169 {
2170 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2171 throw new RestException(403);
2172 }
2173
2174 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($site)."'";
2175 $result = $this->db->query($sql);
2176
2177 if ($result && $this->db->num_rows($result) == 0) {
2178 throw new RestException(404, "This thirdparty does not have $site account attached or does not exist.");
2179 } else {
2180 // If the user tries to edit the site member, we check first if
2181 if (isset($request_data['site']) && $request_data['site'] !== $site) {
2182 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id)." AND site = '".$this->db->escape($request_data['site'])."' ";
2183 $result = $this->db->query($sql);
2184
2185 if ($result && $this->db->num_rows($result) !== 0) {
2186 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.");
2187 }
2188 }
2189
2190 $obj = $this->db->fetch_object($result);
2191 $account = new SocieteAccount($this->db);
2192 $account->fetch($obj->rowid);
2193
2194 foreach ($request_data as $field => $value) {
2195 if ($field === 'caller') {
2196 // 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
2197 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
2198 continue;
2199 }
2200
2201 $account->$field = $this->_checkValForAPI($field, $value, $account);
2202 }
2203
2204 if ($account->update(DolibarrApiAccess::$user) < 0) {
2205 throw new RestException(500, 'Error updating SocieteAccount account');
2206 }
2207
2208 $this->_cleanObjectDatas($account);
2209
2210 return $account;
2211 }
2212 }
2213
2232 public function deleteSocieteAccount($id, $site)
2233 {
2234 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2235 throw new RestException(403);
2236 }
2237
2238 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '".$this->db->escape($site)."'";
2239 $result = $this->db->query($sql);
2240
2241 if ($result && $this->db->num_rows($result) == 0) {
2242 throw new RestException(404);
2243 } else {
2244 $obj = $this->db->fetch_object($result);
2245 $account = new SocieteAccount($this->db);
2246 $account->fetch($obj->rowid);
2247
2248 if ($account->delete(DolibarrApiAccess::$user) < 0) {
2249 throw new RestException(500, "Error while deleting $site account attached to this third party");
2250 }
2251 }
2252 }
2253
2270 {
2271 if (!DolibarrApiAccess::$user->hasRight('societe', 'creer')) {
2272 throw new RestException(403);
2273 }
2274
2279 $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms";
2280 $sql .= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".((int) $id);
2281
2282 $result = $this->db->query($sql);
2283
2284 if ($result && $this->db->num_rows($result) == 0) {
2285 throw new RestException(404, 'This third party does not have any account attached or does not exist.');
2286 } else {
2287 $i = 0;
2288
2289 $num = $this->db->num_rows($result);
2290 while ($i < $num) {
2291 $obj = $this->db->fetch_object($result);
2292 $account = new SocieteAccount($this->db);
2293 $account->fetch($obj->rowid);
2294
2295 if ($account->delete(DolibarrApiAccess::$user) < 0) {
2296 throw new RestException(500, 'Error while deleting account attached to this third party');
2297 }
2298 $i++;
2299 }
2300 }
2301 }
2302
2303 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2310 protected function _cleanObjectDatas($object)
2311 {
2312 // phpcs:enable
2313 $object = parent::_cleanObjectDatas($object);
2314
2315 unset($object->nom); // ->name already defined and nom deprecated
2316 unset($object->name_bis); // ->name_alias already defined
2317 unset($object->note); // ->note_private and note_public already defined
2318 unset($object->departement);
2319 unset($object->departement_code);
2320 unset($object->pays);
2321 unset($object->particulier);
2322 unset($object->prefix_comm);
2323
2324 unset($object->siren);
2325 unset($object->siret);
2326 unset($object->ape);
2327
2328 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.
2329
2330 unset($object->total_ht);
2331 unset($object->total_tva);
2332 unset($object->total_localtax1);
2333 unset($object->total_localtax2);
2334 unset($object->total_ttc);
2335
2336 unset($object->lines);
2337 unset($object->thirdparty);
2338
2339 unset($object->fk_delivery_address); // deprecated feature
2340
2341 return $object;
2342 }
2343
2352 private function _validate($data)
2353 {
2354 if ($data === null) {
2355 $data = array();
2356 }
2357 $thirdparty = array();
2358 foreach (Thirdparties::$FIELDS as $field) {
2359 if (!isset($data[$field])) {
2360 throw new RestException(400, "$field field missing");
2361 }
2362 $thirdparty[$field] = $data[$field];
2363 }
2364 return $thirdparty;
2365 }
2366
2390 private function _fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
2391 {
2392 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
2393 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.'. No read permission on thirdparties.');
2394 }
2395
2396 if ($rowid === 0) {
2397 $result = $this->company->initAsSpecimen();
2398 } else {
2399 $result = $this->company->fetch((int) $rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
2400 }
2401 if (!$result) {
2402 throw new RestException(404, 'Thirdparty not found');
2403 }
2404
2405 if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
2406 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login.' on this thirdparty');
2407 }
2408 if (isModEnabled('mailing')) {
2409 $this->company->getNoEmail();
2410 }
2411
2412 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
2413 $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
2414 $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
2415 } else {
2416 $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
2417 $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
2418 }
2419
2420 $absolute_discount = $this->company->getAvailableDiscounts(null, $filterabsolutediscount);
2421 $absolute_creditnote = $this->company->getAvailableDiscounts(null, $filtercreditnote);
2422 $this->company->absolute_discount = price2num($absolute_discount, 'MT');
2423 $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
2424
2425 return $this->_cleanObjectDatas($this->company);
2426 }
2427}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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:33
_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:98
Class to manage invoices.
Class to manage the table of subscription to notifications.
Class for SocieteAccount.
Class to manage third parties objects (customers, suppliers, prospects...)
updateCompanyNotification($id, $notification_id, $request_data=null)
Update a company notification for a third party.
setThirdpartyPriceLevel($id, $priceLevel)
Set a new price level for the given third party.
_cleanObjectDatas($object)
Clean sensible object datas.
getSocieteByAccounts($site, $key_account)
Get a specific third party by account.
getSupplierCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get supplier categories for a third party.
deleteCompanyNotification($id, $notification_id)
Delete a company notification attached to a third party.
getSocieteAccounts($id, $site=null)
Get a specific account attached to a third party.
getOutStandingOrder($id, $mode='customer')
Get outstanding orders for a third party.
addRepresentative($id, $representative_id)
Add a customer representative to a third party.
getByBarcode($barcode)
Get a third party by barcode.
generateBankAccountDocument($id, $companybankid=null, $model='sepamandate')
Generate a document from a bank account record.
createCompanyNotificationByCode($id, $code, $request_data=null)
Create a company notification for a third party using action trigger code.
getCompanyNotification($id)
Get company notifications for a third party.
addCategory($id, $category_id)
Add a customer category to a third party.
getCompanyBankAccount($id)
Get company bank accounts of a third party.
getInvoicesQualifiedForReplacement($id)
Return invoices qualified to be replaced by another invoice.
post($request_data=null)
Create a third party.
put($id, $request_data=null)
Update third party.
getByEmail($email)
Get properties of a third party by email.
_validate($data)
Validate fields before create or update object.
addSupplierCategory($id, $category_id)
Add a supplier category to a third party.
merge($id, $idtodelete)
Merge a third party into another third party.
deleteSocieteAccounts($id)
Delete all accounts attached to a third party.
__construct()
Constructor.
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get customer categories for a third party.
postSocieteAccount($id, $site, $request_data=null)
Create and attach a new (or replace an existing) specific site account for a third party.
deleteSupplierCategory($id, $category_id)
Remove the link between a category and the third party.
deleteRepresentative($id, $representative_id)
Remove the link between a customer representative and a third party.
createCompanyNotification($id, $request_data=null)
Create a company notification for a third party.
putSocieteAccount($id, $site, $request_data=null)
Update specified values of a specific account attached to a third party.
updateCompanyBankAccount($id, $bankaccount_id, $request_data=null)
Update a company bank account of a third party.
deleteSocieteAccount($id, $site)
Delete a specific site account attached to a third party.
getInvoicesQualifiedForCreditNote($id)
Return invoices qualified to be corrected by a credit note.
getFixedAmountDiscounts($id, $filter="none", $sortfield="f.type", $sortorder='ASC')
Get fixed amount discount of a third party.
getOutStandingProposals($id, $mode='customer')
Get outstanding proposals for a third party.
_fetch($rowid, $ref='', $ref_ext='', $barcode='', $idprof1='', $idprof2='', $idprof3='', $idprof4='', $idprof5='', $idprof6='', $email='', $ref_alias='')
Fetch properties of a thirdparty object.
getSalesRepresentatives($id, $mode=0)
Get representatives of a third party.
getOutStandingInvoices($id, $mode='customer')
Get outstanding invoices for a third party.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $mode=0, $category=0, $sqlfilters='', $properties='', $pagination_data=false)
List third parties.
deleteCompanyBankAccount($id, $bankaccount_id)
Delete a bank account attached to a third party.
createSocieteAccount($id, $request_data=null)
Create and attach a new account to an existing third party.
createCompanyBankAccount($id, $request_data=null)
Create a company bank account for a third party.
deleteCategory($id, $category_id)
Remove the link between a customer category and the third party.
Class to manage translations.
Class to manage Dolibarr users.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.