dolibarr 18.0.8
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
338 public function createInvoiceFromOrder($orderid)
339 {
340 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
341
342 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
343 throw new RestException(401);
344 }
345 if (!DolibarrApiAccess::$user->rights->facture->creer) {
346 throw new RestException(401);
347 }
348 if (empty($orderid)) {
349 throw new RestException(400, 'Order ID is mandatory');
350 }
351 if (!DolibarrApi::_checkAccessToResource('commande', $orderid)) {
352 throw new RestException(403, 'Access not allowed on order for login '.DolibarrApiAccess::$user->login);
353 }
354
355 $order = new Commande($this->db);
356 $result = $order->fetch($orderid);
357 if (!$result) {
358 throw new RestException(404, 'Order not found');
359 }
360
361 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
362 if ($result < 0) {
363 throw new RestException(405, $this->invoice->error);
364 }
365 $this->invoice->fetchObjectLinked();
366 return $this->_cleanObjectDatas($this->invoice);
367 }
368
377 public function getLines($id)
378 {
379 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
380 throw new RestException(401);
381 }
382
383 $result = $this->invoice->fetch($id);
384 if (!$result) {
385 throw new RestException(404, 'Invoice not found');
386 }
387
388 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
389 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
390 }
391 $this->invoice->getLinesArray();
392 $result = array();
393 foreach ($this->invoice->lines as $line) {
394 array_push($result, $this->_cleanObjectDatas($line));
395 }
396 return $result;
397 }
398
413 public function putLine($id, $lineid, $request_data = null)
414 {
415 if (!DolibarrApiAccess::$user->rights->facture->creer) {
416 throw new RestException(401);
417 }
418
419 $result = $this->invoice->fetch($id);
420 if (!$result) {
421 throw new RestException(404, 'Invoice not found');
422 }
423
424 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
425 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
426 }
427
428 $request_data = (object) $request_data;
429
430 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
431 $request_data->label = sanitizeVal($request_data->label);
432
433 $updateRes = $this->invoice->updateline(
434 $lineid,
435 $request_data->desc,
436 $request_data->subprice,
437 $request_data->qty,
438 $request_data->remise_percent,
439 $request_data->date_start,
440 $request_data->date_end,
441 $request_data->tva_tx,
442 $request_data->localtax1_tx,
443 $request_data->localtax2_tx,
444 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
445 $request_data->info_bits,
446 $request_data->product_type,
447 $request_data->fk_parent_line,
448 0,
449 $request_data->fk_fournprice,
450 $request_data->pa_ht,
451 $request_data->label,
452 $request_data->special_code,
453 $request_data->array_options,
454 $request_data->situation_percent,
455 $request_data->fk_unit,
456 $request_data->multicurrency_subprice,
457 0,
458 $request_data->ref_ext,
459 $request_data->rang
460 );
461
462 if ($updateRes > 0) {
463 $result = $this->get($id);
464 unset($result->line);
465 return $this->_cleanObjectDatas($result);
466 } else {
467 throw new RestException(304, $this->invoice->error);
468 }
469 }
470
484 public function postContact($id, $contactid, $type)
485 {
486 if (!DolibarrApiAccess::$user->rights->facture->creer) {
487 throw new RestException(401);
488 }
489
490 $result = $this->invoice->fetch($id);
491
492 if (!$result) {
493 throw new RestException(404, 'Invoice not found');
494 }
495
496 if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) {
497 throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER');
498 }
499
500 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
501 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
502 }
503
504 $result = $this->invoice->add_contact($contactid, $type, 'external');
505
506 if (!$result) {
507 throw new RestException(500, 'Error when added the contact');
508 }
509
510 return array(
511 'success' => array(
512 'code' => 200,
513 'message' => 'Contact linked to the invoice'
514 )
515 );
516 }
517
532 public function deleteContact($id, $contactid, $type)
533 {
534 if (!DolibarrApiAccess::$user->rights->facture->creer) {
535 throw new RestException(401);
536 }
537
538 $result = $this->invoice->fetch($id);
539
540 if (!$result) {
541 throw new RestException(404, 'Invoice not found');
542 }
543
544 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
545 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
546 }
547
548 $contacts = $this->invoice->liste_contact();
549
550 foreach ($contacts as $contact) {
551 if ($contact['id'] == $contactid && $contact['code'] == $type) {
552 $result = $this->invoice->delete_contact($contact['rowid']);
553
554 if (!$result) {
555 throw new RestException(500, 'Error when deleted the contact');
556 }
557 }
558 }
559
560 return $this->_cleanObjectDatas($this->invoice);
561 }
562
577 public function deleteLine($id, $lineid)
578 {
579 if (!DolibarrApiAccess::$user->rights->facture->creer) {
580 throw new RestException(401);
581 }
582 if (empty($lineid)) {
583 throw new RestException(400, 'Line ID is mandatory');
584 }
585
586 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
587 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
588 }
589
590 $result = $this->invoice->fetch($id);
591 if (!$result) {
592 throw new RestException(404, 'Invoice not found');
593 }
594
595 $updateRes = $this->invoice->deleteline($lineid, $id);
596 if ($updateRes > 0) {
597 return $this->get($id);
598 } else {
599 throw new RestException(405, $this->invoice->error);
600 }
601 }
602
610 public function put($id, $request_data = null)
611 {
612 if (!DolibarrApiAccess::$user->rights->facture->creer) {
613 throw new RestException(401);
614 }
615
616 $result = $this->invoice->fetch($id);
617 if (!$result) {
618 throw new RestException(404, 'Invoice not found');
619 }
620
621 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
622 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
623 }
624
625 foreach ($request_data as $field => $value) {
626 if ($field == 'id') {
627 continue;
628 }
629 if ($field == 'array_options' && is_array($value)) {
630 foreach ($value as $index => $val) {
631 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
632 }
633 continue;
634 }
635 $this->invoice->$field = $value;
636 }
637
638 // update bank account
639 if (!empty($this->invoice->fk_account)) {
640 if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) {
641 throw new RestException(400, $this->invoice->error);
642 }
643 }
644
645 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
646 return $this->get($id);
647 } else {
648 throw new RestException(500, $this->invoice->error);
649 }
650 }
651
658 public function delete($id)
659 {
660 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
661 throw new RestException(401);
662 }
663 $result = $this->invoice->fetch($id);
664 if (!$result) {
665 throw new RestException(404, 'Invoice not found');
666 }
667
668 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
669 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
670 }
671
672 $result = $this->invoice->delete(DolibarrApiAccess::$user);
673 if ($result < 0) {
674 throw new RestException(500, 'Error when deleting invoice');
675 } elseif ($result == 0) {
676 throw new RestException(403, 'Invoice not erasable');
677 }
678
679 return array(
680 'success' => array(
681 'code' => 200,
682 'message' => 'Invoice deleted'
683 )
684 );
685 }
686
710 public function postLine($id, $request_data = null)
711 {
712 if (!DolibarrApiAccess::$user->rights->facture->creer) {
713 throw new RestException(401);
714 }
715
716 $result = $this->invoice->fetch($id);
717 if (!$result) {
718 throw new RestException(404, 'Invoice not found');
719 }
720
721 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
722 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
723 }
724
725 $request_data = (object) $request_data;
726
727 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
728 $request_data->label = sanitizeVal($request_data->label);
729
730 // Reset fk_parent_line for no child products and special product
731 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
732 $request_data->fk_parent_line = 0;
733 }
734
735 // calculate pa_ht
736 $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);
737 $pa_ht = $marginInfos[0];
738
739 $updateRes = $this->invoice->addline(
740 $request_data->desc,
741 $request_data->subprice,
742 $request_data->qty,
743 $request_data->tva_tx,
744 $request_data->localtax1_tx,
745 $request_data->localtax2_tx,
746 $request_data->fk_product,
747 $request_data->remise_percent,
748 $request_data->date_start,
749 $request_data->date_end,
750 $request_data->fk_code_ventilation,
751 $request_data->info_bits,
752 $request_data->fk_remise_except,
753 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
754 $request_data->subprice,
755 $request_data->product_type,
756 $request_data->rang,
757 $request_data->special_code,
758 $request_data->origin,
759 $request_data->origin_id,
760 $request_data->fk_parent_line,
761 empty($request_data->fk_fournprice) ?null:$request_data->fk_fournprice,
762 $pa_ht,
763 $request_data->label,
764 $request_data->array_options,
765 $request_data->situation_percent,
766 $request_data->fk_prev_id,
767 $request_data->fk_unit,
768 0,
769 $request_data->ref_ext
770 );
771
772 if ($updateRes < 0) {
773 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
774 }
775
776 return $updateRes;
777 }
778
798 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
799 {
800 if (!DolibarrApiAccess::$user->rights->facture->creer) {
801 throw new RestException(401);
802 }
803 $result = $this->invoice->fetch($id);
804 if (!$result) {
805 throw new RestException(404, 'Invoice not found');
806 }
807
808 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
809 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
810 }
811
812 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
813 if ($result < 0) {
814 throw new RestException(500, 'Error : '.$this->invoice->error);
815 }
816
817 $result = $this->invoice->fetch($id);
818 if (!$result) {
819 throw new RestException(404, 'Invoice not found');
820 }
821
822 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
823 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
824 }
825
826 return $this->_cleanObjectDatas($this->invoice);
827 }
828
829
830
846 public function settodraft($id, $idwarehouse = -1)
847 {
848 if (!DolibarrApiAccess::$user->rights->facture->creer) {
849 throw new RestException(401);
850 }
851 $result = $this->invoice->fetch($id);
852 if (!$result) {
853 throw new RestException(404, 'Invoice not found');
854 }
855
856 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
857 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
858 }
859
860 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
861 if ($result == 0) {
862 throw new RestException(304, 'Nothing done.');
863 }
864 if ($result < 0) {
865 throw new RestException(500, 'Error : '.$this->invoice->error);
866 }
867
868 $result = $this->invoice->fetch($id);
869 if (!$result) {
870 throw new RestException(404, 'Invoice not found');
871 }
872
873 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
874 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
875 }
876
877 return $this->_cleanObjectDatas($this->invoice);
878 }
879
880
897 public function validate($id, $idwarehouse = 0, $notrigger = 0)
898 {
899 if (!DolibarrApiAccess::$user->rights->facture->creer) {
900 throw new RestException(401);
901 }
902 $result = $this->invoice->fetch($id);
903 if (!$result) {
904 throw new RestException(404, 'Invoice not found');
905 }
906
907 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
908 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
909 }
910
911 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
912 if ($result == 0) {
913 throw new RestException(304, 'Error nothing done. May be object is already validated');
914 }
915 if ($result < 0) {
916 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
917 }
918
919 $result = $this->invoice->fetch($id);
920 if (!$result) {
921 throw new RestException(404, 'Invoice not found');
922 }
923
924 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
925 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
926 }
927
928 return $this->_cleanObjectDatas($this->invoice);
929 }
930
946 public function settopaid($id, $close_code = '', $close_note = '')
947 {
948 if (!DolibarrApiAccess::$user->rights->facture->creer) {
949 throw new RestException(401);
950 }
951 $result = $this->invoice->fetch($id);
952 if (!$result) {
953 throw new RestException(404, 'Invoice not found');
954 }
955
956 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
957 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
958 }
959
960 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
961 if ($result == 0) {
962 throw new RestException(304, 'Error nothing done. May be object is already validated');
963 }
964 if ($result < 0) {
965 throw new RestException(500, 'Error : '.$this->invoice->error);
966 }
967
968
969 $result = $this->invoice->fetch($id);
970 if (!$result) {
971 throw new RestException(404, 'Invoice not found');
972 }
973
974 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
975 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
976 }
977
978 return $this->_cleanObjectDatas($this->invoice);
979 }
980
981
995 public function settounpaid($id)
996 {
997 if (!DolibarrApiAccess::$user->rights->facture->creer) {
998 throw new RestException(401);
999 }
1000 $result = $this->invoice->fetch($id);
1001 if (!$result) {
1002 throw new RestException(404, 'Invoice not found');
1003 }
1004
1005 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1006 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1007 }
1008
1009 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1010 if ($result == 0) {
1011 throw new RestException(304, 'Nothing done');
1012 }
1013 if ($result < 0) {
1014 throw new RestException(500, 'Error : '.$this->invoice->error);
1015 }
1016
1017
1018 $result = $this->invoice->fetch($id);
1019 if (!$result) {
1020 throw new RestException(404, 'Invoice not found');
1021 }
1022
1023 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1024 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1025 }
1026
1027 return $this->_cleanObjectDatas($this->invoice);
1028 }
1029
1038 public function getDiscount($id)
1039 {
1040 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1041
1042 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1043 throw new RestException(401);
1044 }
1045
1046 $result = $this->invoice->fetch($id);
1047 if (!$result) {
1048 throw new RestException(404, 'Invoice not found');
1049 }
1050
1051 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1052 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1053 }
1054
1055 $discountcheck = new DiscountAbsolute($this->db);
1056 $result = $discountcheck->fetch(0, $this->invoice->id);
1057
1058 if ($result == 0) {
1059 throw new RestException(404, 'Discount not found');
1060 }
1061 if ($result < 0) {
1062 throw new RestException(500, $discountcheck->error);
1063 }
1064
1065 return parent::_cleanObjectDatas($discountcheck);
1066 }
1067
1081 public function markAsCreditAvailable($id)
1082 {
1083 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1084
1085 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1086 throw new RestException(401);
1087 }
1088
1089 $result = $this->invoice->fetch($id);
1090 if (!$result) {
1091 throw new RestException(404, 'Invoice not found');
1092 }
1093
1094 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1095 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1096 }
1097
1098 if ($this->invoice->paye) {
1099 throw new RestException(500, 'Alreay paid');
1100 }
1101
1102 $this->invoice->fetch($id);
1103 $this->invoice->fetch_thirdparty();
1104
1105 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1106 $discountcheck = new DiscountAbsolute($this->db);
1107 $result = $discountcheck->fetch(0, $this->invoice->id);
1108
1109 $canconvert = 0;
1110 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1111 $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)
1112 }
1113 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1114 $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)
1115 }
1116 if ($canconvert) {
1117 $this->db->begin();
1118
1119 $amount_ht = $amount_tva = $amount_ttc = array();
1120 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1121
1122 // Loop on each vat rate
1123 $i = 0;
1124 foreach ($this->invoice->lines as $line) {
1125 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1126 // no need to create discount if amount is null
1127 $amount_ht[$line->tva_tx] += $line->total_ht;
1128 $amount_tva[$line->tva_tx] += $line->total_tva;
1129 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1130 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1131 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1132 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1133 $i++;
1134 }
1135 }
1136
1137 // Insert one discount by VAT rate category
1138 $discount = new DiscountAbsolute($this->db);
1139 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1140 $discount->description = '(CREDIT_NOTE)';
1141 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1142 $discount->description = '(DEPOSIT)';
1143 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1144 $discount->description = '(EXCESS RECEIVED)';
1145 } else {
1146 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1147 }
1148
1149 $discount->fk_soc = $this->invoice->socid;
1150 $discount->fk_facture_source = $this->invoice->id;
1151
1152 $error = 0;
1153
1154 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1155 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1156
1157 // Total payments
1158 $sql = 'SELECT SUM(pf.amount) as total_payments';
1159 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1160 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1161 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1162 $sql .= ' AND pf.fk_paiement = p.rowid';
1163 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1164 $resql = $this->db->query($sql);
1165 if (!$resql) {
1166 dol_print_error($this->db);
1167 }
1168
1169 $res = $this->db->fetch_object($resql);
1170 $total_payments = $res->total_payments;
1171
1172 // Total credit note and deposit
1173 $total_creditnote_and_deposit = 0;
1174 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1175 $sql .= " re.description, re.fk_facture_source";
1176 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1177 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1178 $resql = $this->db->query($sql);
1179 if (!empty($resql)) {
1180 while ($obj = $this->db->fetch_object($resql)) {
1181 $total_creditnote_and_deposit += $obj->amount_ttc;
1182 }
1183 } else {
1184 dol_print_error($this->db);
1185 }
1186
1187 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1188 $discount->amount_tva = 0;
1189 $discount->tva_tx = 0;
1190
1191 $result = $discount->create(DolibarrApiAccess::$user);
1192 if ($result < 0) {
1193 $error++;
1194 }
1195 }
1196 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1197 foreach ($amount_ht as $tva_tx => $xxx) {
1198 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1199 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1200 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1201 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1202 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1203 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1204 $discount->tva_tx = abs($tva_tx);
1205
1206 $result = $discount->create(DolibarrApiAccess::$user);
1207 if ($result < 0) {
1208 $error++;
1209 break;
1210 }
1211 }
1212 }
1213
1214 if (empty($error)) {
1215 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1216 // Classe facture
1217 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1218 if ($result >= 0) {
1219 $this->db->commit();
1220 } else {
1221 $this->db->rollback();
1222 throw new RestException(500, 'Could not set paid');
1223 }
1224 } else {
1225 $this->db->commit();
1226 }
1227 } else {
1228 $this->db->rollback();
1229 throw new RestException(500, 'Discount creation error');
1230 }
1231 }
1232
1233 return $this->_cleanObjectDatas($this->invoice);
1234 }
1235
1252 public function useDiscount($id, $discountid)
1253 {
1254 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1255 throw new RestException(401);
1256 }
1257 if (empty($id)) {
1258 throw new RestException(400, 'Invoice ID is mandatory');
1259 }
1260 if (empty($discountid)) {
1261 throw new RestException(400, 'Discount ID is mandatory');
1262 }
1263
1264 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1265 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1266 }
1267
1268 $result = $this->invoice->fetch($id);
1269 if (!$result) {
1270 throw new RestException(404, 'Invoice not found');
1271 }
1272
1273 $result = $this->invoice->insert_discount($discountid);
1274 if ($result < 0) {
1275 throw new RestException(405, $this->invoice->error);
1276 }
1277
1278 return $result;
1279 }
1280
1297 public function useCreditNote($id, $discountid)
1298 {
1299 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1300
1301 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1302 throw new RestException(401);
1303 }
1304 if (empty($id)) {
1305 throw new RestException(400, 'Invoice ID is mandatory');
1306 }
1307 if (empty($discountid)) {
1308 throw new RestException(400, 'Credit ID is mandatory');
1309 }
1310
1311 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1312 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1313 }
1314 $discount = new DiscountAbsolute($this->db);
1315 $result = $discount->fetch($discountid);
1316 if (!$result) {
1317 throw new RestException(404, 'Credit not found');
1318 }
1319
1320 $result = $discount->link_to_invoice(0, $id);
1321 if ($result < 0) {
1322 throw new RestException(405, $discount->error);
1323 }
1324
1325 return $result;
1326 }
1327
1341 public function getPayments($id)
1342 {
1343
1344 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1345 throw new RestException(401);
1346 }
1347 if (empty($id)) {
1348 throw new RestException(400, 'Invoice ID is mandatory');
1349 }
1350
1351 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1352 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1353 }
1354
1355 $result = $this->invoice->fetch($id);
1356 if (!$result) {
1357 throw new RestException(404, 'Invoice not found');
1358 }
1359
1360 $result = $this->invoice->getListOfPayments();
1361 if ($result < 0) {
1362 throw new RestException(405, $this->invoice->error);
1363 }
1364
1365 return $result;
1366 }
1367
1368
1390 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1391 {
1392 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1393
1394 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1395 throw new RestException(403);
1396 }
1397 if (empty($id)) {
1398 throw new RestException(400, 'Invoice ID is mandatory');
1399 }
1400
1401 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1402 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1403 }
1404
1405 if (isModEnabled("banque")) {
1406 if (empty($accountid)) {
1407 throw new RestException(400, 'Account ID is mandatory');
1408 }
1409 }
1410
1411 if (empty($paymentid)) {
1412 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1413 }
1414
1415
1416 $result = $this->invoice->fetch($id);
1417 if (!$result) {
1418 throw new RestException(404, 'Invoice not found');
1419 }
1420
1421 // Calculate amount to pay
1422 $totalpaid = $this->invoice->getSommePaiement();
1423 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1424 $totaldeposits = $this->invoice->getSumDepositsUsed();
1425 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1426
1427 $this->db->begin();
1428
1429 $amounts = array();
1430 $multicurrency_amounts = array();
1431
1432 // Clean parameters amount if payment is for a credit note
1433 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1434 $resteapayer = price2num($resteapayer, 'MT');
1435 $amounts[$id] = -$resteapayer;
1436 // Multicurrency
1437 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1438 $multicurrency_amounts[$id] = -$newvalue;
1439 } else {
1440 $resteapayer = price2num($resteapayer, 'MT');
1441 $amounts[$id] = $resteapayer;
1442 // Multicurrency
1443 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1444 $multicurrency_amounts[$id] = $newvalue;
1445 }
1446
1447 // Creation of payment line
1448 $paymentobj = new Paiement($this->db);
1449 $paymentobj->datepaye = $datepaye;
1450 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1451 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1452 $paymentobj->paiementid = $paymentid;
1453 $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1);
1454 $paymentobj->num_payment = $num_payment;
1455 $paymentobj->note_private = $comment;
1456
1457 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1458 if ($payment_id < 0) {
1459 $this->db->rollback();
1460 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1461 }
1462
1463 if (isModEnabled("banque")) {
1464 $label = '(CustomerInvoicePayment)';
1465
1466 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1467 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1468 }
1469 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1470 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1471 }
1472 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1473 if ($result < 0) {
1474 $this->db->rollback();
1475 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1476 }
1477 }
1478
1479 $this->db->commit();
1480
1481 return $payment_id;
1482 }
1483
1510 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1511 {
1512 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1513
1514 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1515 throw new RestException(403);
1516 }
1517 foreach ($arrayofamounts as $id => $amount) {
1518 if (empty($id)) {
1519 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1520 }
1521 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1522 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1523 }
1524 }
1525
1526 if (isModEnabled("banque")) {
1527 if (empty($accountid)) {
1528 throw new RestException(400, 'Account ID is mandatory');
1529 }
1530 }
1531 if (empty($paymentid)) {
1532 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1533 }
1534
1535 $this->db->begin();
1536
1537 $amounts = array();
1538 $multicurrency_amounts = array();
1539
1540 // Loop on each invoice to pay
1541 foreach ($arrayofamounts as $id => $amountarray) {
1542 $result = $this->invoice->fetch($id);
1543 if (!$result) {
1544 $this->db->rollback();
1545 throw new RestException(404, 'Invoice ID '.$id.' not found');
1546 }
1547
1548 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1549 $this->db->rollback();
1550 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1551 }
1552
1553 $is_multicurrency = 0;
1554 $total_ttc = $this->invoice->total_ttc;
1555
1556 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1557 $is_multicurrency = 1;
1558 $total_ttc = $this->invoice->multicurrency_total_ttc;
1559 }
1560
1561 // Calculate amount to pay
1562 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1563 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1564 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1565 $remainstopay = $amount = price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1566
1567 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1568 $amount = price2num($amountarray["amount"], 'MT');
1569 }
1570
1571 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1572 $amount = price2num($amountarray["multicurrency_amount"], 'MT');
1573 }
1574
1575 if (abs($amount) > abs($remainstopay) && !$accepthigherpayment) {
1576 $this->db->rollback();
1577 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1578 }
1579
1580 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1581 $amount = - abs($amount);
1582 }
1583
1584 if ($is_multicurrency) {
1585 $amounts[$id] = null;
1586 // Multicurrency
1587 $multicurrency_amounts[$id] = $amount;
1588 } else {
1589 $amounts[$id] = $amount;
1590 // Multicurrency
1591 $multicurrency_amounts[$id] = null;
1592 }
1593 }
1594
1595 // Creation of payment line
1596 $paymentobj = new Paiement($this->db);
1597 $paymentobj->datepaye = $datepaye;
1598 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1599 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1600 $paymentobj->paiementid = $paymentid;
1601 $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1);
1602 $paymentobj->num_payment = $num_payment;
1603 $paymentobj->note_private = $comment;
1604 $paymentobj->ref_ext = $ref_ext;
1605 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1606 if ($payment_id < 0) {
1607 $this->db->rollback();
1608 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1609 }
1610 if (isModEnabled("banque")) {
1611 $label = '(CustomerInvoicePayment)';
1612 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1613 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1614 }
1615 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1616 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1617 }
1618 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1619 if ($result < 0) {
1620 $this->db->rollback();
1621 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1622 }
1623 }
1624
1625 $this->db->commit();
1626
1627 return $payment_id;
1628 }
1629
1644 public function putPayment($id, $num_payment = '')
1645 {
1646 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1647
1648 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1649 throw new RestException(401);
1650 }
1651 if (empty($id)) {
1652 throw new RestException(400, 'Payment ID is mandatory');
1653 }
1654
1655 $paymentobj = new Paiement($this->db);
1656 $result = $paymentobj->fetch($id);
1657
1658 if (!$result) {
1659 throw new RestException(404, 'Payment not found');
1660 }
1661
1662 if (!empty($num_payment)) {
1663 $result = $paymentobj->update_num($num_payment);
1664 if ($result < 0) {
1665 throw new RestException(500, 'Error when updating the payment num');
1666 }
1667 }
1668
1669 return [
1670 'success' => [
1671 'code' => 200,
1672 'message' => 'Payment updated'
1673 ]
1674 ];
1675 }
1676
1677 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1684 protected function _cleanObjectDatas($object)
1685 {
1686 // phpcs:enable
1687 $object = parent::_cleanObjectDatas($object);
1688
1689 unset($object->note);
1690 unset($object->address);
1691 unset($object->barcode_type);
1692 unset($object->barcode_type_code);
1693 unset($object->barcode_type_label);
1694 unset($object->barcode_type_coder);
1695 unset($object->canvas);
1696
1697 return $object;
1698 }
1699
1708 private function _validate($data)
1709 {
1710 $invoice = array();
1711 foreach (Invoices::$FIELDS as $field) {
1712 if (!isset($data[$field])) {
1713 throw new RestException(400, "$field field missing");
1714 }
1715 $invoice[$field] = $data[$field];
1716 }
1717 return $invoice;
1718 }
1719
1720
1734 public function getTemplateInvoice($id, $contact_list = 1)
1735 {
1736 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
1737 }
1738
1752 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
1753 {
1754 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1755 throw new RestException(401);
1756 }
1757
1758 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
1759 if (!$result) {
1760 throw new RestException(404, 'Template invoice not found');
1761 }
1762
1763 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
1764 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1765 }
1766
1767 // Add external contacts ids
1768 if ($contact_list > -1) {
1769 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
1770 if (is_array($tmparray)) {
1771 $this->template_invoice->contacts_ids = $tmparray;
1772 }
1773 }
1774
1775 $this->template_invoice->fetchObjectLinked();
1776 return $this->_cleanTemplateObjectDatas($this->template_invoice);
1777 }
1778
1779
1780 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1787 protected function _cleanTemplateObjectDatas($object)
1788 {
1789 // phpcs:enable
1790 $object = parent::_cleanObjectDatas($object);
1791
1792 unset($object->note);
1793 unset($object->address);
1794 unset($object->barcode_type);
1795 unset($object->barcode_type_code);
1796 unset($object->barcode_type_label);
1797 unset($object->barcode_type_coder);
1798 unset($object->canvas);
1799
1800 return $object;
1801 }
1802}
Class to manage customers orders.
Class to manage absolute discounts.
Class for API REST v1.
Definition api.class.php:32
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:87
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.