dolibarr 19.0.3
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 public 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
180 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '')
181 {
182 global $db, $conf;
183
184 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
185 throw new RestException(401);
186 }
187
188 $obj_ret = array();
189
190 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
191 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
192
193 // If the internal user must only see his customers, force searching by him
194 $search_sale = 0;
195 if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
196 $search_sale = DolibarrApiAccess::$user->id;
197 }
198
199 $sql = "SELECT t.rowid";
200 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
201 $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)
202 }
203 $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
204
205 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
206 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
207 }
208
209 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
210 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
211 $sql .= " AND t.fk_soc = sc.fk_soc";
212 }
213 if ($socids) {
214 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
215 }
216
217 if ($search_sale > 0) {
218 $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
219 }
220
221 // Filter by status
222 if ($status == 'draft') {
223 $sql .= " AND t.fk_statut IN (0)";
224 }
225 if ($status == 'unpaid') {
226 $sql .= " AND t.fk_statut IN (1)";
227 }
228 if ($status == 'paid') {
229 $sql .= " AND t.fk_statut IN (2)";
230 }
231 if ($status == 'cancelled') {
232 $sql .= " AND t.fk_statut IN (3)";
233 }
234 // Insert sale filter
235 if ($search_sale > 0) {
236 $sql .= " AND sc.fk_user = ".((int) $search_sale);
237 }
238 // Add sql filters
239 if ($sqlfilters) {
240 $errormessage = '';
241 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
242 if ($errormessage) {
243 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
244 }
245 }
246
247 $sql .= $this->db->order($sortfield, $sortorder);
248 if ($limit) {
249 if ($page < 0) {
250 $page = 0;
251 }
252 $offset = $limit * $page;
253
254 $sql .= $this->db->plimit($limit + 1, $offset);
255 }
256
257 $result = $this->db->query($sql);
258 if ($result) {
259 $i = 0;
260 $num = $this->db->num_rows($result);
261 $min = min($num, ($limit <= 0 ? $num : $limit));
262 while ($i < $min) {
263 $obj = $this->db->fetch_object($result);
264 $invoice_static = new Facture($this->db);
265 if ($invoice_static->fetch($obj->rowid)) {
266 // Get payment details
267 $invoice_static->totalpaid = $invoice_static->getSommePaiement();
268 $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed();
269 $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
270 $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT');
271
272 // Add external contacts ids
273 $tmparray = $invoice_static->liste_contact(-1, 'external', 1);
274 if (is_array($tmparray)) {
275 $invoice_static->contacts_ids = $tmparray;
276 }
277 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
278 }
279 $i++;
280 }
281 } else {
282 throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror());
283 }
284
285 return $obj_ret;
286 }
287
294 public function post($request_data = null)
295 {
296 if (!DolibarrApiAccess::$user->rights->facture->creer) {
297 throw new RestException(401, "Insuffisant rights");
298 }
299 // Check mandatory fields
300 $result = $this->_validate($request_data);
301
302 foreach ($request_data as $field => $value) {
303 if ($field === 'caller') {
304 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller
305 $this->invoice->context['caller'] = $request_data['caller'];
306 continue;
307 }
308
309 $this->invoice->$field = $value;
310 }
311 if (!array_key_exists('date', $request_data)) {
312 $this->invoice->date = dol_now();
313 }
314 /* We keep lines as an array
315 if (isset($request_data["lines"])) {
316 $lines = array();
317 foreach ($request_data["lines"] as $line) {
318 array_push($lines, (object) $line);
319 }
320 $this->invoice->lines = $lines;
321 }*/
322
323 if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) {
324 throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors));
325 }
326 return ((int) $this->invoice->id);
327 }
328
342 public function createInvoiceFromOrder($orderid)
343 {
344 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
345
346 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
347 throw new RestException(401);
348 }
349 if (!DolibarrApiAccess::$user->rights->facture->creer) {
350 throw new RestException(401);
351 }
352 if (empty($orderid)) {
353 throw new RestException(400, 'Order ID is mandatory');
354 }
355
356 $order = new Commande($this->db);
357 $result = $order->fetch($orderid);
358 if (!$result) {
359 throw new RestException(404, 'Order not found');
360 }
361
362 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
363 if ($result < 0) {
364 throw new RestException(405, $this->invoice->error);
365 }
366 $this->invoice->fetchObjectLinked();
367 return $this->_cleanObjectDatas($this->invoice);
368 }
369
378 public function getLines($id)
379 {
380 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
381 throw new RestException(401);
382 }
383
384 $result = $this->invoice->fetch($id);
385 if (!$result) {
386 throw new RestException(404, 'Invoice not found');
387 }
388
389 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
390 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
391 }
392 $this->invoice->getLinesArray();
393 $result = array();
394 foreach ($this->invoice->lines as $line) {
395 array_push($result, $this->_cleanObjectDatas($line));
396 }
397 return $result;
398 }
399
414 public function putLine($id, $lineid, $request_data = null)
415 {
416 if (!DolibarrApiAccess::$user->rights->facture->creer) {
417 throw new RestException(401);
418 }
419
420 $result = $this->invoice->fetch($id);
421 if (!$result) {
422 throw new RestException(404, 'Invoice not found');
423 }
424
425 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
426 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
427 }
428
429 $request_data = (object) $request_data;
430
431 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
432 $request_data->label = sanitizeVal($request_data->label);
433
434 $updateRes = $this->invoice->updateline(
435 $lineid,
436 $request_data->desc,
437 $request_data->subprice,
438 $request_data->qty,
439 $request_data->remise_percent,
440 $request_data->date_start,
441 $request_data->date_end,
442 $request_data->tva_tx,
443 $request_data->localtax1_tx,
444 $request_data->localtax2_tx,
445 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
446 $request_data->info_bits,
447 $request_data->product_type,
448 $request_data->fk_parent_line,
449 0,
450 $request_data->fk_fournprice,
451 $request_data->pa_ht,
452 $request_data->label,
453 $request_data->special_code,
454 $request_data->array_options,
455 $request_data->situation_percent,
456 $request_data->fk_unit,
457 $request_data->multicurrency_subprice,
458 0,
459 $request_data->ref_ext,
460 $request_data->rang
461 );
462
463 if ($updateRes > 0) {
464 $result = $this->get($id);
465 unset($result->line);
466 return $this->_cleanObjectDatas($result);
467 } else {
468 throw new RestException(304, $this->invoice->error);
469 }
470 }
471
485 public function postContact($id, $contactid, $type)
486 {
487 if (!DolibarrApiAccess::$user->rights->facture->creer) {
488 throw new RestException(401);
489 }
490
491 $result = $this->invoice->fetch($id);
492
493 if (!$result) {
494 throw new RestException(404, 'Invoice not found');
495 }
496
497 if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) {
498 throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER');
499 }
500
501 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
502 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
503 }
504
505 $result = $this->invoice->add_contact($contactid, $type, 'external');
506
507 if (!$result) {
508 throw new RestException(500, 'Error when added the contact');
509 }
510
511 return array(
512 'success' => array(
513 'code' => 200,
514 'message' => 'Contact linked to the invoice'
515 )
516 );
517 }
518
533 public function deleteContact($id, $contactid, $type)
534 {
535 if (!DolibarrApiAccess::$user->rights->facture->creer) {
536 throw new RestException(401);
537 }
538
539 $result = $this->invoice->fetch($id);
540
541 if (!$result) {
542 throw new RestException(404, 'Invoice not found');
543 }
544
545 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
546 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
547 }
548
549 $contacts = $this->invoice->liste_contact();
550
551 foreach ($contacts as $contact) {
552 if ($contact['id'] == $contactid && $contact['code'] == $type) {
553 $result = $this->invoice->delete_contact($contact['rowid']);
554
555 if (!$result) {
556 throw new RestException(500, 'Error when deleted the contact');
557 }
558 }
559 }
560
561 return $this->_cleanObjectDatas($this->invoice);
562 }
563
578 public function deleteLine($id, $lineid)
579 {
580 if (!DolibarrApiAccess::$user->rights->facture->creer) {
581 throw new RestException(401);
582 }
583 if (empty($lineid)) {
584 throw new RestException(400, 'Line ID is mandatory');
585 }
586
587 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
588 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
589 }
590
591 $result = $this->invoice->fetch($id);
592 if (!$result) {
593 throw new RestException(404, 'Invoice not found');
594 }
595
596 $updateRes = $this->invoice->deleteline($lineid, $id);
597 if ($updateRes > 0) {
598 return $this->get($id);
599 } else {
600 throw new RestException(405, $this->invoice->error);
601 }
602 }
603
611 public function put($id, $request_data = null)
612 {
613 if (!DolibarrApiAccess::$user->rights->facture->creer) {
614 throw new RestException(401);
615 }
616
617 $result = $this->invoice->fetch($id);
618 if (!$result) {
619 throw new RestException(404, 'Invoice not found');
620 }
621
622 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
623 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
624 }
625
626 foreach ($request_data as $field => $value) {
627 if ($field == 'id') {
628 continue;
629 }
630 if ($field === 'caller') {
631 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller
632 $this->invoice->context['caller'] = $request_data['caller'];
633 continue;
634 }
635
636 $this->invoice->$field = $value;
637 }
638
639 // update bank account
640 if (!empty($this->invoice->fk_account)) {
641 if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) {
642 throw new RestException(400, $this->invoice->error);
643 }
644 }
645
646 if ($this->invoice->update(DolibarrApiAccess::$user)) {
647 return $this->get($id);
648 }
649
650 return false;
651 }
652
659 public function delete($id)
660 {
661 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
662 throw new RestException(401);
663 }
664 $result = $this->invoice->fetch($id);
665 if (!$result) {
666 throw new RestException(404, 'Invoice not found');
667 }
668
669 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
670 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
671 }
672
673 $result = $this->invoice->delete(DolibarrApiAccess::$user);
674 if ($result < 0) {
675 throw new RestException(500, 'Error when deleting invoice');
676 } elseif ($result == 0) {
677 throw new RestException(403, 'Invoice not erasable');
678 }
679
680 return array(
681 'success' => array(
682 'code' => 200,
683 'message' => 'Invoice deleted'
684 )
685 );
686 }
687
711 public function postLine($id, $request_data = null)
712 {
713 if (!DolibarrApiAccess::$user->rights->facture->creer) {
714 throw new RestException(401);
715 }
716
717 $result = $this->invoice->fetch($id);
718 if (!$result) {
719 throw new RestException(404, 'Invoice not found');
720 }
721
722 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
723 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
724 }
725
726 $request_data = (object) $request_data;
727
728 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
729 $request_data->label = sanitizeVal($request_data->label);
730
731 // Reset fk_parent_line for no child products and special product
732 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
733 $request_data->fk_parent_line = 0;
734 }
735
736 // calculate pa_ht
737 $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);
738 $pa_ht = $marginInfos[0];
739
740 $updateRes = $this->invoice->addline(
741 $request_data->desc,
742 $request_data->subprice,
743 $request_data->qty,
744 $request_data->tva_tx,
745 $request_data->localtax1_tx,
746 $request_data->localtax2_tx,
747 $request_data->fk_product,
748 $request_data->remise_percent,
749 $request_data->date_start,
750 $request_data->date_end,
751 $request_data->fk_code_ventilation,
752 $request_data->info_bits,
753 $request_data->fk_remise_except,
754 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
755 $request_data->subprice,
756 $request_data->product_type,
757 $request_data->rang,
758 $request_data->special_code,
759 $request_data->origin,
760 $request_data->origin_id,
761 $request_data->fk_parent_line,
762 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
763 $pa_ht,
764 $request_data->label,
765 $request_data->array_options,
766 $request_data->situation_percent,
767 $request_data->fk_prev_id,
768 $request_data->fk_unit,
769 0,
770 $request_data->ref_ext
771 );
772
773 if ($updateRes < 0) {
774 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
775 }
776
777 return $updateRes;
778 }
779
799 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
800 {
801 if (!DolibarrApiAccess::$user->rights->facture->creer) {
802 throw new RestException(401);
803 }
804 $result = $this->invoice->fetch($id);
805 if (!$result) {
806 throw new RestException(404, 'Invoice not found');
807 }
808
809 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
810 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
811 }
812
813 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
814 if ($result < 0) {
815 throw new RestException(500, 'Error : '.$this->invoice->error);
816 }
817
818 $result = $this->invoice->fetch($id);
819 if (!$result) {
820 throw new RestException(404, 'Invoice not found');
821 }
822
823 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
824 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
825 }
826
827 return $this->_cleanObjectDatas($this->invoice);
828 }
829
830
831
847 public function settodraft($id, $idwarehouse = -1)
848 {
849 if (!DolibarrApiAccess::$user->rights->facture->creer) {
850 throw new RestException(401);
851 }
852 $result = $this->invoice->fetch($id);
853 if (!$result) {
854 throw new RestException(404, 'Invoice not found');
855 }
856
857 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
858 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
859 }
860
861 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
862 if ($result == 0) {
863 throw new RestException(304, 'Nothing done.');
864 }
865 if ($result < 0) {
866 throw new RestException(500, 'Error : '.$this->invoice->error);
867 }
868
869 $result = $this->invoice->fetch($id);
870 if (!$result) {
871 throw new RestException(404, 'Invoice not found');
872 }
873
874 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
875 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
876 }
877
878 return $this->_cleanObjectDatas($this->invoice);
879 }
880
881
898 public function validate($id, $idwarehouse = 0, $notrigger = 0)
899 {
900 if (!DolibarrApiAccess::$user->rights->facture->creer) {
901 throw new RestException(401);
902 }
903 $result = $this->invoice->fetch($id);
904 if (!$result) {
905 throw new RestException(404, 'Invoice not found');
906 }
907
908 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
909 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
910 }
911
912 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
913 if ($result == 0) {
914 throw new RestException(304, 'Error nothing done. May be object is already validated');
915 }
916 if ($result < 0) {
917 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
918 }
919
920 $result = $this->invoice->fetch($id);
921 if (!$result) {
922 throw new RestException(404, 'Invoice not found');
923 }
924
925 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
926 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
927 }
928
929 return $this->_cleanObjectDatas($this->invoice);
930 }
931
947 public function settopaid($id, $close_code = '', $close_note = '')
948 {
949 if (!DolibarrApiAccess::$user->rights->facture->creer) {
950 throw new RestException(401);
951 }
952 $result = $this->invoice->fetch($id);
953 if (!$result) {
954 throw new RestException(404, 'Invoice not found');
955 }
956
957 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
958 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
959 }
960
961 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
962 if ($result == 0) {
963 throw new RestException(304, 'Error nothing done. May be object is already validated');
964 }
965 if ($result < 0) {
966 throw new RestException(500, 'Error : '.$this->invoice->error);
967 }
968
969
970 $result = $this->invoice->fetch($id);
971 if (!$result) {
972 throw new RestException(404, 'Invoice not found');
973 }
974
975 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
976 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
977 }
978
979 return $this->_cleanObjectDatas($this->invoice);
980 }
981
982
996 public function settounpaid($id)
997 {
998 if (!DolibarrApiAccess::$user->rights->facture->creer) {
999 throw new RestException(401);
1000 }
1001 $result = $this->invoice->fetch($id);
1002 if (!$result) {
1003 throw new RestException(404, 'Invoice not found');
1004 }
1005
1006 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1007 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1008 }
1009
1010 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1011 if ($result == 0) {
1012 throw new RestException(304, 'Nothing done');
1013 }
1014 if ($result < 0) {
1015 throw new RestException(500, 'Error : '.$this->invoice->error);
1016 }
1017
1018
1019 $result = $this->invoice->fetch($id);
1020 if (!$result) {
1021 throw new RestException(404, 'Invoice not found');
1022 }
1023
1024 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1025 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1026 }
1027
1028 return $this->_cleanObjectDatas($this->invoice);
1029 }
1030
1039 public function getDiscount($id)
1040 {
1041 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1042
1043 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1044 throw new RestException(401);
1045 }
1046
1047 $result = $this->invoice->fetch($id);
1048 if (!$result) {
1049 throw new RestException(404, 'Invoice not found');
1050 }
1051
1052 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1053 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1054 }
1055
1056 $discountcheck = new DiscountAbsolute($this->db);
1057 $result = $discountcheck->fetch(0, $this->invoice->id);
1058
1059 if ($result == 0) {
1060 throw new RestException(404, 'Discount not found');
1061 }
1062 if ($result < 0) {
1063 throw new RestException(500, $discountcheck->error);
1064 }
1065
1066 return parent::_cleanObjectDatas($discountcheck);
1067 }
1068
1082 public function markAsCreditAvailable($id)
1083 {
1084 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1085
1086 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1087 throw new RestException(401);
1088 }
1089
1090 $result = $this->invoice->fetch($id);
1091 if (!$result) {
1092 throw new RestException(404, 'Invoice not found');
1093 }
1094
1095 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1096 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1097 }
1098
1099 if ($this->invoice->paye) {
1100 throw new RestException(500, 'Alreay paid');
1101 }
1102
1103 $this->invoice->fetch($id);
1104 $this->invoice->fetch_thirdparty();
1105
1106 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1107 $discountcheck = new DiscountAbsolute($this->db);
1108 $result = $discountcheck->fetch(0, $this->invoice->id);
1109
1110 $canconvert = 0;
1111 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1112 $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)
1113 }
1114 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1115 $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)
1116 }
1117 if ($canconvert) {
1118 $this->db->begin();
1119
1120 $amount_ht = $amount_tva = $amount_ttc = array();
1121 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1122
1123 // Loop on each vat rate
1124 $i = 0;
1125 foreach ($this->invoice->lines as $line) {
1126 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1127 // no need to create discount if amount is null
1128 $amount_ht[$line->tva_tx] += $line->total_ht;
1129 $amount_tva[$line->tva_tx] += $line->total_tva;
1130 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1131 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1132 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1133 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1134 $i++;
1135 }
1136 }
1137
1138 // Insert one discount by VAT rate category
1139 $discount = new DiscountAbsolute($this->db);
1140 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1141 $discount->description = '(CREDIT_NOTE)';
1142 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1143 $discount->description = '(DEPOSIT)';
1144 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1145 $discount->description = '(EXCESS RECEIVED)';
1146 } else {
1147 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1148 }
1149
1150 $discount->fk_soc = $this->invoice->socid;
1151 $discount->fk_facture_source = $this->invoice->id;
1152
1153 $error = 0;
1154
1155 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1156 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1157
1158 // Total payments
1159 $sql = 'SELECT SUM(pf.amount) as total_payments';
1160 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1161 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1162 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1163 $sql .= ' AND pf.fk_paiement = p.rowid';
1164 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1165 $resql = $this->db->query($sql);
1166 if (!$resql) {
1167 dol_print_error($this->db);
1168 }
1169
1170 $res = $this->db->fetch_object($resql);
1171 $total_payments = $res->total_payments;
1172
1173 // Total credit note and deposit
1174 $total_creditnote_and_deposit = 0;
1175 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1176 $sql .= " re.description, re.fk_facture_source";
1177 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1178 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1179 $resql = $this->db->query($sql);
1180 if (!empty($resql)) {
1181 while ($obj = $this->db->fetch_object($resql)) {
1182 $total_creditnote_and_deposit += $obj->amount_ttc;
1183 }
1184 } else {
1185 dol_print_error($this->db);
1186 }
1187
1188 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1189 $discount->amount_tva = 0;
1190 $discount->tva_tx = 0;
1191
1192 $result = $discount->create(DolibarrApiAccess::$user);
1193 if ($result < 0) {
1194 $error++;
1195 }
1196 }
1197 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1198 foreach ($amount_ht as $tva_tx => $xxx) {
1199 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1200 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1201 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1202 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1203 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1204 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1205 $discount->tva_tx = abs($tva_tx);
1206
1207 $result = $discount->create(DolibarrApiAccess::$user);
1208 if ($result < 0) {
1209 $error++;
1210 break;
1211 }
1212 }
1213 }
1214
1215 if (empty($error)) {
1216 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1217 // Classe facture
1218 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1219 if ($result >= 0) {
1220 $this->db->commit();
1221 } else {
1222 $this->db->rollback();
1223 throw new RestException(500, 'Could not set paid');
1224 }
1225 } else {
1226 $this->db->commit();
1227 }
1228 } else {
1229 $this->db->rollback();
1230 throw new RestException(500, 'Discount creation error');
1231 }
1232 }
1233
1234 return $this->_cleanObjectDatas($this->invoice);
1235 }
1236
1253 public function useDiscount($id, $discountid)
1254 {
1255 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1256 throw new RestException(401);
1257 }
1258 if (empty($id)) {
1259 throw new RestException(400, 'Invoice ID is mandatory');
1260 }
1261 if (empty($discountid)) {
1262 throw new RestException(400, 'Discount ID is mandatory');
1263 }
1264
1265 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1266 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1267 }
1268
1269 $result = $this->invoice->fetch($id);
1270 if (!$result) {
1271 throw new RestException(404, 'Invoice not found');
1272 }
1273
1274 $result = $this->invoice->insert_discount($discountid);
1275 if ($result < 0) {
1276 throw new RestException(405, $this->invoice->error);
1277 }
1278
1279 return $result;
1280 }
1281
1298 public function useCreditNote($id, $discountid)
1299 {
1300 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1301
1302 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1303 throw new RestException(401);
1304 }
1305 if (empty($id)) {
1306 throw new RestException(400, 'Invoice ID is mandatory');
1307 }
1308 if (empty($discountid)) {
1309 throw new RestException(400, 'Credit ID is mandatory');
1310 }
1311
1312 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1313 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1314 }
1315 $discount = new DiscountAbsolute($this->db);
1316 $result = $discount->fetch($discountid);
1317 if (!$result) {
1318 throw new RestException(404, 'Credit not found');
1319 }
1320
1321 $result = $discount->link_to_invoice(0, $id);
1322 if ($result < 0) {
1323 throw new RestException(405, $discount->error);
1324 }
1325
1326 return $result;
1327 }
1328
1342 public function getPayments($id)
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] = price2num(-1 * $resteapayer, 'MT');
1436 // Multicurrency
1437 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1438 $multicurrency_amounts[$id] = price2num(-1 * $newvalue, 'MT');
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 ($amount > $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 = price2num(-1 * $amount, 'MT');
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:31
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='')
List invoices.
__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.
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.
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.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
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.