dolibarr 21.0.0-alpha
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 * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\RestException;
23
24require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
25require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
26
27
34class Invoices extends DolibarrApi
35{
40 public static $FIELDS = array(
41 'socid',
42 );
43
47 private $invoice;
48
52 private $template_invoice;
53
54
58 public function __construct()
59 {
60 global $db;
61 $this->db = $db;
62 $this->invoice = new Facture($this->db);
63 $this->template_invoice = new FactureRec($this->db);
64 }
65
77 public function get($id, $contact_list = 1)
78 {
79 return $this->_fetch($id, '', '', $contact_list);
80 }
81
95 public function getByRef($ref, $contact_list = 1)
96 {
97 return $this->_fetch(0, $ref, '', $contact_list);
98 }
99
113 public function getByRefExt($ref_ext, $contact_list = 1)
114 {
115 return $this->_fetch(0, '', $ref_ext, $contact_list);
116 }
117
131 private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1)
132 {
133 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
134 throw new RestException(403);
135 }
136
137 $result = $this->invoice->fetch($id, $ref, $ref_ext);
138 if (!$result) {
139 throw new RestException(404, 'Invoice not found');
140 }
141
142 // Get payment details
143 $this->invoice->totalpaid = $this->invoice->getSommePaiement();
144 $this->invoice->totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
145 $this->invoice->totaldeposits = $this->invoice->getSumDepositsUsed();
146 $this->invoice->remaintopay = price2num($this->invoice->total_ttc - $this->invoice->totalpaid - $this->invoice->totalcreditnotes - $this->invoice->totaldeposits, 'MT');
147
148 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
149 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
150 }
151
152 // Add external contacts ids
153 if ($contact_list > -1) {
154 $tmparray = $this->invoice->liste_contact(-1, 'external', $contact_list);
155 if (is_array($tmparray)) {
156 $this->invoice->contacts_ids = $tmparray;
157 }
158 }
159
160 $this->invoice->fetchObjectLinked();
161
162 // Add online_payment_url, copied from order
163 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
164 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $this->invoice->ref);
165
166 return $this->_cleanObjectDatas($this->invoice);
167 }
168
188 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false)
189 {
190 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
191 throw new RestException(403);
192 }
193
194 $obj_ret = array();
195
196 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
197 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
198
199 // If the internal user must only see his customers, force searching by him
200 $search_sale = 0;
201 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
202 $search_sale = DolibarrApiAccess::$user->id;
203 }
204
205 $sql = "SELECT t.rowid";
206 $sql .= " FROM ".MAIN_DB_PREFIX."facture AS t";
207 $sql .= " 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
208 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
209 if ($socids) {
210 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
211 }
212 // Search on sale representative
213 if ($search_sale && $search_sale != '-1') {
214 if ($search_sale == -2) {
215 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
216 } elseif ($search_sale > 0) {
217 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
218 }
219 }
220 // Filter by status
221 if ($status == 'draft') {
222 $sql .= " AND t.fk_statut IN (0)";
223 }
224 if ($status == 'unpaid') {
225 $sql .= " AND t.fk_statut IN (1)";
226 }
227 if ($status == 'paid') {
228 $sql .= " AND t.fk_statut IN (2)";
229 }
230 if ($status == 'cancelled') {
231 $sql .= " AND t.fk_statut IN (3)";
232 }
233 // Add sql filters
234 if ($sqlfilters) {
235 $errormessage = '';
236 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
237 if ($errormessage) {
238 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
239 }
240 }
241
242 //this query will return total invoices with the filters given
243 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
244
245 $sql .= $this->db->order($sortfield, $sortorder);
246 if ($limit) {
247 if ($page < 0) {
248 $page = 0;
249 }
250 $offset = $limit * $page;
251
252 $sql .= $this->db->plimit($limit + 1, $offset);
253 }
254
255 $result = $this->db->query($sql);
256 if ($result) {
257 $i = 0;
258 $num = $this->db->num_rows($result);
259 $min = min($num, ($limit <= 0 ? $num : $limit));
260 while ($i < $min) {
261 $obj = $this->db->fetch_object($result);
262 $invoice_static = new Facture($this->db);
263 if ($invoice_static->fetch($obj->rowid)) {
264 // Get payment details
265 $invoice_static->totalpaid = $invoice_static->getSommePaiement();
266 $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed();
267 $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
268 $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT');
269
270 // Add external contacts ids
271 $tmparray = $invoice_static->liste_contact(-1, 'external', 1);
272 if (is_array($tmparray)) {
273 $invoice_static->contacts_ids = $tmparray;
274 }
275 // Add online_payment_url, copied from order
276 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
277 $invoice_static->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $invoice_static->ref);
278
279 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
280 }
281 $i++;
282 }
283 } else {
284 throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror());
285 }
286
287 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
288 if ($pagination_data) {
289 $totalsResult = $this->db->query($sqlTotals);
290 $total = $this->db->fetch_object($totalsResult)->total;
291
292 $tmp = $obj_ret;
293 $obj_ret = [];
294
295 $obj_ret['data'] = $tmp;
296 $obj_ret['pagination'] = [
297 'total' => (int) $total,
298 'page' => $page, //count starts from 0
299 'page_count' => ceil((int) $total / $limit),
300 'limit' => $limit
301 ];
302 }
303
304 return $obj_ret;
305 }
306
313 public function post($request_data = null)
314 {
315 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
316 throw new RestException(403, "Insuffisant rights");
317 }
318 // Check mandatory fields
319 $result = $this->_validate($request_data);
320
321 foreach ($request_data as $field => $value) {
322 if ($field === 'caller') {
323 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
324 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
325 continue;
326 }
327
328 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
329 }
330 if (!array_key_exists('date', $request_data)) {
331 $this->invoice->date = dol_now();
332 }
333 /* We keep lines as an array
334 if (isset($request_data["lines"])) {
335 $lines = array();
336 foreach ($request_data["lines"] as $line) {
337 array_push($lines, (object) $line);
338 }
339 $this->invoice->lines = $lines;
340 }*/
341
342 if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) {
343 throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors));
344 }
345 return ((int) $this->invoice->id);
346 }
347
361 public function createInvoiceFromOrder($orderid)
362 {
363 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
364
365 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
366 throw new RestException(403);
367 }
368 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
369 throw new RestException(403);
370 }
371 if (empty($orderid)) {
372 throw new RestException(400, 'Order ID is mandatory');
373 }
374
375 $order = new Commande($this->db);
376 $result = $order->fetch($orderid);
377 if (!$result) {
378 throw new RestException(404, 'Order not found');
379 }
380
381 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
382 if ($result < 0) {
383 throw new RestException(405, $this->invoice->error);
384 }
385 $this->invoice->fetchObjectLinked();
386 return $this->_cleanObjectDatas($this->invoice);
387 }
388
402 public function createInvoiceFromContract($contractid)
403 {
404 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
405
406 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
407 throw new RestException(403);
408 }
409 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
410 throw new RestException(403);
411 }
412 if (empty($contractid)) {
413 throw new RestException(400, 'Contract ID is mandatory');
414 }
415
416 $contract = new Contrat($this->db);
417 $result = $contract->fetch($contractid);
418 if (!$result) {
419 throw new RestException(404, 'Contract not found');
420 }
421
422 $result = $this->invoice->createFromContract($contract, DolibarrApiAccess::$user);
423 if ($result < 0) {
424 throw new RestException(405, $this->invoice->error);
425 }
426 $this->invoice->fetchObjectLinked();
427 return $this->_cleanObjectDatas($this->invoice);
428 }
429
438 public function getLines($id)
439 {
440 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
441 throw new RestException(403);
442 }
443
444 $result = $this->invoice->fetch($id);
445 if (!$result) {
446 throw new RestException(404, 'Invoice not found');
447 }
448
449 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
450 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
451 }
452 $this->invoice->getLinesArray();
453 $result = array();
454 foreach ($this->invoice->lines as $line) {
455 array_push($result, $this->_cleanObjectDatas($line));
456 }
457 return $result;
458 }
459
474 public function putLine($id, $lineid, $request_data = null)
475 {
476 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
477 throw new RestException(403);
478 }
479
480 $result = $this->invoice->fetch($id);
481 if (!$result) {
482 throw new RestException(404, 'Invoice not found');
483 }
484
485 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
486 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
487 }
488
489 $request_data = (object) $request_data;
490
491 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
492 $request_data->label = sanitizeVal($request_data->label);
493
494 $updateRes = $this->invoice->updateline(
495 $lineid,
496 $request_data->desc,
497 $request_data->subprice,
498 $request_data->qty,
499 $request_data->remise_percent,
500 $request_data->date_start,
501 $request_data->date_end,
502 $request_data->tva_tx,
503 $request_data->localtax1_tx,
504 $request_data->localtax2_tx,
505 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
506 $request_data->info_bits,
507 $request_data->product_type,
508 $request_data->fk_parent_line,
509 0,
510 $request_data->fk_fournprice,
511 $request_data->pa_ht,
512 $request_data->label,
513 $request_data->special_code,
514 $request_data->array_options,
515 $request_data->situation_percent,
516 $request_data->fk_unit,
517 $request_data->multicurrency_subprice,
518 0,
519 $request_data->ref_ext,
520 $request_data->rang
521 );
522
523 if ($updateRes > 0) {
524 $result = $this->get($id);
525 unset($result->line);
526 return $this->_cleanObjectDatas($result);
527 } else {
528 throw new RestException(304, $this->invoice->error);
529 }
530 }
531
545 public function postContact($id, $contactid, $type)
546 {
547 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
548 throw new RestException(403);
549 }
550
551 $result = $this->invoice->fetch($id);
552
553 if (!$result) {
554 throw new RestException(404, 'Invoice not found');
555 }
556
557 if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) {
558 throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER');
559 }
560
561 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
562 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
563 }
564
565 $result = $this->invoice->add_contact($contactid, $type, 'external');
566
567 if (!$result) {
568 throw new RestException(500, 'Error when added the contact');
569 }
570
571 return array(
572 'success' => array(
573 'code' => 200,
574 'message' => 'Contact linked to the invoice'
575 )
576 );
577 }
578
593 public function deleteContact($id, $contactid, $type)
594 {
595 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
596 throw new RestException(403);
597 }
598
599 $result = $this->invoice->fetch($id);
600
601 if (!$result) {
602 throw new RestException(404, 'Invoice not found');
603 }
604
605 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
606 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
607 }
608
609 $contacts = $this->invoice->liste_contact();
610
611 foreach ($contacts as $contact) {
612 if ($contact['id'] == $contactid && $contact['code'] == $type) {
613 $result = $this->invoice->delete_contact($contact['rowid']);
614
615 if (!$result) {
616 throw new RestException(500, 'Error when deleted the contact');
617 }
618 }
619 }
620
621 return $this->_cleanObjectDatas($this->invoice);
622 }
623
638 public function deleteLine($id, $lineid)
639 {
640 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
641 throw new RestException(403);
642 }
643 if (empty($lineid)) {
644 throw new RestException(400, 'Line ID is mandatory');
645 }
646
647 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
648 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
649 }
650
651 $result = $this->invoice->fetch($id);
652 if (!$result) {
653 throw new RestException(404, 'Invoice not found');
654 }
655
656 $updateRes = $this->invoice->deleteLine($lineid, $id);
657 if ($updateRes > 0) {
658 return $this->get($id);
659 } else {
660 throw new RestException(405, $this->invoice->error);
661 }
662 }
663
671 public function put($id, $request_data = null)
672 {
673 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
674 throw new RestException(403);
675 }
676
677 $result = $this->invoice->fetch($id);
678 if (!$result) {
679 throw new RestException(404, 'Invoice not found');
680 }
681
682 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
683 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
684 }
685
686 foreach ($request_data as $field => $value) {
687 if ($field == 'id') {
688 continue;
689 }
690 if ($field === 'caller') {
691 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
692 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
693 continue;
694 }
695 if ($field == 'array_options' && is_array($value)) {
696 foreach ($value as $index => $val) {
697 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
698 }
699 continue;
700 }
701
702 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
703
704 // If cond reglement => update date lim reglement
705 if ($field == 'cond_reglement_id') {
706 $this->invoice->date_lim_reglement = $this->invoice->calculate_date_lim_reglement();
707 }
708 }
709
710 // update bank account
711 if (!empty($this->invoice->fk_account)) {
712 if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) {
713 throw new RestException(400, $this->invoice->error);
714 }
715 }
716
717 if ($this->invoice->update(DolibarrApiAccess::$user)) {
718 return $this->get($id);
719 }
720
721 return false;
722 }
723
730 public function delete($id)
731 {
732 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
733 throw new RestException(403);
734 }
735 $result = $this->invoice->fetch($id);
736 if (!$result) {
737 throw new RestException(404, 'Invoice not found');
738 }
739
740 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
741 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
742 }
743
744 $result = $this->invoice->delete(DolibarrApiAccess::$user);
745 if ($result < 0) {
746 throw new RestException(500, 'Error when deleting invoice');
747 } elseif ($result == 0) {
748 throw new RestException(403, 'Invoice not erasable');
749 }
750
751 return array(
752 'success' => array(
753 'code' => 200,
754 'message' => 'Invoice deleted'
755 )
756 );
757 }
758
782 public function postLine($id, $request_data = null)
783 {
784 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
785 throw new RestException(403);
786 }
787
788 $result = $this->invoice->fetch($id);
789 if (!$result) {
790 throw new RestException(404, 'Invoice not found');
791 }
792
793 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
794 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
795 }
796
797 $request_data = (object) $request_data;
798
799 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
800 $request_data->label = sanitizeVal($request_data->label);
801
802 // Reset fk_parent_line for no child products and special product
803 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
804 $request_data->fk_parent_line = 0;
805 }
806
807 // calculate pa_ht
808 $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);
809 $pa_ht = $marginInfos[0];
810
811 $updateRes = $this->invoice->addline(
812 $request_data->desc,
813 $request_data->subprice,
814 $request_data->qty,
815 $request_data->tva_tx,
816 $request_data->localtax1_tx,
817 $request_data->localtax2_tx,
818 $request_data->fk_product,
819 $request_data->remise_percent,
820 $request_data->date_start,
821 $request_data->date_end,
822 $request_data->fk_code_ventilation,
823 $request_data->info_bits,
824 $request_data->fk_remise_except,
825 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
826 $request_data->subprice,
827 $request_data->product_type,
828 $request_data->rang,
829 $request_data->special_code,
830 $request_data->origin,
831 $request_data->origin_id,
832 $request_data->fk_parent_line,
833 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
834 $pa_ht,
835 $request_data->label,
836 $request_data->array_options,
837 $request_data->situation_percent,
838 $request_data->fk_prev_id,
839 $request_data->fk_unit,
840 0,
841 $request_data->ref_ext
842 );
843
844 if ($updateRes < 0) {
845 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
846 }
847
848 return $updateRes;
849 }
850
870 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
871 {
872 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
873 throw new RestException(403);
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(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
882 }
883
884 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
885 if ($result < 0) {
886 throw new RestException(500, 'Error : '.$this->invoice->error);
887 }
888
889 $result = $this->invoice->fetch($id);
890 if (!$result) {
891 throw new RestException(404, 'Invoice not found');
892 }
893
894 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
895 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
896 }
897
898 return $this->_cleanObjectDatas($this->invoice);
899 }
900
901
902
918 public function settodraft($id, $idwarehouse = -1)
919 {
920 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
921 throw new RestException(403);
922 }
923 $result = $this->invoice->fetch($id);
924 if (!$result) {
925 throw new RestException(404, 'Invoice not found');
926 }
927
928 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
929 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
930 }
931
932 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
933 if ($result == 0) {
934 throw new RestException(304, 'Nothing done.');
935 }
936 if ($result < 0) {
937 throw new RestException(500, 'Error : '.$this->invoice->error);
938 }
939
940 $result = $this->invoice->fetch($id);
941 if (!$result) {
942 throw new RestException(404, 'Invoice not found');
943 }
944
945 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
946 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
947 }
948
949 return $this->_cleanObjectDatas($this->invoice);
950 }
951
952
970 public function validate($id, $force_number = '', $idwarehouse = 0, $notrigger = 0)
971 {
972 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
973 throw new RestException(403);
974 }
975 $result = $this->invoice->fetch($id);
976 if (!$result) {
977 throw new RestException(404, 'Invoice not found');
978 }
979
980 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
981 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
982 }
983
984 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
985 if ($result == 0) {
986 throw new RestException(304, 'Error nothing done. May be object is already validated');
987 }
988 if ($result < 0) {
989 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
990 }
991
992 $result = $this->invoice->fetch($id);
993 if (!$result) {
994 throw new RestException(404, 'Invoice not found');
995 }
996
997 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
998 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
999 }
1000
1001 // copy from order
1002 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1003 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $this->invoice->ref);
1004
1005 return $this->_cleanObjectDatas($this->invoice);
1006 }
1007
1023 public function settopaid($id, $close_code = '', $close_note = '')
1024 {
1025 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1026 throw new RestException(403);
1027 }
1028 $result = $this->invoice->fetch($id);
1029 if (!$result) {
1030 throw new RestException(404, 'Invoice not found');
1031 }
1032
1033 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1034 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1035 }
1036
1037 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1038 if ($result == 0) {
1039 throw new RestException(304, 'Error nothing done. May be object is already validated');
1040 }
1041 if ($result < 0) {
1042 throw new RestException(500, 'Error : '.$this->invoice->error);
1043 }
1044
1045
1046 $result = $this->invoice->fetch($id);
1047 if (!$result) {
1048 throw new RestException(404, 'Invoice not found');
1049 }
1050
1051 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1052 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1053 }
1054
1055 return $this->_cleanObjectDatas($this->invoice);
1056 }
1057
1058
1072 public function settounpaid($id)
1073 {
1074 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1075 throw new RestException(403);
1076 }
1077 $result = $this->invoice->fetch($id);
1078 if (!$result) {
1079 throw new RestException(404, 'Invoice not found');
1080 }
1081
1082 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1083 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1084 }
1085
1086 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1087 if ($result == 0) {
1088 throw new RestException(304, 'Nothing done');
1089 }
1090 if ($result < 0) {
1091 throw new RestException(500, 'Error : '.$this->invoice->error);
1092 }
1093
1094
1095 $result = $this->invoice->fetch($id);
1096 if (!$result) {
1097 throw new RestException(404, 'Invoice not found');
1098 }
1099
1100 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1101 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1102 }
1103
1104 return $this->_cleanObjectDatas($this->invoice);
1105 }
1106
1115 public function getDiscount($id)
1116 {
1117 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1118
1119 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1120 throw new RestException(403);
1121 }
1122
1123 $result = $this->invoice->fetch($id);
1124 if (!$result) {
1125 throw new RestException(404, 'Invoice not found');
1126 }
1127
1128 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1129 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1130 }
1131
1132 $discountcheck = new DiscountAbsolute($this->db);
1133 $result = $discountcheck->fetch(0, $this->invoice->id);
1134
1135 if ($result == 0) {
1136 throw new RestException(404, 'Discount not found');
1137 }
1138 if ($result < 0) {
1139 throw new RestException(500, $discountcheck->error);
1140 }
1141
1142 return parent::_cleanObjectDatas($discountcheck);
1143 }
1144
1159 {
1160 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1161
1162 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1163 throw new RestException(403);
1164 }
1165
1166 $result = $this->invoice->fetch($id);
1167 if (!$result) {
1168 throw new RestException(404, 'Invoice not found');
1169 }
1170
1171 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1172 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1173 }
1174
1175 if ($this->invoice->paye) {
1176 throw new RestException(500, 'Alreay paid');
1177 }
1178
1179 $this->invoice->fetch($id);
1180 $this->invoice->fetch_thirdparty();
1181
1182 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1183 $discountcheck = new DiscountAbsolute($this->db);
1184 $result = $discountcheck->fetch(0, $this->invoice->id);
1185
1186 $canconvert = 0;
1187 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1188 $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
1189 }
1190 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1191 $canconvert = 1; // we can convert credit note into discount if credit note is not paid back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
1192 }
1193 if ($canconvert) {
1194 $this->db->begin();
1195
1196 $amount_ht = $amount_tva = $amount_ttc = array();
1197 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1198 '
1199 @phan-var-force array<string,float> $amount_ht
1200 @phan-var-force array<string,float> $amount_tva
1201 @phan-var-force array<string,float> $amount_ttc
1202 @phan-var-force array<string,float> $multicurrency_amount_ht
1203 @phan-var-force array<string,float> $multicurrency_amount_tva
1204 @phan-var-force array<string,float> $multicurrency_amount_ttc
1205 ';
1206
1207 // Loop on each vat rate
1208 $i = 0;
1209 foreach ($this->invoice->lines as $line) {
1210 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1211 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1212 $amount_ht[$line->tva_tx] = 0.0;
1213 $amount_tva[$line->tva_tx] = 0.0;
1214 $amount_ttc[$line->tva_tx] = 0.0;
1215 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1216 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1217 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1218 }
1219 // no need to create discount if amount is null
1220 $amount_ht[$line->tva_tx] += $line->total_ht;
1221 $amount_tva[$line->tva_tx] += $line->total_tva;
1222 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1223 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1224 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1225 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1226 $i++;
1227 }
1228 }
1229
1230 // Insert one discount by VAT rate category
1231 $discount = new DiscountAbsolute($this->db);
1232 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1233 $discount->description = '(CREDIT_NOTE)';
1234 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1235 $discount->description = '(DEPOSIT)';
1236 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1237 $discount->description = '(EXCESS RECEIVED)';
1238 } else {
1239 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1240 }
1241
1242 $discount->fk_soc = $this->invoice->socid;
1243 $discount->socid = $this->invoice->socid;
1244 $discount->fk_facture_source = $this->invoice->id;
1245
1246 $error = 0;
1247
1248 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1249 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1250
1251 // Total payments
1252 $sql = 'SELECT SUM(pf.amount) as total_payments';
1253 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1254 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1255 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1256 $sql .= ' AND pf.fk_paiement = p.rowid';
1257 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1258 $resql = $this->db->query($sql);
1259 if (!$resql) {
1260 dol_print_error($this->db);
1261 }
1262
1263 $res = $this->db->fetch_object($resql);
1264 $total_payments = $res->total_payments;
1265
1266 // Total credit note and deposit
1267 $total_creditnote_and_deposit = 0;
1268 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1269 $sql .= " re.description, re.fk_facture_source";
1270 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1271 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1272 $resql = $this->db->query($sql);
1273 if (!empty($resql)) {
1274 while ($obj = $this->db->fetch_object($resql)) {
1275 $total_creditnote_and_deposit += $obj->amount_ttc;
1276 }
1277 } else {
1278 dol_print_error($this->db);
1279 }
1280
1281 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1282 $discount->amount_tva = 0;
1283 $discount->tva_tx = 0;
1284
1285 $result = $discount->create(DolibarrApiAccess::$user);
1286 if ($result < 0) {
1287 $error++;
1288 }
1289 }
1290 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1291 foreach ($amount_ht as $tva_tx => $xxx) {
1292 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1293 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1294 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1295 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1296 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1297 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1298 $discount->tva_tx = abs((float) $tva_tx);
1299
1300 $result = $discount->create(DolibarrApiAccess::$user);
1301 if ($result < 0) {
1302 $error++;
1303 break;
1304 }
1305 }
1306 }
1307
1308 if (empty($error)) {
1309 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1310 // Set the invoice as paid
1311 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1312 if ($result >= 0) {
1313 $this->db->commit();
1314 } else {
1315 $this->db->rollback();
1316 throw new RestException(500, 'Could not set paid');
1317 }
1318 } else {
1319 $this->db->commit();
1320 }
1321 } else {
1322 $this->db->rollback();
1323 throw new RestException(500, 'Discount creation error');
1324 }
1325 }
1326
1327 return $this->_cleanObjectDatas($this->invoice);
1328 }
1329
1346 public function useDiscount($id, $discountid)
1347 {
1348 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1349 throw new RestException(403);
1350 }
1351 if (empty($id)) {
1352 throw new RestException(400, 'Invoice ID is mandatory');
1353 }
1354 if (empty($discountid)) {
1355 throw new RestException(400, 'Discount ID is mandatory');
1356 }
1357
1358 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1359 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1360 }
1361
1362 $result = $this->invoice->fetch($id);
1363 if (!$result) {
1364 throw new RestException(404, 'Invoice not found');
1365 }
1366
1367 $result = $this->invoice->insert_discount($discountid);
1368 if ($result < 0) {
1369 throw new RestException(405, $this->invoice->error);
1370 }
1371
1372 return $result;
1373 }
1374
1391 public function useCreditNote($id, $discountid)
1392 {
1393 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1394
1395 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1396 throw new RestException(403);
1397 }
1398 if (empty($id)) {
1399 throw new RestException(400, 'Invoice ID is mandatory');
1400 }
1401 if (empty($discountid)) {
1402 throw new RestException(400, 'Credit ID is mandatory');
1403 }
1404
1405 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1406 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1407 }
1408 $discount = new DiscountAbsolute($this->db);
1409 $result = $discount->fetch($discountid);
1410 if (!$result) {
1411 throw new RestException(404, 'Credit not found');
1412 }
1413
1414 $result = $discount->link_to_invoice(0, $id);
1415 if ($result < 0) {
1416 throw new RestException(405, $discount->error);
1417 }
1418
1419 return $result;
1420 }
1421
1435 public function getPayments($id)
1436 {
1437 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1438 throw new RestException(403);
1439 }
1440 if (empty($id)) {
1441 throw new RestException(400, 'Invoice ID is mandatory');
1442 }
1443
1444 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1445 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1446 }
1447
1448 $result = $this->invoice->fetch($id);
1449 if (!$result) {
1450 throw new RestException(404, 'Invoice not found');
1451 }
1452
1453 $result = $this->invoice->getListOfPayments();
1454 if ($result < 0) {
1455 throw new RestException(405, $this->invoice->error);
1456 }
1457
1458 return $result;
1459 }
1460
1461
1483 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1484 {
1485 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1486
1487 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1488 throw new RestException(403);
1489 }
1490 if (empty($id)) {
1491 throw new RestException(400, 'Invoice ID is mandatory');
1492 }
1493
1494 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1495 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1496 }
1497
1498 if (isModEnabled("bank")) {
1499 if (empty($accountid)) {
1500 throw new RestException(400, 'Account ID is mandatory');
1501 }
1502 }
1503
1504 if (empty($paymentid)) {
1505 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1506 }
1507
1508
1509 $result = $this->invoice->fetch($id);
1510 if (!$result) {
1511 throw new RestException(404, 'Invoice not found');
1512 }
1513
1514 // Calculate amount to pay
1515 $totalpaid = $this->invoice->getSommePaiement();
1516 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1517 $totaldeposits = $this->invoice->getSumDepositsUsed();
1518 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1519
1520 $this->db->begin();
1521
1522 $amounts = array();
1523 $multicurrency_amounts = array();
1524
1525 // Clean parameters amount if payment is for a credit note
1526 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1527 $resteapayer = price2num($resteapayer, 'MT');
1528 $amounts[$id] = (float) price2num(-1 * (float) $resteapayer, 'MT');
1529 // Multicurrency
1530 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1531 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1532 } else {
1533 $resteapayer = price2num($resteapayer, 'MT');
1534 $amounts[$id] = (float) $resteapayer;
1535 // Multicurrency
1536 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1537 $multicurrency_amounts[$id] = (float) $newvalue;
1538 }
1539
1540 // Creation of payment line
1541 $paymentobj = new Paiement($this->db);
1542 $paymentobj->datepaye = $datepaye;
1543 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1544 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1545 $paymentobj->paiementid = $paymentid;
1546 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1547 $paymentobj->num_payment = $num_payment;
1548 $paymentobj->note_private = $comment;
1549
1550 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1551 if ($payment_id < 0) {
1552 $this->db->rollback();
1553 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1554 }
1555
1556 if (isModEnabled("bank")) {
1557 $label = '(CustomerInvoicePayment)';
1558
1559 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1560 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1561 }
1562 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1563 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1564 }
1565 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1566 if ($result < 0) {
1567 $this->db->rollback();
1568 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1569 }
1570 }
1571
1572 $this->db->commit();
1573
1574 return $payment_id;
1575 }
1576
1603 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1604 {
1605 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1606
1607 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1608 throw new RestException(403);
1609 }
1610 foreach ($arrayofamounts as $id => $amount) {
1611 if (empty($id)) {
1612 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1613 }
1614 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1615 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1616 }
1617 }
1618
1619 if (isModEnabled("bank")) {
1620 if (empty($accountid)) {
1621 throw new RestException(400, 'Account ID is mandatory');
1622 }
1623 }
1624 if (empty($paymentid)) {
1625 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1626 }
1627
1628 $this->db->begin();
1629
1630 $amounts = array();
1631 $multicurrency_amounts = array();
1632
1633 // Loop on each invoice to pay
1634 foreach ($arrayofamounts as $id => $amountarray) {
1635 $result = $this->invoice->fetch($id);
1636 if (!$result) {
1637 $this->db->rollback();
1638 throw new RestException(404, 'Invoice ID '.$id.' not found');
1639 }
1640
1641 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1642 $this->db->rollback();
1643 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1644 }
1645
1646 $is_multicurrency = 0;
1647 $total_ttc = $this->invoice->total_ttc;
1648
1649 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1650 $is_multicurrency = 1;
1651 $total_ttc = $this->invoice->multicurrency_total_ttc;
1652 }
1653
1654 // Calculate amount to pay
1655 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1656 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1657 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1658 $remainstopay = $amount = price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1659
1660 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1661 $amount = price2num($amountarray["amount"], 'MT');
1662 }
1663
1664 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1665 $amount = price2num($amountarray["multicurrency_amount"], 'MT');
1666 }
1667
1668 if ($amount > $remainstopay && !$accepthigherpayment) {
1669 $this->db->rollback();
1670 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1671 }
1672
1673 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1674 $amount = price2num(-1 * (float) $amount, 'MT');
1675 }
1676
1677 if ($is_multicurrency) {
1678 $amounts[$id] = null;
1679 // Multicurrency
1680 $multicurrency_amounts[$id] = (float) $amount;
1681 } else {
1682 $amounts[$id] = (float) $amount;
1683 // Multicurrency
1684 $multicurrency_amounts[$id] = null;
1685 }
1686 }
1687
1688 // Creation of payment line
1689 $paymentobj = new Paiement($this->db);
1690 $paymentobj->datepaye = $datepaye;
1691 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1692 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1693 $paymentobj->paiementid = $paymentid;
1694 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1695 $paymentobj->num_payment = $num_payment;
1696 $paymentobj->note_private = $comment;
1697 $paymentobj->ref_ext = $ref_ext;
1698 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1699 if ($payment_id < 0) {
1700 $this->db->rollback();
1701 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1702 }
1703 if (isModEnabled("bank")) {
1704 $label = '(CustomerInvoicePayment)';
1705 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1706 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1707 }
1708 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1709 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1710 }
1711 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1712 if ($result < 0) {
1713 $this->db->rollback();
1714 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1715 }
1716 }
1717
1718 $this->db->commit();
1719
1720 return $payment_id;
1721 }
1722
1737 public function putPayment($id, $num_payment = '')
1738 {
1739 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1740
1741 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1742 throw new RestException(403);
1743 }
1744 if (empty($id)) {
1745 throw new RestException(400, 'Payment ID is mandatory');
1746 }
1747
1748 $paymentobj = new Paiement($this->db);
1749 $result = $paymentobj->fetch($id);
1750
1751 if (!$result) {
1752 throw new RestException(404, 'Payment not found');
1753 }
1754
1755 if (!empty($num_payment)) {
1756 $result = $paymentobj->update_num($num_payment);
1757 if ($result < 0) {
1758 throw new RestException(500, 'Error when updating the payment num');
1759 }
1760 }
1761
1762 return [
1763 'success' => [
1764 'code' => 200,
1765 'message' => 'Payment updated'
1766 ]
1767 ];
1768 }
1769
1770 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1777 protected function _cleanObjectDatas($object)
1778 {
1779 // phpcs:enable
1780 $object = parent::_cleanObjectDatas($object);
1781
1782 unset($object->note);
1783 unset($object->address);
1784 unset($object->barcode_type);
1785 unset($object->barcode_type_code);
1786 unset($object->barcode_type_label);
1787 unset($object->barcode_type_coder);
1788 unset($object->canvas);
1789
1790 return $object;
1791 }
1792
1801 private function _validate($data)
1802 {
1803 $invoice = array();
1804 foreach (Invoices::$FIELDS as $field) {
1805 if (!isset($data[$field])) {
1806 throw new RestException(400, "$field field missing");
1807 }
1808 $invoice[$field] = $data[$field];
1809 }
1810 return $invoice;
1811 }
1812
1813
1827 public function getTemplateInvoice($id, $contact_list = 1)
1828 {
1829 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
1830 }
1831
1845 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
1846 {
1847 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1848 throw new RestException(403);
1849 }
1850
1851 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
1852 if (!$result) {
1853 throw new RestException(404, 'Template invoice not found');
1854 }
1855
1856 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
1857 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1858 }
1859
1860 // Add external contacts ids
1861 if ($contact_list > -1) {
1862 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
1863 if (is_array($tmparray)) {
1864 $this->template_invoice->contacts_ids = $tmparray;
1865 }
1866 }
1867
1868 $this->template_invoice->fetchObjectLinked();
1869 return $this->_cleanTemplateObjectDatas($this->template_invoice);
1870 }
1871
1872
1873 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1881 {
1882 // phpcs:enable
1883 $object = parent::_cleanObjectDatas($object);
1884
1885 unset($object->note);
1886 unset($object->address);
1887 unset($object->barcode_type);
1888 unset($object->barcode_type_code);
1889 unset($object->barcode_type_label);
1890 unset($object->barcode_type_coder);
1891 unset($object->canvas);
1892
1893 return $object;
1894 }
1895}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
Class to manage customers orders.
Class to manage absolute discounts.
Class for API REST v1.
Definition api.class.php:30
_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:82
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoice templates.
postContact($id, $contactid, $type)
Add a contact type of given invoice.
putPayment($id, $num_payment='')
Update a payment.
addContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0)
Adds a contact to an invoice.
createInvoiceFromOrder($orderid)
Create an invoice using an existing order.
markAsCreditAvailable($id)
Create a discount (credit available) for a credit note or a deposit.
getDiscount($id)
Get discount from invoice.
__construct()
Constructor.
put($id, $request_data=null)
Update invoice.
validate($id, $force_number='', $idwarehouse=0, $notrigger=0)
Validate an 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.
createInvoiceFromContract($contractid)
Create an invoice using a contract.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false)
List invoices.
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.
_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 '.
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.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.