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('', $ref, '', $contact_list);
98 }
99
113 public function getByRefExt($ref_ext, $contact_list = 1)
114 {
115 return $this->_fetch('', '', $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
1158 public function markAsCreditAvailable($id)
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 // Loop on each vat rate
1200 $i = 0;
1201 foreach ($this->invoice->lines as $line) {
1202 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1203 // no need to create discount if amount is null
1204 $amount_ht[$line->tva_tx] += $line->total_ht;
1205 $amount_tva[$line->tva_tx] += $line->total_tva;
1206 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1207 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1208 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1209 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1210 $i++;
1211 }
1212 }
1213
1214 // Insert one discount by VAT rate category
1215 $discount = new DiscountAbsolute($this->db);
1216 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1217 $discount->description = '(CREDIT_NOTE)';
1218 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1219 $discount->description = '(DEPOSIT)';
1220 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1221 $discount->description = '(EXCESS RECEIVED)';
1222 } else {
1223 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1224 }
1225
1226 $discount->fk_soc = $this->invoice->socid;
1227 $discount->socid = $this->invoice->socid;
1228 $discount->fk_facture_source = $this->invoice->id;
1229
1230 $error = 0;
1231
1232 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1233 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1234
1235 // Total payments
1236 $sql = 'SELECT SUM(pf.amount) as total_payments';
1237 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1238 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1239 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1240 $sql .= ' AND pf.fk_paiement = p.rowid';
1241 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1242 $resql = $this->db->query($sql);
1243 if (!$resql) {
1244 dol_print_error($this->db);
1245 }
1246
1247 $res = $this->db->fetch_object($resql);
1248 $total_payments = $res->total_payments;
1249
1250 // Total credit note and deposit
1251 $total_creditnote_and_deposit = 0;
1252 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1253 $sql .= " re.description, re.fk_facture_source";
1254 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1255 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1256 $resql = $this->db->query($sql);
1257 if (!empty($resql)) {
1258 while ($obj = $this->db->fetch_object($resql)) {
1259 $total_creditnote_and_deposit += $obj->amount_ttc;
1260 }
1261 } else {
1262 dol_print_error($this->db);
1263 }
1264
1265 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1266 $discount->amount_tva = 0;
1267 $discount->tva_tx = 0;
1268
1269 $result = $discount->create(DolibarrApiAccess::$user);
1270 if ($result < 0) {
1271 $error++;
1272 }
1273 }
1274 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1275 foreach ($amount_ht as $tva_tx => $xxx) {
1276 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1277 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1278 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1279 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1280 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1281 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1282 $discount->tva_tx = abs($tva_tx);
1283
1284 $result = $discount->create(DolibarrApiAccess::$user);
1285 if ($result < 0) {
1286 $error++;
1287 break;
1288 }
1289 }
1290 }
1291
1292 if (empty($error)) {
1293 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1294 // Set the invoice as paid
1295 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1296 if ($result >= 0) {
1297 $this->db->commit();
1298 } else {
1299 $this->db->rollback();
1300 throw new RestException(500, 'Could not set paid');
1301 }
1302 } else {
1303 $this->db->commit();
1304 }
1305 } else {
1306 $this->db->rollback();
1307 throw new RestException(500, 'Discount creation error');
1308 }
1309 }
1310
1311 return $this->_cleanObjectDatas($this->invoice);
1312 }
1313
1330 public function useDiscount($id, $discountid)
1331 {
1332 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1333 throw new RestException(403);
1334 }
1335 if (empty($id)) {
1336 throw new RestException(400, 'Invoice ID is mandatory');
1337 }
1338 if (empty($discountid)) {
1339 throw new RestException(400, 'Discount ID is mandatory');
1340 }
1341
1342 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1343 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1344 }
1345
1346 $result = $this->invoice->fetch($id);
1347 if (!$result) {
1348 throw new RestException(404, 'Invoice not found');
1349 }
1350
1351 $result = $this->invoice->insert_discount($discountid);
1352 if ($result < 0) {
1353 throw new RestException(405, $this->invoice->error);
1354 }
1355
1356 return $result;
1357 }
1358
1375 public function useCreditNote($id, $discountid)
1376 {
1377 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1378
1379 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1380 throw new RestException(403);
1381 }
1382 if (empty($id)) {
1383 throw new RestException(400, 'Invoice ID is mandatory');
1384 }
1385 if (empty($discountid)) {
1386 throw new RestException(400, 'Credit ID is mandatory');
1387 }
1388
1389 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1390 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1391 }
1392 $discount = new DiscountAbsolute($this->db);
1393 $result = $discount->fetch($discountid);
1394 if (!$result) {
1395 throw new RestException(404, 'Credit not found');
1396 }
1397
1398 $result = $discount->link_to_invoice(0, $id);
1399 if ($result < 0) {
1400 throw new RestException(405, $discount->error);
1401 }
1402
1403 return $result;
1404 }
1405
1419 public function getPayments($id)
1420 {
1421 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1422 throw new RestException(403);
1423 }
1424 if (empty($id)) {
1425 throw new RestException(400, 'Invoice ID is mandatory');
1426 }
1427
1428 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1429 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1430 }
1431
1432 $result = $this->invoice->fetch($id);
1433 if (!$result) {
1434 throw new RestException(404, 'Invoice not found');
1435 }
1436
1437 $result = $this->invoice->getListOfPayments();
1438 if ($result < 0) {
1439 throw new RestException(405, $this->invoice->error);
1440 }
1441
1442 return $result;
1443 }
1444
1445
1467 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1468 {
1469 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1470
1471 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1472 throw new RestException(403);
1473 }
1474 if (empty($id)) {
1475 throw new RestException(400, 'Invoice ID is mandatory');
1476 }
1477
1478 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1479 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1480 }
1481
1482 if (isModEnabled("bank")) {
1483 if (empty($accountid)) {
1484 throw new RestException(400, 'Account ID is mandatory');
1485 }
1486 }
1487
1488 if (empty($paymentid)) {
1489 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1490 }
1491
1492
1493 $result = $this->invoice->fetch($id);
1494 if (!$result) {
1495 throw new RestException(404, 'Invoice not found');
1496 }
1497
1498 // Calculate amount to pay
1499 $totalpaid = $this->invoice->getSommePaiement();
1500 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1501 $totaldeposits = $this->invoice->getSumDepositsUsed();
1502 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1503
1504 $this->db->begin();
1505
1506 $amounts = array();
1507 $multicurrency_amounts = array();
1508
1509 // Clean parameters amount if payment is for a credit note
1510 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1511 $resteapayer = price2num($resteapayer, 'MT');
1512 $amounts[$id] = (float) price2num(-1 * (float) $resteapayer, 'MT');
1513 // Multicurrency
1514 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1515 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1516 } else {
1517 $resteapayer = price2num($resteapayer, 'MT');
1518 $amounts[$id] = (float) $resteapayer;
1519 // Multicurrency
1520 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1521 $multicurrency_amounts[$id] = (float) $newvalue;
1522 }
1523
1524 // Creation of payment line
1525 $paymentobj = new Paiement($this->db);
1526 $paymentobj->datepaye = dol_stringtotime($datepaye);
1527 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1528 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1529 $paymentobj->paiementid = $paymentid;
1530 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1);
1531 $paymentobj->num_payment = $num_payment;
1532 $paymentobj->note_private = $comment;
1533
1534 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1535 if ($payment_id < 0) {
1536 $this->db->rollback();
1537 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1538 }
1539
1540 if (isModEnabled("bank")) {
1541 $label = '(CustomerInvoicePayment)';
1542
1543 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1544 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1545 }
1546 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1547 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1548 }
1549 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1550 if ($result < 0) {
1551 $this->db->rollback();
1552 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1553 }
1554 }
1555
1556 $this->db->commit();
1557
1558 return $payment_id;
1559 }
1560
1587 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1588 {
1589 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1590
1591 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1592 throw new RestException(403);
1593 }
1594 foreach ($arrayofamounts as $id => $amount) {
1595 if (empty($id)) {
1596 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1597 }
1598 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1599 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1600 }
1601 }
1602
1603 if (isModEnabled("bank")) {
1604 if (empty($accountid)) {
1605 throw new RestException(400, 'Account ID is mandatory');
1606 }
1607 }
1608 if (empty($paymentid)) {
1609 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1610 }
1611
1612 $this->db->begin();
1613
1614 $amounts = array();
1615 $multicurrency_amounts = array();
1616
1617 // Loop on each invoice to pay
1618 foreach ($arrayofamounts as $id => $amountarray) {
1619 $result = $this->invoice->fetch($id);
1620 if (!$result) {
1621 $this->db->rollback();
1622 throw new RestException(404, 'Invoice ID '.$id.' not found');
1623 }
1624
1625 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1626 $this->db->rollback();
1627 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1628 }
1629
1630 $is_multicurrency = 0;
1631 $total_ttc = $this->invoice->total_ttc;
1632
1633 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1634 $is_multicurrency = 1;
1635 $total_ttc = $this->invoice->multicurrency_total_ttc;
1636 }
1637
1638 // Calculate amount to pay
1639 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1640 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1641 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1642 $remainstopay = $amount = price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1643
1644 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1645 $amount = price2num($amountarray["amount"], 'MT');
1646 }
1647
1648 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1649 $amount = price2num($amountarray["multicurrency_amount"], 'MT');
1650 }
1651
1652 if ($amount > $remainstopay && !$accepthigherpayment) {
1653 $this->db->rollback();
1654 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1655 }
1656
1657 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1658 $amount = price2num(-1 * (float) $amount, 'MT');
1659 }
1660
1661 if ($is_multicurrency) {
1662 $amounts[$id] = null;
1663 // Multicurrency
1664 $multicurrency_amounts[$id] = (float) $amount;
1665 } else {
1666 $amounts[$id] = (float) $amount;
1667 // Multicurrency
1668 $multicurrency_amounts[$id] = null;
1669 }
1670 }
1671
1672 // Creation of payment line
1673 $paymentobj = new Paiement($this->db);
1674 $paymentobj->datepaye = $datepaye;
1675 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1676 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1677 $paymentobj->paiementid = $paymentid;
1678 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1);
1679 $paymentobj->num_payment = $num_payment;
1680 $paymentobj->note_private = $comment;
1681 $paymentobj->ref_ext = $ref_ext;
1682 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1683 if ($payment_id < 0) {
1684 $this->db->rollback();
1685 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1686 }
1687 if (isModEnabled("bank")) {
1688 $label = '(CustomerInvoicePayment)';
1689 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1690 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1691 }
1692 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1693 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1694 }
1695 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1696 if ($result < 0) {
1697 $this->db->rollback();
1698 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1699 }
1700 }
1701
1702 $this->db->commit();
1703
1704 return $payment_id;
1705 }
1706
1721 public function putPayment($id, $num_payment = '')
1722 {
1723 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1724
1725 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1726 throw new RestException(403);
1727 }
1728 if (empty($id)) {
1729 throw new RestException(400, 'Payment ID is mandatory');
1730 }
1731
1732 $paymentobj = new Paiement($this->db);
1733 $result = $paymentobj->fetch($id);
1734
1735 if (!$result) {
1736 throw new RestException(404, 'Payment not found');
1737 }
1738
1739 if (!empty($num_payment)) {
1740 $result = $paymentobj->update_num($num_payment);
1741 if ($result < 0) {
1742 throw new RestException(500, 'Error when updating the payment num');
1743 }
1744 }
1745
1746 return [
1747 'success' => [
1748 'code' => 200,
1749 'message' => 'Payment updated'
1750 ]
1751 ];
1752 }
1753
1754 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1761 protected function _cleanObjectDatas($object)
1762 {
1763 // phpcs:enable
1764 $object = parent::_cleanObjectDatas($object);
1765
1766 unset($object->note);
1767 unset($object->address);
1768 unset($object->barcode_type);
1769 unset($object->barcode_type_code);
1770 unset($object->barcode_type_label);
1771 unset($object->barcode_type_coder);
1772 unset($object->canvas);
1773
1774 return $object;
1775 }
1776
1785 private function _validate($data)
1786 {
1787 $invoice = array();
1788 foreach (Invoices::$FIELDS as $field) {
1789 if (!isset($data[$field])) {
1790 throw new RestException(400, "$field field missing");
1791 }
1792 $invoice[$field] = $data[$field];
1793 }
1794 return $invoice;
1795 }
1796
1797
1811 public function getTemplateInvoice($id, $contact_list = 1)
1812 {
1813 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
1814 }
1815
1829 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
1830 {
1831 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1832 throw new RestException(403);
1833 }
1834
1835 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
1836 if (!$result) {
1837 throw new RestException(404, 'Template invoice not found');
1838 }
1839
1840 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
1841 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1842 }
1843
1844 // Add external contacts ids
1845 if ($contact_list > -1) {
1846 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
1847 if (is_array($tmparray)) {
1848 $this->template_invoice->contacts_ids = $tmparray;
1849 }
1850 }
1851
1852 $this->template_invoice->fetchObjectLinked();
1853 return $this->_cleanTemplateObjectDatas($this->template_invoice);
1854 }
1855
1856
1857 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1865 {
1866 // phpcs:enable
1867 $object = parent::_cleanObjectDatas($object);
1868
1869 unset($object->note);
1870 unset($object->address);
1871 unset($object->barcode_type);
1872 unset($object->barcode_type_code);
1873 unset($object->barcode_type_label);
1874 unset($object->barcode_type_coder);
1875 unset($object->canvas);
1876
1877 return $object;
1878 }
1879}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
Class to manage customers orders.
Class to manage contracts.
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.
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:426
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.