dolibarr 19.0.4
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 if ($field == 'array_options' && is_array($value)) {
637 foreach ($value as $index => $val) {
638 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
639 }
640 continue;
641 }
642 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
643 }
644
645 // update bank account
646 if (!empty($this->invoice->fk_account)) {
647 if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) {
648 throw new RestException(400, $this->invoice->error);
649 }
650 }
651
652 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
653 return $this->get($id);
654 } else {
655 throw new RestException(500, $this->invoice->error);
656 }
657 }
658
665 public function delete($id)
666 {
667 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
668 throw new RestException(401);
669 }
670 $result = $this->invoice->fetch($id);
671 if (!$result) {
672 throw new RestException(404, 'Invoice not found');
673 }
674
675 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
676 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
677 }
678
679 $result = $this->invoice->delete(DolibarrApiAccess::$user);
680 if ($result < 0) {
681 throw new RestException(500, 'Error when deleting invoice');
682 } elseif ($result == 0) {
683 throw new RestException(403, 'Invoice not erasable');
684 }
685
686 return array(
687 'success' => array(
688 'code' => 200,
689 'message' => 'Invoice deleted'
690 )
691 );
692 }
693
717 public function postLine($id, $request_data = null)
718 {
719 if (!DolibarrApiAccess::$user->rights->facture->creer) {
720 throw new RestException(401);
721 }
722
723 $result = $this->invoice->fetch($id);
724 if (!$result) {
725 throw new RestException(404, 'Invoice not found');
726 }
727
728 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
729 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
730 }
731
732 $request_data = (object) $request_data;
733
734 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
735 $request_data->label = sanitizeVal($request_data->label);
736
737 // Reset fk_parent_line for no child products and special product
738 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
739 $request_data->fk_parent_line = 0;
740 }
741
742 // calculate pa_ht
743 $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);
744 $pa_ht = $marginInfos[0];
745
746 $updateRes = $this->invoice->addline(
747 $request_data->desc,
748 $request_data->subprice,
749 $request_data->qty,
750 $request_data->tva_tx,
751 $request_data->localtax1_tx,
752 $request_data->localtax2_tx,
753 $request_data->fk_product,
754 $request_data->remise_percent,
755 $request_data->date_start,
756 $request_data->date_end,
757 $request_data->fk_code_ventilation,
758 $request_data->info_bits,
759 $request_data->fk_remise_except,
760 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
761 $request_data->subprice,
762 $request_data->product_type,
763 $request_data->rang,
764 $request_data->special_code,
765 $request_data->origin,
766 $request_data->origin_id,
767 $request_data->fk_parent_line,
768 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
769 $pa_ht,
770 $request_data->label,
771 $request_data->array_options,
772 $request_data->situation_percent,
773 $request_data->fk_prev_id,
774 $request_data->fk_unit,
775 0,
776 $request_data->ref_ext
777 );
778
779 if ($updateRes < 0) {
780 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
781 }
782
783 return $updateRes;
784 }
785
805 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
806 {
807 if (!DolibarrApiAccess::$user->rights->facture->creer) {
808 throw new RestException(401);
809 }
810 $result = $this->invoice->fetch($id);
811 if (!$result) {
812 throw new RestException(404, 'Invoice not found');
813 }
814
815 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
816 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
817 }
818
819 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
820 if ($result < 0) {
821 throw new RestException(500, 'Error : '.$this->invoice->error);
822 }
823
824 $result = $this->invoice->fetch($id);
825 if (!$result) {
826 throw new RestException(404, 'Invoice not found');
827 }
828
829 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
830 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
831 }
832
833 return $this->_cleanObjectDatas($this->invoice);
834 }
835
836
837
853 public function settodraft($id, $idwarehouse = -1)
854 {
855 if (!DolibarrApiAccess::$user->rights->facture->creer) {
856 throw new RestException(401);
857 }
858 $result = $this->invoice->fetch($id);
859 if (!$result) {
860 throw new RestException(404, 'Invoice not found');
861 }
862
863 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
864 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
865 }
866
867 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
868 if ($result == 0) {
869 throw new RestException(304, 'Nothing done.');
870 }
871 if ($result < 0) {
872 throw new RestException(500, 'Error : '.$this->invoice->error);
873 }
874
875 $result = $this->invoice->fetch($id);
876 if (!$result) {
877 throw new RestException(404, 'Invoice not found');
878 }
879
880 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
881 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
882 }
883
884 return $this->_cleanObjectDatas($this->invoice);
885 }
886
887
904 public function validate($id, $idwarehouse = 0, $notrigger = 0)
905 {
906 if (!DolibarrApiAccess::$user->rights->facture->creer) {
907 throw new RestException(401);
908 }
909 $result = $this->invoice->fetch($id);
910 if (!$result) {
911 throw new RestException(404, 'Invoice not found');
912 }
913
914 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
915 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
916 }
917
918 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
919 if ($result == 0) {
920 throw new RestException(304, 'Error nothing done. May be object is already validated');
921 }
922 if ($result < 0) {
923 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
924 }
925
926 $result = $this->invoice->fetch($id);
927 if (!$result) {
928 throw new RestException(404, 'Invoice not found');
929 }
930
931 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
932 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
933 }
934
935 return $this->_cleanObjectDatas($this->invoice);
936 }
937
953 public function settopaid($id, $close_code = '', $close_note = '')
954 {
955 if (!DolibarrApiAccess::$user->rights->facture->creer) {
956 throw new RestException(401);
957 }
958 $result = $this->invoice->fetch($id);
959 if (!$result) {
960 throw new RestException(404, 'Invoice not found');
961 }
962
963 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
964 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
965 }
966
967 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
968 if ($result == 0) {
969 throw new RestException(304, 'Error nothing done. May be object is already validated');
970 }
971 if ($result < 0) {
972 throw new RestException(500, 'Error : '.$this->invoice->error);
973 }
974
975
976 $result = $this->invoice->fetch($id);
977 if (!$result) {
978 throw new RestException(404, 'Invoice not found');
979 }
980
981 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
982 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
983 }
984
985 return $this->_cleanObjectDatas($this->invoice);
986 }
987
988
1002 public function settounpaid($id)
1003 {
1004 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1005 throw new RestException(401);
1006 }
1007 $result = $this->invoice->fetch($id);
1008 if (!$result) {
1009 throw new RestException(404, 'Invoice not found');
1010 }
1011
1012 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1013 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1014 }
1015
1016 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1017 if ($result == 0) {
1018 throw new RestException(304, 'Nothing done');
1019 }
1020 if ($result < 0) {
1021 throw new RestException(500, 'Error : '.$this->invoice->error);
1022 }
1023
1024
1025 $result = $this->invoice->fetch($id);
1026 if (!$result) {
1027 throw new RestException(404, 'Invoice not found');
1028 }
1029
1030 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1031 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1032 }
1033
1034 return $this->_cleanObjectDatas($this->invoice);
1035 }
1036
1045 public function getDiscount($id)
1046 {
1047 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1048
1049 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1050 throw new RestException(401);
1051 }
1052
1053 $result = $this->invoice->fetch($id);
1054 if (!$result) {
1055 throw new RestException(404, 'Invoice not found');
1056 }
1057
1058 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1059 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1060 }
1061
1062 $discountcheck = new DiscountAbsolute($this->db);
1063 $result = $discountcheck->fetch(0, $this->invoice->id);
1064
1065 if ($result == 0) {
1066 throw new RestException(404, 'Discount not found');
1067 }
1068 if ($result < 0) {
1069 throw new RestException(500, $discountcheck->error);
1070 }
1071
1072 return parent::_cleanObjectDatas($discountcheck);
1073 }
1074
1088 public function markAsCreditAvailable($id)
1089 {
1090 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1091
1092 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1093 throw new RestException(401);
1094 }
1095
1096 $result = $this->invoice->fetch($id);
1097 if (!$result) {
1098 throw new RestException(404, 'Invoice not found');
1099 }
1100
1101 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1102 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1103 }
1104
1105 if ($this->invoice->paye) {
1106 throw new RestException(500, 'Alreay paid');
1107 }
1108
1109 $this->invoice->fetch($id);
1110 $this->invoice->fetch_thirdparty();
1111
1112 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1113 $discountcheck = new DiscountAbsolute($this->db);
1114 $result = $discountcheck->fetch(0, $this->invoice->id);
1115
1116 $canconvert = 0;
1117 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1118 $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)
1119 }
1120 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1121 $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)
1122 }
1123 if ($canconvert) {
1124 $this->db->begin();
1125
1126 $amount_ht = $amount_tva = $amount_ttc = array();
1127 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1128
1129 // Loop on each vat rate
1130 $i = 0;
1131 foreach ($this->invoice->lines as $line) {
1132 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1133 // no need to create discount if amount is null
1134 $amount_ht[$line->tva_tx] += $line->total_ht;
1135 $amount_tva[$line->tva_tx] += $line->total_tva;
1136 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1137 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1138 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1139 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1140 $i++;
1141 }
1142 }
1143
1144 // Insert one discount by VAT rate category
1145 $discount = new DiscountAbsolute($this->db);
1146 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1147 $discount->description = '(CREDIT_NOTE)';
1148 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1149 $discount->description = '(DEPOSIT)';
1150 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1151 $discount->description = '(EXCESS RECEIVED)';
1152 } else {
1153 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1154 }
1155
1156 $discount->fk_soc = $this->invoice->socid;
1157 $discount->fk_facture_source = $this->invoice->id;
1158
1159 $error = 0;
1160
1161 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1162 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1163
1164 // Total payments
1165 $sql = 'SELECT SUM(pf.amount) as total_payments';
1166 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1167 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1168 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1169 $sql .= ' AND pf.fk_paiement = p.rowid';
1170 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1171 $resql = $this->db->query($sql);
1172 if (!$resql) {
1173 dol_print_error($this->db);
1174 }
1175
1176 $res = $this->db->fetch_object($resql);
1177 $total_payments = $res->total_payments;
1178
1179 // Total credit note and deposit
1180 $total_creditnote_and_deposit = 0;
1181 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1182 $sql .= " re.description, re.fk_facture_source";
1183 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1184 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1185 $resql = $this->db->query($sql);
1186 if (!empty($resql)) {
1187 while ($obj = $this->db->fetch_object($resql)) {
1188 $total_creditnote_and_deposit += $obj->amount_ttc;
1189 }
1190 } else {
1191 dol_print_error($this->db);
1192 }
1193
1194 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1195 $discount->amount_tva = 0;
1196 $discount->tva_tx = 0;
1197
1198 $result = $discount->create(DolibarrApiAccess::$user);
1199 if ($result < 0) {
1200 $error++;
1201 }
1202 }
1203 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1204 foreach ($amount_ht as $tva_tx => $xxx) {
1205 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1206 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1207 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1208 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1209 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1210 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1211 $discount->tva_tx = abs($tva_tx);
1212
1213 $result = $discount->create(DolibarrApiAccess::$user);
1214 if ($result < 0) {
1215 $error++;
1216 break;
1217 }
1218 }
1219 }
1220
1221 if (empty($error)) {
1222 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1223 // Classe facture
1224 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1225 if ($result >= 0) {
1226 $this->db->commit();
1227 } else {
1228 $this->db->rollback();
1229 throw new RestException(500, 'Could not set paid');
1230 }
1231 } else {
1232 $this->db->commit();
1233 }
1234 } else {
1235 $this->db->rollback();
1236 throw new RestException(500, 'Discount creation error');
1237 }
1238 }
1239
1240 return $this->_cleanObjectDatas($this->invoice);
1241 }
1242
1259 public function useDiscount($id, $discountid)
1260 {
1261 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1262 throw new RestException(401);
1263 }
1264 if (empty($id)) {
1265 throw new RestException(400, 'Invoice ID is mandatory');
1266 }
1267 if (empty($discountid)) {
1268 throw new RestException(400, 'Discount ID is mandatory');
1269 }
1270
1271 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1272 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1273 }
1274
1275 $result = $this->invoice->fetch($id);
1276 if (!$result) {
1277 throw new RestException(404, 'Invoice not found');
1278 }
1279
1280 $result = $this->invoice->insert_discount($discountid);
1281 if ($result < 0) {
1282 throw new RestException(405, $this->invoice->error);
1283 }
1284
1285 return $result;
1286 }
1287
1304 public function useCreditNote($id, $discountid)
1305 {
1306 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1307
1308 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1309 throw new RestException(401);
1310 }
1311 if (empty($id)) {
1312 throw new RestException(400, 'Invoice ID is mandatory');
1313 }
1314 if (empty($discountid)) {
1315 throw new RestException(400, 'Credit ID is mandatory');
1316 }
1317
1318 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1319 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1320 }
1321 $discount = new DiscountAbsolute($this->db);
1322 $result = $discount->fetch($discountid);
1323 if (!$result) {
1324 throw new RestException(404, 'Credit not found');
1325 }
1326
1327 $result = $discount->link_to_invoice(0, $id);
1328 if ($result < 0) {
1329 throw new RestException(405, $discount->error);
1330 }
1331
1332 return $result;
1333 }
1334
1348 public function getPayments($id)
1349 {
1350 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1351 throw new RestException(401);
1352 }
1353 if (empty($id)) {
1354 throw new RestException(400, 'Invoice ID is mandatory');
1355 }
1356
1357 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1358 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1359 }
1360
1361 $result = $this->invoice->fetch($id);
1362 if (!$result) {
1363 throw new RestException(404, 'Invoice not found');
1364 }
1365
1366 $result = $this->invoice->getListOfPayments();
1367 if ($result < 0) {
1368 throw new RestException(405, $this->invoice->error);
1369 }
1370
1371 return $result;
1372 }
1373
1374
1396 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1397 {
1398 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1399
1400 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1401 throw new RestException(403);
1402 }
1403 if (empty($id)) {
1404 throw new RestException(400, 'Invoice ID is mandatory');
1405 }
1406
1407 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1408 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1409 }
1410
1411 if (isModEnabled("banque")) {
1412 if (empty($accountid)) {
1413 throw new RestException(400, 'Account ID is mandatory');
1414 }
1415 }
1416
1417 if (empty($paymentid)) {
1418 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1419 }
1420
1421
1422 $result = $this->invoice->fetch($id);
1423 if (!$result) {
1424 throw new RestException(404, 'Invoice not found');
1425 }
1426
1427 // Calculate amount to pay
1428 $totalpaid = $this->invoice->getSommePaiement();
1429 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1430 $totaldeposits = $this->invoice->getSumDepositsUsed();
1431 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1432
1433 $this->db->begin();
1434
1435 $amounts = array();
1436 $multicurrency_amounts = array();
1437
1438 // Clean parameters amount if payment is for a credit note
1439 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1440 $resteapayer = price2num($resteapayer, 'MT');
1441 $amounts[$id] = price2num(-1 * $resteapayer, 'MT');
1442 // Multicurrency
1443 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1444 $multicurrency_amounts[$id] = price2num(-1 * $newvalue, 'MT');
1445 } else {
1446 $resteapayer = price2num($resteapayer, 'MT');
1447 $amounts[$id] = $resteapayer;
1448 // Multicurrency
1449 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1450 $multicurrency_amounts[$id] = $newvalue;
1451 }
1452
1453 // Creation of payment line
1454 $paymentobj = new Paiement($this->db);
1455 $paymentobj->datepaye = $datepaye;
1456 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1457 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1458 $paymentobj->paiementid = $paymentid;
1459 $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1);
1460 $paymentobj->num_payment = $num_payment;
1461 $paymentobj->note_private = $comment;
1462
1463 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1464 if ($payment_id < 0) {
1465 $this->db->rollback();
1466 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1467 }
1468
1469 if (isModEnabled("banque")) {
1470 $label = '(CustomerInvoicePayment)';
1471
1472 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1473 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1474 }
1475 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1476 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1477 }
1478 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1479 if ($result < 0) {
1480 $this->db->rollback();
1481 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1482 }
1483 }
1484
1485 $this->db->commit();
1486
1487 return $payment_id;
1488 }
1489
1516 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1517 {
1518 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1519
1520 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1521 throw new RestException(403);
1522 }
1523 foreach ($arrayofamounts as $id => $amount) {
1524 if (empty($id)) {
1525 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1526 }
1527 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1528 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1529 }
1530 }
1531
1532 if (isModEnabled("banque")) {
1533 if (empty($accountid)) {
1534 throw new RestException(400, 'Account ID is mandatory');
1535 }
1536 }
1537 if (empty($paymentid)) {
1538 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1539 }
1540
1541 $this->db->begin();
1542
1543 $amounts = array();
1544 $multicurrency_amounts = array();
1545
1546 // Loop on each invoice to pay
1547 foreach ($arrayofamounts as $id => $amountarray) {
1548 $result = $this->invoice->fetch($id);
1549 if (!$result) {
1550 $this->db->rollback();
1551 throw new RestException(404, 'Invoice ID '.$id.' not found');
1552 }
1553
1554 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1555 $this->db->rollback();
1556 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1557 }
1558
1559 $is_multicurrency = 0;
1560 $total_ttc = $this->invoice->total_ttc;
1561
1562 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1563 $is_multicurrency = 1;
1564 $total_ttc = $this->invoice->multicurrency_total_ttc;
1565 }
1566
1567 // Calculate amount to pay
1568 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1569 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1570 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1571 $remainstopay = $amount = price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1572
1573 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1574 $amount = price2num($amountarray["amount"], 'MT');
1575 }
1576
1577 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1578 $amount = price2num($amountarray["multicurrency_amount"], 'MT');
1579 }
1580
1581 if ($amount > $remainstopay && !$accepthigherpayment) {
1582 $this->db->rollback();
1583 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1584 }
1585
1586 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1587 $amount = price2num(-1 * $amount, 'MT');
1588 }
1589
1590 if ($is_multicurrency) {
1591 $amounts[$id] = null;
1592 // Multicurrency
1593 $multicurrency_amounts[$id] = $amount;
1594 } else {
1595 $amounts[$id] = $amount;
1596 // Multicurrency
1597 $multicurrency_amounts[$id] = null;
1598 }
1599 }
1600
1601 // Creation of payment line
1602 $paymentobj = new Paiement($this->db);
1603 $paymentobj->datepaye = $datepaye;
1604 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1605 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1606 $paymentobj->paiementid = $paymentid;
1607 $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1);
1608 $paymentobj->num_payment = $num_payment;
1609 $paymentobj->note_private = $comment;
1610 $paymentobj->ref_ext = $ref_ext;
1611 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1612 if ($payment_id < 0) {
1613 $this->db->rollback();
1614 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1615 }
1616 if (isModEnabled("banque")) {
1617 $label = '(CustomerInvoicePayment)';
1618 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1619 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1620 }
1621 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1622 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1623 }
1624 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1625 if ($result < 0) {
1626 $this->db->rollback();
1627 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1628 }
1629 }
1630
1631 $this->db->commit();
1632
1633 return $payment_id;
1634 }
1635
1650 public function putPayment($id, $num_payment = '')
1651 {
1652 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1653
1654 if (!DolibarrApiAccess::$user->rights->facture->creer) {
1655 throw new RestException(401);
1656 }
1657 if (empty($id)) {
1658 throw new RestException(400, 'Payment ID is mandatory');
1659 }
1660
1661 $paymentobj = new Paiement($this->db);
1662 $result = $paymentobj->fetch($id);
1663
1664 if (!$result) {
1665 throw new RestException(404, 'Payment not found');
1666 }
1667
1668 if (!empty($num_payment)) {
1669 $result = $paymentobj->update_num($num_payment);
1670 if ($result < 0) {
1671 throw new RestException(500, 'Error when updating the payment num');
1672 }
1673 }
1674
1675 return [
1676 'success' => [
1677 'code' => 200,
1678 'message' => 'Payment updated'
1679 ]
1680 ];
1681 }
1682
1683 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1690 protected function _cleanObjectDatas($object)
1691 {
1692 // phpcs:enable
1693 $object = parent::_cleanObjectDatas($object);
1694
1695 unset($object->note);
1696 unset($object->address);
1697 unset($object->barcode_type);
1698 unset($object->barcode_type_code);
1699 unset($object->barcode_type_label);
1700 unset($object->barcode_type_coder);
1701 unset($object->canvas);
1702
1703 return $object;
1704 }
1705
1714 private function _validate($data)
1715 {
1716 $invoice = array();
1717 foreach (Invoices::$FIELDS as $field) {
1718 if (!isset($data[$field])) {
1719 throw new RestException(400, "$field field missing");
1720 }
1721 $invoice[$field] = $data[$field];
1722 }
1723 return $invoice;
1724 }
1725
1726
1740 public function getTemplateInvoice($id, $contact_list = 1)
1741 {
1742 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
1743 }
1744
1758 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
1759 {
1760 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1761 throw new RestException(401);
1762 }
1763
1764 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
1765 if (!$result) {
1766 throw new RestException(404, 'Template invoice not found');
1767 }
1768
1769 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
1770 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1771 }
1772
1773 // Add external contacts ids
1774 if ($contact_list > -1) {
1775 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
1776 if (is_array($tmparray)) {
1777 $this->template_invoice->contacts_ids = $tmparray;
1778 }
1779 }
1780
1781 $this->template_invoice->fetchObjectLinked();
1782 return $this->_cleanTemplateObjectDatas($this->template_invoice);
1783 }
1784
1785
1786 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1793 protected function _cleanTemplateObjectDatas($object)
1794 {
1795 // phpcs:enable
1796 $object = parent::_cleanObjectDatas($object);
1797
1798 unset($object->note);
1799 unset($object->address);
1800 unset($object->barcode_type);
1801 unset($object->barcode_type_code);
1802 unset($object->barcode_type_label);
1803 unset($object->barcode_type_coder);
1804 unset($object->canvas);
1805
1806 return $object;
1807 }
1808}
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.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:85
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.
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.