dolibarr 18.0.6
api_invoices.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2020 Thibault FOUCART <support@ptibogxiv.net>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
22require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
23
24
31class Invoices extends DolibarrApi
32{
37 static $FIELDS = array(
38 'socid',
39 );
40
44 private $invoice;
45
49 private $template_invoice;
50
51
55 public function __construct()
56 {
57 global $db, $conf;
58 $this->db = $db;
59 $this->invoice = new Facture($this->db);
60 $this->template_invoice = new FactureRec($this->db);
61 }
62
74 public function get($id, $contact_list = 1)
75 {
76 return $this->_fetch($id, '', '', $contact_list);
77 }
78
92 public function getByRef($ref, $contact_list = 1)
93 {
94 return $this->_fetch('', $ref, '', $contact_list);
95 }
96
110 public function getByRefExt($ref_ext, $contact_list = 1)
111 {
112 return $this->_fetch('', '', $ref_ext, $contact_list);
113 }
114
128 private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1)
129 {
130 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
131 throw new RestException(401);
132 }
133
134 $result = $this->invoice->fetch($id, $ref, $ref_ext);
135 if (!$result) {
136 throw new RestException(404, 'Invoice not found');
137 }
138
139 // Get payment details
140 $this->invoice->totalpaid = $this->invoice->getSommePaiement();
141 $this->invoice->totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
142 $this->invoice->totaldeposits = $this->invoice->getSumDepositsUsed();
143 $this->invoice->remaintopay = price2num($this->invoice->total_ttc - $this->invoice->totalpaid - $this->invoice->totalcreditnotes - $this->invoice->totaldeposits, 'MT');
144
145 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
146 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
147 }
148
149 // Add external contacts ids
150 if ($contact_list > -1) {
151 $tmparray = $this->invoice->liste_contact(-1, 'external', $contact_list);
152 if (is_array($tmparray)) {
153 $this->invoice->contacts_ids = $tmparray;
154 }
155 }
156
157 $this->invoice->fetchObjectLinked();
158
159 return $this->_cleanObjectDatas($this->invoice);
160 }
161
179 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '')
180 {
181 global $db, $conf;
182
183 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
184 throw new RestException(401);
185 }
186
187 $obj_ret = array();
188
189 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
190 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
191
192 // If the internal user must only see his customers, force searching by him
193 $search_sale = 0;
194 if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
195 $search_sale = DolibarrApiAccess::$user->id;
196 }
197
198 $sql = "SELECT t.rowid";
199 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
200 $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
201 }
202 $sql .= " FROM ".MAIN_DB_PREFIX."facture AS t LEFT JOIN ".MAIN_DB_PREFIX."facture_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
203
204 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
205 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
206 }
207
208 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
209 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
210 $sql .= " AND t.fk_soc = sc.fk_soc";
211 }
212 if ($socids) {
213 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
214 }
215
216 if ($search_sale > 0) {
217 $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
218 }
219
220 // Filter by status
221 if ($status == 'draft') {
222 $sql .= " AND t.fk_statut IN (0)";
223 }
224 if ($status == 'unpaid') {
225 $sql .= " AND t.fk_statut IN (1)";
226 }
227 if ($status == 'paid') {
228 $sql .= " AND t.fk_statut IN (2)";
229 }
230 if ($status == 'cancelled') {
231 $sql .= " AND t.fk_statut IN (3)";
232 }
233 // Insert sale filter
234 if ($search_sale > 0) {
235 $sql .= " AND sc.fk_user = ".((int) $search_sale);
236 }
237 // Add sql filters
238 if ($sqlfilters) {
239 $errormessage = '';
240 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
241 if ($errormessage) {
242 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
243 }
244 }
245
246 $sql .= $this->db->order($sortfield, $sortorder);
247 if ($limit) {
248 if ($page < 0) {
249 $page = 0;
250 }
251 $offset = $limit * $page;
252
253 $sql .= $this->db->plimit($limit + 1, $offset);
254 }
255
256 $result = $this->db->query($sql);
257 if ($result) {
258 $i = 0;
259 $num = $this->db->num_rows($result);
260 $min = min($num, ($limit <= 0 ? $num : $limit));
261 while ($i < $min) {
262 $obj = $this->db->fetch_object($result);
263 $invoice_static = new Facture($this->db);
264 if ($invoice_static->fetch($obj->rowid)) {
265 // Get payment details
266 $invoice_static->totalpaid = $invoice_static->getSommePaiement();
267 $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed();
268 $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
269 $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT');
270
271 // Add external contacts ids
272 $tmparray = $invoice_static->liste_contact(-1, 'external', 1);
273 if (is_array($tmparray)) {
274 $invoice_static->contacts_ids = $tmparray;
275 }
276 $obj_ret[] = $this->_cleanObjectDatas($invoice_static);
277 }
278 $i++;
279 }
280 } else {
281 throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror());
282 }
283 if (!count($obj_ret)) {
284 throw new RestException(404, 'No invoice found');
285 }
286 return $obj_ret;
287 }
288
295 public function post($request_data = null)
296 {
297 if (!DolibarrApiAccess::$user->rights->facture->creer) {
298 throw new RestException(401, "Insuffisant rights");
299 }
300 // Check mandatory fields
301 $result = $this->_validate($request_data);
302
303 foreach ($request_data as $field => $value) {
304 $this->invoice->$field = $value;
305 }
306 if (!array_key_exists('date', $request_data)) {
307 $this->invoice->date = dol_now();
308 }
309 /* We keep lines as an array
310 if (isset($request_data["lines"])) {
311 $lines = array();
312 foreach ($request_data["lines"] as $line) {
313 array_push($lines, (object) $line);
314 }
315 $this->invoice->lines = $lines;
316 }*/
317
318 if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) {
319 throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors));
320 }
321 return ((int) $this->invoice->id);
322 }
323
337 public function createInvoiceFromOrder($orderid)
338 {
339 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
340
341 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
342 throw new RestException(401);
343 }
344 if (!DolibarrApiAccess::$user->rights->facture->creer) {
345 throw new RestException(401);
346 }
347 if (empty($orderid)) {
348 throw new RestException(400, 'Order ID is mandatory');
349 }
350
351 $order = new Commande($this->db);
352 $result = $order->fetch($orderid);
353 if (!$result) {
354 throw new RestException(404, 'Order not found');
355 }
356
357 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
358 if ($result < 0) {
359 throw new RestException(405, $this->invoice->error);
360 }
361 $this->invoice->fetchObjectLinked();
362 return $this->_cleanObjectDatas($this->invoice);
363 }
364
373 public function getLines($id)
374 {
375 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
376 throw new RestException(401);
377 }
378
379 $result = $this->invoice->fetch($id);
380 if (!$result) {
381 throw new RestException(404, 'Invoice not found');
382 }
383
384 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
385 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
386 }
387 $this->invoice->getLinesArray();
388 $result = array();
389 foreach ($this->invoice->lines as $line) {
390 array_push($result, $this->_cleanObjectDatas($line));
391 }
392 return $result;
393 }
394
409 public function putLine($id, $lineid, $request_data = null)
410 {
411 if (!DolibarrApiAccess::$user->rights->facture->creer) {
412 throw new RestException(401);
413 }
414
415 $result = $this->invoice->fetch($id);
416 if (!$result) {
417 throw new RestException(404, 'Invoice not found');
418 }
419
420 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
421 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
422 }
423
424 $request_data = (object) $request_data;
425
426 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
427 $request_data->label = sanitizeVal($request_data->label);
428
429 $updateRes = $this->invoice->updateline(
430 $lineid,
431 $request_data->desc,
432 $request_data->subprice,
433 $request_data->qty,
434 $request_data->remise_percent,
435 $request_data->date_start,
436 $request_data->date_end,
437 $request_data->tva_tx,
438 $request_data->localtax1_tx,
439 $request_data->localtax2_tx,
440 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
441 $request_data->info_bits,
442 $request_data->product_type,
443 $request_data->fk_parent_line,
444 0,
445 $request_data->fk_fournprice,
446 $request_data->pa_ht,
447 $request_data->label,
448 $request_data->special_code,
449 $request_data->array_options,
450 $request_data->situation_percent,
451 $request_data->fk_unit,
452 $request_data->multicurrency_subprice,
453 0,
454 $request_data->ref_ext,
455 $request_data->rang
456 );
457
458 if ($updateRes > 0) {
459 $result = $this->get($id);
460 unset($result->line);
461 return $this->_cleanObjectDatas($result);
462 } else {
463 throw new RestException(304, $this->invoice->error);
464 }
465 }
466
480 public function postContact($id, $contactid, $type)
481 {
482 if (!DolibarrApiAccess::$user->rights->facture->creer) {
483 throw new RestException(401);
484 }
485
486 $result = $this->invoice->fetch($id);
487
488 if (!$result) {
489 throw new RestException(404, 'Invoice not found');
490 }
491
492 if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) {
493 throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER');
494 }
495
496 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
497 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
498 }
499
500 $result = $this->invoice->add_contact($contactid, $type, 'external');
501
502 if (!$result) {
503 throw new RestException(500, 'Error when added the contact');
504 }
505
506 return array(
507 'success' => array(
508 'code' => 200,
509 'message' => 'Contact linked to the invoice'
510 )
511 );
512 }
513
528 public function deleteContact($id, $contactid, $type)
529 {
530 if (!DolibarrApiAccess::$user->rights->facture->creer) {
531 throw new RestException(401);
532 }
533
534 $result = $this->invoice->fetch($id);
535
536 if (!$result) {
537 throw new RestException(404, 'Invoice not found');
538 }
539
540 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
541 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
542 }
543
544 $contacts = $this->invoice->liste_contact();
545
546 foreach ($contacts as $contact) {
547 if ($contact['id'] == $contactid && $contact['code'] == $type) {
548 $result = $this->invoice->delete_contact($contact['rowid']);
549
550 if (!$result) {
551 throw new RestException(500, 'Error when deleted the contact');
552 }
553 }
554 }
555
556 return $this->_cleanObjectDatas($this->invoice);
557 }
558
573 public function deleteLine($id, $lineid)
574 {
575 if (!DolibarrApiAccess::$user->rights->facture->creer) {
576 throw new RestException(401);
577 }
578 if (empty($lineid)) {
579 throw new RestException(400, 'Line ID is mandatory');
580 }
581
582 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
583 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
584 }
585
586 $result = $this->invoice->fetch($id);
587 if (!$result) {
588 throw new RestException(404, 'Invoice not found');
589 }
590
591 $updateRes = $this->invoice->deleteline($lineid, $id);
592 if ($updateRes > 0) {
593 return $this->get($id);
594 } else {
595 throw new RestException(405, $this->invoice->error);
596 }
597 }
598
606 public function put($id, $request_data = null)
607 {
608 if (!DolibarrApiAccess::$user->rights->facture->creer) {
609 throw new RestException(401);
610 }
611
612 $result = $this->invoice->fetch($id);
613 if (!$result) {
614 throw new RestException(404, 'Invoice not found');
615 }
616
617 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
618 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
619 }
620
621 foreach ($request_data as $field => $value) {
622 if ($field == 'id') {
623 continue;
624 }
625 if ($field == 'array_options' && is_array($value)) {
626 foreach ($value as $index => $val) {
627 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
628 }
629 continue;
630 }
631 $this->invoice->$field = $value;
632 }
633
634 // update bank account
635 if (!empty($this->invoice->fk_account)) {
636 if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) {
637 throw new RestException(400, $this->invoice->error);
638 }
639 }
640
641 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
642 return $this->get($id);
643 } else {
644 throw new RestException(500, $this->invoice->error);
645 }
646 }
647
654 public function delete($id)
655 {
656 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
657 throw new RestException(401);
658 }
659 $result = $this->invoice->fetch($id);
660 if (!$result) {
661 throw new RestException(404, 'Invoice not found');
662 }
663
664 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
665 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
666 }
667
668 $result = $this->invoice->delete(DolibarrApiAccess::$user);
669 if ($result < 0) {
670 throw new RestException(500, 'Error when deleting invoice');
671 } elseif ($result == 0) {
672 throw new RestException(403, 'Invoice not erasable');
673 }
674
675 return array(
676 'success' => array(
677 'code' => 200,
678 'message' => 'Invoice deleted'
679 )
680 );
681 }
682
706 public function postLine($id, $request_data = null)
707 {
708 if (!DolibarrApiAccess::$user->rights->facture->creer) {
709 throw new RestException(401);
710 }
711
712 $result = $this->invoice->fetch($id);
713 if (!$result) {
714 throw new RestException(404, 'Invoice not found');
715 }
716
717 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
718 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
719 }
720
721 $request_data = (object) $request_data;
722
723 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
724 $request_data->label = sanitizeVal($request_data->label);
725
726 // Reset fk_parent_line for no child products and special product
727 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
728 $request_data->fk_parent_line = 0;
729 }
730
731 // calculate pa_ht
732 $marginInfos = getMarginInfos($request_data->subprice, $request_data->remise_percent, $request_data->tva_tx, $request_data->localtax1_tx, $request_data->localtax2_tx, $request_data->fk_fournprice, $request_data->pa_ht);
733 $pa_ht = $marginInfos[0];
734
735 $updateRes = $this->invoice->addline(
736 $request_data->desc,
737 $request_data->subprice,
738 $request_data->qty,
739 $request_data->tva_tx,
740 $request_data->localtax1_tx,
741 $request_data->localtax2_tx,
742 $request_data->fk_product,
743 $request_data->remise_percent,
744 $request_data->date_start,
745 $request_data->date_end,
746 $request_data->fk_code_ventilation,
747 $request_data->info_bits,
748 $request_data->fk_remise_except,
749 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
750 $request_data->subprice,
751 $request_data->product_type,
752 $request_data->rang,
753 $request_data->special_code,
754 $request_data->origin,
755 $request_data->origin_id,
756 $request_data->fk_parent_line,
757 empty($request_data->fk_fournprice) ?null:$request_data->fk_fournprice,
758 $pa_ht,
759 $request_data->label,
760 $request_data->array_options,
761 $request_data->situation_percent,
762 $request_data->fk_prev_id,
763 $request_data->fk_unit,
764 0,
765 $request_data->ref_ext
766 );
767
768 if ($updateRes < 0) {
769 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
770 }
771
772 return $updateRes;
773 }
774
794 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
795 {
796 if (!DolibarrApiAccess::$user->rights->facture->creer) {
797 throw new RestException(401);
798 }
799 $result = $this->invoice->fetch($id);
800 if (!$result) {
801 throw new RestException(404, 'Invoice not found');
802 }
803
804 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
805 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
806 }
807
808 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
809 if ($result < 0) {
810 throw new RestException(500, 'Error : '.$this->invoice->error);
811 }
812
813 $result = $this->invoice->fetch($id);
814 if (!$result) {
815 throw new RestException(404, 'Invoice not found');
816 }
817
818 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
819 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
820 }
821
822 return $this->_cleanObjectDatas($this->invoice);
823 }
824
825
826
842 public function settodraft($id, $idwarehouse = -1)
843 {
844 if (!DolibarrApiAccess::$user->rights->facture->creer) {
845 throw new RestException(401);
846 }
847 $result = $this->invoice->fetch($id);
848 if (!$result) {
849 throw new RestException(404, 'Invoice not found');
850 }
851
852 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
853 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
854 }
855
856 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
857 if ($result == 0) {
858 throw new RestException(304, 'Nothing done.');
859 }
860 if ($result < 0) {
861 throw new RestException(500, 'Error : '.$this->invoice->error);
862 }
863
864 $result = $this->invoice->fetch($id);
865 if (!$result) {
866 throw new RestException(404, 'Invoice not found');
867 }
868
869 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
870 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
871 }
872
873 return $this->_cleanObjectDatas($this->invoice);
874 }
875
876
893 public function validate($id, $idwarehouse = 0, $notrigger = 0)
894 {
895 if (!DolibarrApiAccess::$user->rights->facture->creer) {
896 throw new RestException(401);
897 }
898 $result = $this->invoice->fetch($id);
899 if (!$result) {
900 throw new RestException(404, 'Invoice not found');
901 }
902
903 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
904 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
905 }
906
907 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
908 if ($result == 0) {
909 throw new RestException(304, 'Error nothing done. May be object is already validated');
910 }
911 if ($result < 0) {
912 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
913 }
914
915 $result = $this->invoice->fetch($id);
916 if (!$result) {
917 throw new RestException(404, 'Invoice not found');
918 }
919
920 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
921 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
922 }
923
924 return $this->_cleanObjectDatas($this->invoice);
925 }
926
942 public function settopaid($id, $close_code = '', $close_note = '')
943 {
944 if (!DolibarrApiAccess::$user->rights->facture->creer) {
945 throw new RestException(401);
946 }
947 $result = $this->invoice->fetch($id);
948 if (!$result) {
949 throw new RestException(404, 'Invoice not found');
950 }
951
952 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
953 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
954 }
955
956 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
957 if ($result == 0) {
958 throw new RestException(304, 'Error nothing done. May be object is already validated');
959 }
960 if ($result < 0) {
961 throw new RestException(500, 'Error : '.$this->invoice->error);
962 }
963
964
965 $result = $this->invoice->fetch($id);
966 if (!$result) {
967 throw new RestException(404, 'Invoice not found');
968 }
969
970 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
971 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
972 }
973
974 return $this->_cleanObjectDatas($this->invoice);
975 }
976
977
991 public function settounpaid($id)
992 {
993 if (!DolibarrApiAccess::$user->rights->facture->creer) {
994 throw new RestException(401);
995 }
996 $result = $this->invoice->fetch($id);
997 if (!$result) {
998 throw new RestException(404, 'Invoice not found');
999 }
1000
1001 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1002 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1003 }
1004
1005 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1006 if ($result == 0) {
1007 throw new RestException(304, 'Nothing done');
1008 }
1009 if ($result < 0) {
1010 throw new RestException(500, 'Error : '.$this->invoice->error);
1011 }
1012
1013
1014 $result = $this->invoice->fetch($id);
1015 if (!$result) {
1016 throw new RestException(404, 'Invoice not found');
1017 }
1018
1019 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1020 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1021 }
1022
1023 return $this->_cleanObjectDatas($this->invoice);
1024 }
1025
1034 public function getDiscount($id)
1035 {
1036 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1037
1038 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1039 throw new RestException(401);
1040 }
1041
1042 $result = $this->invoice->fetch($id);
1043 if (!$result) {
1044 throw new RestException(404, 'Invoice not found');
1045 }
1046
1047 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1048 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1049 }
1050
1051 $discountcheck = new DiscountAbsolute($this->db);
1052 $result = $discountcheck->fetch(0, $this->invoice->id);
1053
1054 if ($result == 0) {
1055 throw new RestException(404, 'Discount not found');
1056 }
1057 if ($result < 0) {
1058 throw new RestException(500, $discountcheck->error);
1059 }
1060
1061 return parent::_cleanObjectDatas($discountcheck);
1062 }
1063
1077 public function markAsCreditAvailable($id)
1078 {
1079 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1080
1081 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1082 throw new RestException(401);
1083 }
1084
1085 $result = $this->invoice->fetch($id);
1086 if (!$result) {
1087 throw new RestException(404, 'Invoice not found');
1088 }
1089
1090 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1091 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1092 }
1093
1094 if ($this->invoice->paye) {
1095 throw new RestException(500, 'Alreay paid');
1096 }
1097
1098 $this->invoice->fetch($id);
1099 $this->invoice->fetch_thirdparty();
1100
1101 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1102 $discountcheck = new DiscountAbsolute($this->db);
1103 $result = $discountcheck->fetch(0, $this->invoice->id);
1104
1105 $canconvert = 0;
1106 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1107 $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
1108 }
1109 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1110 $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
1111 }
1112 if ($canconvert) {
1113 $this->db->begin();
1114
1115 $amount_ht = $amount_tva = $amount_ttc = array();
1116 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1117
1118 // Loop on each vat rate
1119 $i = 0;
1120 foreach ($this->invoice->lines as $line) {
1121 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1122 // no need to create discount if amount is null
1123 $amount_ht[$line->tva_tx] += $line->total_ht;
1124 $amount_tva[$line->tva_tx] += $line->total_tva;
1125 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1126 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1127 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1128 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1129 $i++;
1130 }
1131 }
1132
1133 // Insert one discount by VAT rate category
1134 $discount = new DiscountAbsolute($this->db);
1135 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1136 $discount->description = '(CREDIT_NOTE)';
1137 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1138 $discount->description = '(DEPOSIT)';
1139 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1140 $discount->description = '(EXCESS RECEIVED)';
1141 } else {
1142 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1143 }
1144
1145 $discount->fk_soc = $this->invoice->socid;
1146 $discount->fk_facture_source = $this->invoice->id;
1147
1148 $error = 0;
1149
1150 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1151 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1152
1153 // Total payments
1154 $sql = 'SELECT SUM(pf.amount) as total_payments';
1155 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1156 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1157 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1158 $sql .= ' AND pf.fk_paiement = p.rowid';
1159 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1160 $resql = $this->db->query($sql);
1161 if (!$resql) {
1162 dol_print_error($this->db);
1163 }
1164
1165 $res = $this->db->fetch_object($resql);
1166 $total_payments = $res->total_payments;
1167
1168 // Total credit note and deposit
1169 $total_creditnote_and_deposit = 0;
1170 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1171 $sql .= " re.description, re.fk_facture_source";
1172 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1173 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1174 $resql = $this->db->query($sql);
1175 if (!empty($resql)) {
1176 while ($obj = $this->db->fetch_object($resql)) {
1177 $total_creditnote_and_deposit += $obj->amount_ttc;
1178 }
1179 } else {
1180 dol_print_error($this->db);
1181 }
1182
1183 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1184 $discount->amount_tva = 0;
1185 $discount->tva_tx = 0;
1186
1187 $result = $discount->create(DolibarrApiAccess::$user);
1188 if ($result < 0) {
1189 $error++;
1190 }
1191 }
1192 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1193 foreach ($amount_ht as $tva_tx => $xxx) {
1194 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1195 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1196 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1197 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1198 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1199 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1200 $discount->tva_tx = abs($tva_tx);
1201
1202 $result = $discount->create(DolibarrApiAccess::$user);
1203 if ($result < 0) {
1204 $error++;
1205 break;
1206 }
1207 }
1208 }
1209
1210 if (empty($error)) {
1211 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1212 // Classe facture
1213 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1214 if ($result >= 0) {
1215 $this->db->commit();
1216 } else {
1217 $this->db->rollback();
1218 throw new RestException(500, 'Could not set paid');
1219 }
1220 } else {
1221 $this->db->commit();
1222 }
1223 } else {
1224 $this->db->rollback();
1225 throw new RestException(500, 'Discount creation error');
1226 }
1227 }
1228
1229 return $this->_cleanObjectDatas($this->invoice);
1230 }
1231
1248 public function useDiscount($id, $discountid)
1249 {
1250 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1251 throw new RestException(401);
1252 }
1253 if (empty($id)) {
1254 throw new RestException(400, 'Invoice ID is mandatory');
1255 }
1256 if (empty($discountid)) {
1257 throw new RestException(400, 'Discount ID is mandatory');
1258 }
1259
1260 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1261 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1262 }
1263
1264 $result = $this->invoice->fetch($id);
1265 if (!$result) {
1266 throw new RestException(404, 'Invoice not found');
1267 }
1268
1269 $result = $this->invoice->insert_discount($discountid);
1270 if ($result < 0) {
1271 throw new RestException(405, $this->invoice->error);
1272 }
1273
1274 return $result;
1275 }
1276
1293 public function useCreditNote($id, $discountid)
1294 {
1295 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1296
1297 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1298 throw new RestException(401);
1299 }
1300 if (empty($id)) {
1301 throw new RestException(400, 'Invoice ID is mandatory');
1302 }
1303 if (empty($discountid)) {
1304 throw new RestException(400, 'Credit ID is mandatory');
1305 }
1306
1307 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1308 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1309 }
1310 $discount = new DiscountAbsolute($this->db);
1311 $result = $discount->fetch($discountid);
1312 if (!$result) {
1313 throw new RestException(404, 'Credit not found');
1314 }
1315
1316 $result = $discount->link_to_invoice(0, $id);
1317 if ($result < 0) {
1318 throw new RestException(405, $discount->error);
1319 }
1320
1321 return $result;
1322 }
1323
1337 public function getPayments($id)
1338 {
1339
1340 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1341 throw new RestException(401);
1342 }
1343 if (empty($id)) {
1344 throw new RestException(400, 'Invoice ID is mandatory');
1345 }
1346
1347 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1348 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1349 }
1350
1351 $result = $this->invoice->fetch($id);
1352 if (!$result) {
1353 throw new RestException(404, 'Invoice not found');
1354 }
1355
1356 $result = $this->invoice->getListOfPayments();
1357 if ($result < 0) {
1358 throw new RestException(405, $this->invoice->error);
1359 }
1360
1361 return $result;
1362 }
1363
1364
1386 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1387 {
1388 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1389
1390 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1391 throw new RestException(403);
1392 }
1393 if (empty($id)) {
1394 throw new RestException(400, 'Invoice ID is mandatory');
1395 }
1396
1397 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1398 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1399 }
1400
1401 if (isModEnabled("banque")) {
1402 if (empty($accountid)) {
1403 throw new RestException(400, 'Account ID is mandatory');
1404 }
1405 }
1406
1407 if (empty($paymentid)) {
1408 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1409 }
1410
1411
1412 $result = $this->invoice->fetch($id);
1413 if (!$result) {
1414 throw new RestException(404, 'Invoice not found');
1415 }
1416
1417 // Calculate amount to pay
1418 $totalpaid = $this->invoice->getSommePaiement();
1419 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1420 $totaldeposits = $this->invoice->getSumDepositsUsed();
1421 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1422
1423 $this->db->begin();
1424
1425 $amounts = array();
1426 $multicurrency_amounts = array();
1427
1428 // Clean parameters amount if payment is for a credit note
1429 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1430 $resteapayer = price2num($resteapayer, 'MT');
1431 $amounts[$id] = -$resteapayer;
1432 // Multicurrency
1433 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1434 $multicurrency_amounts[$id] = -$newvalue;
1435 } else {
1436 $resteapayer = price2num($resteapayer, 'MT');
1437 $amounts[$id] = $resteapayer;
1438 // Multicurrency
1439 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1440 $multicurrency_amounts[$id] = $newvalue;
1441 }
1442
1443 // Creation of payment line
1444 $paymentobj = new Paiement($this->db);
1445 $paymentobj->datepaye = $datepaye;
1446 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1447 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1448 $paymentobj->paiementid = $paymentid;
1449 $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1);
1450 $paymentobj->num_payment = $num_payment;
1451 $paymentobj->note_private = $comment;
1452
1453 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1454 if ($payment_id < 0) {
1455 $this->db->rollback();
1456 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1457 }
1458
1459 if (isModEnabled("banque")) {
1460 $label = '(CustomerInvoicePayment)';
1461
1462 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1463 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1464 }
1465 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1466 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1467 }
1468 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1469 if ($result < 0) {
1470 $this->db->rollback();
1471 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1472 }
1473 }
1474
1475 $this->db->commit();
1476
1477 return $payment_id;
1478 }
1479
1506 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1507 {
1508 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1509
1510 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1511 throw new RestException(403);
1512 }
1513 foreach ($arrayofamounts as $id => $amount) {
1514 if (empty($id)) {
1515 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1516 }
1517 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1518 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1519 }
1520 }
1521
1522 if (isModEnabled("banque")) {
1523 if (empty($accountid)) {
1524 throw new RestException(400, 'Account ID is mandatory');
1525 }
1526 }
1527 if (empty($paymentid)) {
1528 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1529 }
1530
1531 $this->db->begin();
1532
1533 $amounts = array();
1534 $multicurrency_amounts = array();
1535
1536 // Loop on each invoice to pay
1537 foreach ($arrayofamounts as $id => $amountarray) {
1538 $result = $this->invoice->fetch($id);
1539 if (!$result) {
1540 $this->db->rollback();
1541 throw new RestException(404, 'Invoice ID '.$id.' not found');
1542 }
1543
1544 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1545 $this->db->rollback();
1546 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1547 }
1548
1549 $is_multicurrency = 0;
1550 $total_ttc = $this->invoice->total_ttc;
1551
1552 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1553 $is_multicurrency = 1;
1554 $total_ttc = $this->invoice->multicurrency_total_ttc;
1555 }
1556
1557 // Calculate amount to pay
1558 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1559 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1560 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1561 $remainstopay = $amount = price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1562
1563 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1564 $amount = price2num($amountarray["amount"], 'MT');
1565 }
1566
1567 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1568 $amount = price2num($amountarray["multicurrency_amount"], 'MT');
1569 }
1570
1571 if ($amount > $remainstopay && !$accepthigherpayment) {
1572 $this->db->rollback();
1573 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1574 }
1575
1576 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1577 $amount = -$amount;
1578 }
1579
1580 if ($is_multicurrency) {
1581 $amounts[$id] = null;
1582 // Multicurrency
1583 $multicurrency_amounts[$id] = $amount;
1584 } else {
1585 $amounts[$id] = $amount;
1586 // Multicurrency
1587 $multicurrency_amounts[$id] = null;
1588 }
1589 }
1590
1591 // Creation of payment line
1592 $paymentobj = new Paiement($this->db);
1593 $paymentobj->datepaye = $datepaye;
1594 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1595 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1596 $paymentobj->paiementid = $paymentid;
1597 $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1);
1598 $paymentobj->num_payment = $num_payment;
1599 $paymentobj->note_private = $comment;
1600 $paymentobj->ref_ext = $ref_ext;
1601 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1602 if ($payment_id < 0) {
1603 $this->db->rollback();
1604 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1605 }
1606 if (isModEnabled("banque")) {
1607 $label = '(CustomerInvoicePayment)';
1608 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1609 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1610 }
1611 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1612 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1613 }
1614 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1615 if ($result < 0) {
1616 $this->db->rollback();
1617 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1618 }
1619 }
1620
1621 $this->db->commit();
1622
1623 return $payment_id;
1624 }
1625
1640 public function putPayment($id, $num_payment = '')
1641 {
1642 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1643
1644 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1645 throw new RestException(401);
1646 }
1647 if (empty($id)) {
1648 throw new RestException(400, 'Payment ID is mandatory');
1649 }
1650
1651 $paymentobj = new Paiement($this->db);
1652 $result = $paymentobj->fetch($id);
1653
1654 if (!$result) {
1655 throw new RestException(404, 'Payment not found');
1656 }
1657
1658 if (!empty($num_payment)) {
1659 $result = $paymentobj->update_num($num_payment);
1660 if ($result < 0) {
1661 throw new RestException(500, 'Error when updating the payment num');
1662 }
1663 }
1664
1665 return [
1666 'success' => [
1667 'code' => 200,
1668 'message' => 'Payment updated'
1669 ]
1670 ];
1671 }
1672
1673 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1680 protected function _cleanObjectDatas($object)
1681 {
1682 // phpcs:enable
1683 $object = parent::_cleanObjectDatas($object);
1684
1685 unset($object->note);
1686 unset($object->address);
1687 unset($object->barcode_type);
1688 unset($object->barcode_type_code);
1689 unset($object->barcode_type_label);
1690 unset($object->barcode_type_coder);
1691 unset($object->canvas);
1692
1693 return $object;
1694 }
1695
1704 private function _validate($data)
1705 {
1706 $invoice = array();
1707 foreach (Invoices::$FIELDS as $field) {
1708 if (!isset($data[$field])) {
1709 throw new RestException(400, "$field field missing");
1710 }
1711 $invoice[$field] = $data[$field];
1712 }
1713 return $invoice;
1714 }
1715
1716
1730 public function getTemplateInvoice($id, $contact_list = 1)
1731 {
1732 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
1733 }
1734
1748 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
1749 {
1750 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1751 throw new RestException(401);
1752 }
1753
1754 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
1755 if (!$result) {
1756 throw new RestException(404, 'Template invoice not found');
1757 }
1758
1759 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
1760 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1761 }
1762
1763 // Add external contacts ids
1764 if ($contact_list > -1) {
1765 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
1766 if (is_array($tmparray)) {
1767 $this->template_invoice->contacts_ids = $tmparray;
1768 }
1769 }
1770
1771 $this->template_invoice->fetchObjectLinked();
1772 return $this->_cleanTemplateObjectDatas($this->template_invoice);
1773 }
1774
1775
1776 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1783 protected function _cleanTemplateObjectDatas($object)
1784 {
1785 // phpcs:enable
1786 $object = parent::_cleanObjectDatas($object);
1787
1788 unset($object->note);
1789 unset($object->address);
1790 unset($object->barcode_type);
1791 unset($object->barcode_type_code);
1792 unset($object->barcode_type_label);
1793 unset($object->barcode_type_coder);
1794 unset($object->canvas);
1795
1796 return $object;
1797 }
1798}
Class to manage customers orders.
Class to manage absolute discounts.
Class for API REST v1.
Definition api.class.php:31
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:86
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoice templates.
postContact($id, $contactid, $type)
Add a contact type of given invoice.
putPayment($id, $num_payment='')
Update a payment.
addContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0)
Adds a contact to an invoice.
createInvoiceFromOrder($orderid)
Create an invoice using an existing order.
markAsCreditAvailable($id)
Create a discount (credit available) for a credit note or a deposit.
getDiscount($id)
Get discount from invoice.
__construct()
Constructor.
put($id, $request_data=null)
Update invoice.
getByRefExt($ref_ext, $contact_list=1)
Get properties of an invoice object by ref_ext.
_fetch($id, $ref='', $ref_ext='', $contact_list=1)
Get properties of an invoice object.
getByRef($ref, $contact_list=1)
Get properties of an invoice object by ref.
getPayments($id)
Get list of payments of a given invoice.
_cleanObjectDatas($object)
Clean sensible object datas.
post($request_data=null)
Create invoice object.
useDiscount($id, $discountid)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount.
settounpaid($id)
Sets an invoice as unpaid.
getTemplateInvoice($id, $contact_list=1)
Get properties of a template invoice object.
putLine($id, $lineid, $request_data=null)
Update a line to a given invoice.
getLines($id)
Get lines of an invoice.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='')
List invoices.
useCreditNote($id, $discountid)
Add an available credit note discount to payments of an existing invoice.
addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='', $ref_ext='', $accepthigherpayment=false)
Add a payment to pay partially or completely one or several invoices.
validate($id, $idwarehouse=0, $notrigger=0)
Validate an invoice.
_cleanTemplateObjectDatas($object)
Clean sensible object datas.
deleteContact($id, $contactid, $type)
Delete a contact type of given invoice.
postLine($id, $request_data=null)
Add a line to a given invoice.
_fetchTemplateInvoice($id, $ref='', $ref_ext='', $contact_list=1)
Get properties of an invoice object.
_validate($data)
Validate fields before create or update object.
addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='')
Add payment line to a specific invoice with the remain to pay as amount.
settopaid($id, $close_code='', $close_note='')
Sets an invoice as paid.
settodraft($id, $idwarehouse=-1)
Sets an invoice as draft.
deleteLine($id, $lineid)
Deletes a line of a given invoice.
Class to manage payments of customer invoices.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.