dolibarr 21.0.3
api_invoices.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2020 Thibault FOUCART <support@ptibogxiv.net>
4 * 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
189 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0)
190 {
191 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
192 throw new RestException(403);
193 }
194
195 $obj_ret = array();
196
197 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
198 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
199
200 // If the internal user must only see his customers, force searching by him
201 $search_sale = 0;
202 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
203 $search_sale = DolibarrApiAccess::$user->id;
204 }
205
206 $sql = "SELECT t.rowid";
207 $sql .= " FROM ".MAIN_DB_PREFIX."facture AS t";
208 $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
209 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
210 if ($socids) {
211 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
212 }
213 // Search on sale representative
214 if ($search_sale && $search_sale != '-1') {
215 if ($search_sale == -2) {
216 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
217 } elseif ($search_sale > 0) {
218 $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).")";
219 }
220 }
221 // Filter by status
222 if ($status == 'draft') {
223 $sql .= " AND t.fk_statut IN (0)";
224 }
225 if ($status == 'unpaid') {
226 $sql .= " AND t.fk_statut IN (1)";
227 }
228 if ($status == 'paid') {
229 $sql .= " AND t.fk_statut IN (2)";
230 }
231 if ($status == 'cancelled') {
232 $sql .= " AND t.fk_statut IN (3)";
233 }
234 // Add sql filters
235 if ($sqlfilters) {
236 $errormessage = '';
237 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
238 if ($errormessage) {
239 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
240 }
241 }
242
243 //this query will return total invoices with the filters given
244 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
245
246 $sql .= $this->db->order($sortfield, $sortorder);
247 if ($limit) {
248 if ($page < 0) {
249 $page = 0;
250 }
251 $offset = $limit * $page;
252
253 $sql .= $this->db->plimit($limit + 1, $offset);
254 }
255
256 $result = $this->db->query($sql);
257 if ($result) {
258 $i = 0;
259 $num = $this->db->num_rows($result);
260 $min = min($num, ($limit <= 0 ? $num : $limit));
261 while ($i < $min) {
262 $obj = $this->db->fetch_object($result);
263 $invoice_static = new Facture($this->db);
264 if ($invoice_static->fetch($obj->rowid) > 0) {
265 // Get payment details
266 $invoice_static->totalpaid = $invoice_static->getSommePaiement();
267 $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed();
268 $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
269 $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT');
270
271 // Add external contacts ids
272 $tmparray = $invoice_static->liste_contact(-1, 'external', 1);
273 if (is_array($tmparray)) {
274 $invoice_static->contacts_ids = $tmparray;
275 }
276
277 if ($loadlinkedobjects) {
278 // retrieve linked objects
279 $invoice_static->fetchObjectLinked();
280 }
281
282 // Add online_payment_url, copied from order
283 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
284 $invoice_static->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $invoice_static->ref);
285
286 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
287 }
288 $i++;
289 }
290 } else {
291 throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror());
292 }
293
294 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
295 if ($pagination_data) {
296 $totalsResult = $this->db->query($sqlTotals);
297 $total = $this->db->fetch_object($totalsResult)->total;
298
299 $tmp = $obj_ret;
300 $obj_ret = [];
301
302 $obj_ret['data'] = $tmp;
303 $obj_ret['pagination'] = [
304 'total' => (int) $total,
305 'page' => $page, //count starts from 0
306 'page_count' => ceil((int) $total / $limit),
307 'limit' => $limit
308 ];
309 }
310
311 return $obj_ret;
312 }
313
320 public function post($request_data = null)
321 {
322 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
323 throw new RestException(403, "Insuffisant rights");
324 }
325 // Check mandatory fields
326 $result = $this->_validate($request_data);
327
328 foreach ($request_data as $field => $value) {
329 if ($field === 'caller') {
330 // 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
331 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
332 continue;
333 }
334
335 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
336 }
337 if (!array_key_exists('date', $request_data)) {
338 $this->invoice->date = dol_now();
339 }
340 /* We keep lines as an array
341 if (isset($request_data["lines"])) {
342 $lines = array();
343 foreach ($request_data["lines"] as $line) {
344 array_push($lines, (object) $line);
345 }
346 $this->invoice->lines = $lines;
347 }*/
348
349 if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) {
350 throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors));
351 }
352 return ((int) $this->invoice->id);
353 }
354
368 public function createInvoiceFromOrder($orderid)
369 {
370 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
371
372 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
373 throw new RestException(403);
374 }
375 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
376 throw new RestException(403);
377 }
378 if (empty($orderid)) {
379 throw new RestException(400, 'Order ID is mandatory');
380 }
381
382 $order = new Commande($this->db);
383 $result = $order->fetch($orderid);
384 if (!$result) {
385 throw new RestException(404, 'Order not found');
386 }
387
388 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
389 if ($result < 0) {
390 throw new RestException(405, $this->invoice->error);
391 }
392 $this->invoice->fetchObjectLinked();
393 return $this->_cleanObjectDatas($this->invoice);
394 }
395
409 public function createInvoiceFromContract($contractid)
410 {
411 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
412
413 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
414 throw new RestException(403);
415 }
416 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
417 throw new RestException(403);
418 }
419 if (empty($contractid)) {
420 throw new RestException(400, 'Contract ID is mandatory');
421 }
422
423 $contract = new Contrat($this->db);
424 $result = $contract->fetch($contractid);
425 if (!$result) {
426 throw new RestException(404, 'Contract not found');
427 }
428
429 $result = $this->invoice->createFromContract($contract, DolibarrApiAccess::$user);
430 if ($result < 0) {
431 throw new RestException(405, $this->invoice->error);
432 }
433 $this->invoice->fetchObjectLinked();
434 return $this->_cleanObjectDatas($this->invoice);
435 }
436
445 public function getLines($id)
446 {
447 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
448 throw new RestException(403);
449 }
450
451 $result = $this->invoice->fetch($id);
452 if (!$result) {
453 throw new RestException(404, 'Invoice not found');
454 }
455
456 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
457 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
458 }
459 $this->invoice->getLinesArray();
460 $result = array();
461 foreach ($this->invoice->lines as $line) {
462 array_push($result, $this->_cleanObjectDatas($line));
463 }
464 return $result;
465 }
466
481 public function putLine($id, $lineid, $request_data = null)
482 {
483 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
484 throw new RestException(403);
485 }
486
487 $result = $this->invoice->fetch($id);
488 if (!$result) {
489 throw new RestException(404, 'Invoice not found');
490 }
491
492 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
493 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
494 }
495
496 $request_data = (object) $request_data;
497
498 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
499 $request_data->label = sanitizeVal($request_data->label);
500
501 $updateRes = $this->invoice->updateline(
502 $lineid,
503 $request_data->desc,
504 $request_data->subprice,
505 $request_data->qty,
506 $request_data->remise_percent,
507 $request_data->date_start,
508 $request_data->date_end,
509 $request_data->tva_tx,
510 $request_data->localtax1_tx,
511 $request_data->localtax2_tx,
512 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
513 $request_data->info_bits,
514 $request_data->product_type,
515 $request_data->fk_parent_line,
516 0,
517 $request_data->fk_fournprice,
518 $request_data->pa_ht,
519 $request_data->label,
520 $request_data->special_code,
521 $request_data->array_options,
522 $request_data->situation_percent,
523 $request_data->fk_unit,
524 $request_data->multicurrency_subprice,
525 0,
526 $request_data->ref_ext,
527 $request_data->rang
528 );
529
530 if ($updateRes > 0) {
531 $result = $this->get($id);
532 unset($result->line);
533 return $this->_cleanObjectDatas($result);
534 } else {
535 throw new RestException(304, $this->invoice->error);
536 }
537 }
538
552 public function postContact($id, $contactid, $type)
553 {
554 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
555 throw new RestException(403);
556 }
557
558 $result = $this->invoice->fetch($id);
559
560 if (!$result) {
561 throw new RestException(404, 'Invoice not found');
562 }
563
564 if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) {
565 throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER');
566 }
567
568 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
569 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
570 }
571
572 $result = $this->invoice->add_contact($contactid, $type, 'external');
573
574 if (!$result) {
575 throw new RestException(500, 'Error when added the contact');
576 }
577
578 return array(
579 'success' => array(
580 'code' => 200,
581 'message' => 'Contact linked to the invoice'
582 )
583 );
584 }
585
600 public function deleteContact($id, $contactid, $type)
601 {
602 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
603 throw new RestException(403);
604 }
605
606 $result = $this->invoice->fetch($id);
607
608 if (!$result) {
609 throw new RestException(404, 'Invoice not found');
610 }
611
612 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
613 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
614 }
615
616 $contacts = $this->invoice->liste_contact();
617
618 foreach ($contacts as $contact) {
619 if ($contact['id'] == $contactid && $contact['code'] == $type) {
620 $result = $this->invoice->delete_contact($contact['rowid']);
621
622 if (!$result) {
623 throw new RestException(500, 'Error when deleted the contact');
624 }
625 }
626 }
627
628 return $this->_cleanObjectDatas($this->invoice);
629 }
630
645 public function deleteLine($id, $lineid)
646 {
647 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
648 throw new RestException(403);
649 }
650 if (empty($lineid)) {
651 throw new RestException(400, 'Line ID is mandatory');
652 }
653
654 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
655 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
656 }
657
658 $result = $this->invoice->fetch($id);
659 if (!$result) {
660 throw new RestException(404, 'Invoice not found');
661 }
662
663 $updateRes = $this->invoice->deleteLine($lineid, $id);
664 if ($updateRes > 0) {
665 return $this->get($id);
666 } else {
667 throw new RestException(405, $this->invoice->error);
668 }
669 }
670
678 public function put($id, $request_data = null)
679 {
680 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
681 throw new RestException(403);
682 }
683
684 $result = $this->invoice->fetch($id);
685 if (!$result) {
686 throw new RestException(404, 'Invoice not found');
687 }
688
689 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
690 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
691 }
692
693 foreach ($request_data as $field => $value) {
694 if ($field == 'id') {
695 continue;
696 }
697 if ($field === 'caller') {
698 // 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
699 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
700 continue;
701 }
702 if ($field == 'array_options' && is_array($value)) {
703 foreach ($value as $index => $val) {
704 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
705 }
706 continue;
707 }
708
709 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
710
711 // If cond reglement => update date lim reglement
712 if ($field == 'cond_reglement_id') {
713 $this->invoice->date_lim_reglement = $this->invoice->calculate_date_lim_reglement();
714 }
715 }
716
717 // update bank account
718 if (!empty($this->invoice->fk_account)) {
719 if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) {
720 throw new RestException(400, $this->invoice->error);
721 }
722 }
723
724 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
725 return $this->get($id);
726 } else {
727 throw new RestException(500, $this->invoice->error);
728 }
729 }
730
737 public function delete($id)
738 {
739 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
740 throw new RestException(403);
741 }
742 $result = $this->invoice->fetch($id);
743 if (!$result) {
744 throw new RestException(404, 'Invoice not found');
745 }
746
747 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
748 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
749 }
750
751 $result = $this->invoice->delete(DolibarrApiAccess::$user);
752 if ($result < 0) {
753 throw new RestException(500, 'Error when deleting invoice');
754 } elseif ($result == 0) {
755 throw new RestException(403, 'Invoice not erasable');
756 }
757
758 return array(
759 'success' => array(
760 'code' => 200,
761 'message' => 'Invoice deleted'
762 )
763 );
764 }
765
789 public function postLine($id, $request_data = null)
790 {
791 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
792 throw new RestException(403);
793 }
794
795 $result = $this->invoice->fetch($id);
796 if (!$result) {
797 throw new RestException(404, 'Invoice not found');
798 }
799
800 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
801 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
802 }
803
804 $request_data = (object) $request_data;
805
806 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
807 $request_data->label = sanitizeVal($request_data->label);
808
809 // Reset fk_parent_line for no child products and special product
810 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
811 $request_data->fk_parent_line = 0;
812 }
813
814 // calculate pa_ht
815 $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);
816 $pa_ht = $marginInfos[0];
817
818 $updateRes = $this->invoice->addline(
819 $request_data->desc,
820 $request_data->subprice,
821 $request_data->qty,
822 $request_data->tva_tx,
823 $request_data->localtax1_tx,
824 $request_data->localtax2_tx,
825 $request_data->fk_product,
826 $request_data->remise_percent,
827 $request_data->date_start,
828 $request_data->date_end,
829 $request_data->fk_code_ventilation,
830 $request_data->info_bits,
831 $request_data->fk_remise_except,
832 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
833 $request_data->subprice,
834 $request_data->product_type,
835 $request_data->rang,
836 $request_data->special_code,
837 $request_data->origin,
838 $request_data->origin_id,
839 $request_data->fk_parent_line,
840 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
841 $pa_ht,
842 $request_data->label,
843 $request_data->array_options,
844 $request_data->situation_percent,
845 $request_data->fk_prev_id,
846 $request_data->fk_unit,
847 0,
848 $request_data->ref_ext
849 );
850
851 if ($updateRes < 0) {
852 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
853 }
854
855 return $updateRes;
856 }
857
876 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
877 {
878 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
879 throw new RestException(403);
880 }
881 $result = $this->invoice->fetch($id);
882 if (!$result) {
883 throw new RestException(404, 'Invoice not found');
884 }
885
886 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
887 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
888 }
889
890 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
891 if ($result < 0) {
892 throw new RestException(500, 'Error : '.$this->invoice->error);
893 }
894
895 $result = $this->invoice->fetch($id);
896 if (!$result) {
897 throw new RestException(404, 'Invoice not found');
898 }
899
900 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
901 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
902 }
903
904 return $this->_cleanObjectDatas($this->invoice);
905 }
906
907
908
923 public function settodraft($id, $idwarehouse = -1)
924 {
925 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
926 throw new RestException(403);
927 }
928 $result = $this->invoice->fetch($id);
929 if (!$result) {
930 throw new RestException(404, 'Invoice not found');
931 }
932
933 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
934 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
935 }
936
937 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
938 if ($result == 0) {
939 throw new RestException(304, 'Nothing done.');
940 }
941 if ($result < 0) {
942 throw new RestException(500, 'Error : '.$this->invoice->error);
943 }
944
945 $result = $this->invoice->fetch($id);
946 if (!$result) {
947 throw new RestException(404, 'Invoice not found');
948 }
949
950 return $this->_cleanObjectDatas($this->invoice);
951 }
952
953
971 public function validate($id, $force_number = '', $idwarehouse = 0, $notrigger = 0)
972 {
973 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
974 throw new RestException(403);
975 }
976 $result = $this->invoice->fetch($id);
977 if (!$result) {
978 throw new RestException(404, 'Invoice not found');
979 }
980
981 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
982 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
983 }
984
985 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
986 if ($result == 0) {
987 throw new RestException(304, 'Error nothing done. May be object is already validated');
988 }
989 if ($result < 0) {
990 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
991 }
992
993 $result = $this->invoice->fetch($id);
994 if (!$result) {
995 throw new RestException(404, 'Invoice not found');
996 }
997
998 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
999 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1000 }
1001
1002 // copy from order
1003 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1004 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $this->invoice->ref);
1005
1006 return $this->_cleanObjectDatas($this->invoice);
1007 }
1008
1024 public function settopaid($id, $close_code = '', $close_note = '')
1025 {
1026 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1027 throw new RestException(403);
1028 }
1029 $result = $this->invoice->fetch($id);
1030 if (!$result) {
1031 throw new RestException(404, 'Invoice not found');
1032 }
1033
1034 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1035 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1036 }
1037
1038 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1039 if ($result == 0) {
1040 throw new RestException(304, 'Error nothing done. May be object is already validated');
1041 }
1042 if ($result < 0) {
1043 throw new RestException(500, 'Error : '.$this->invoice->error);
1044 }
1045
1046
1047 $result = $this->invoice->fetch($id);
1048 if (!$result) {
1049 throw new RestException(404, 'Invoice not found');
1050 }
1051
1052 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1053 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1054 }
1055
1056 return $this->_cleanObjectDatas($this->invoice);
1057 }
1058
1059
1073 public function settounpaid($id)
1074 {
1075 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1076 throw new RestException(403);
1077 }
1078 $result = $this->invoice->fetch($id);
1079 if (!$result) {
1080 throw new RestException(404, 'Invoice not found');
1081 }
1082
1083 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1084 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1085 }
1086
1087 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1088 if ($result == 0) {
1089 throw new RestException(304, 'Nothing done');
1090 }
1091 if ($result < 0) {
1092 throw new RestException(500, 'Error : '.$this->invoice->error);
1093 }
1094
1095
1096 $result = $this->invoice->fetch($id);
1097 if (!$result) {
1098 throw new RestException(404, 'Invoice not found');
1099 }
1100
1101 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1102 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1103 }
1104
1105 return $this->_cleanObjectDatas($this->invoice);
1106 }
1107
1116 public function getDiscount($id)
1117 {
1118 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1119
1120 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1121 throw new RestException(403);
1122 }
1123
1124 $result = $this->invoice->fetch($id);
1125 if (!$result) {
1126 throw new RestException(404, 'Invoice not found');
1127 }
1128
1129 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1130 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1131 }
1132
1133 $discountcheck = new DiscountAbsolute($this->db);
1134 $result = $discountcheck->fetch(0, $this->invoice->id);
1135
1136 if ($result == 0) {
1137 throw new RestException(404, 'Discount not found');
1138 }
1139 if ($result < 0) {
1140 throw new RestException(500, $discountcheck->error);
1141 }
1142
1143 return parent::_cleanObjectDatas($discountcheck);
1144 }
1145
1160 {
1161 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1162
1163 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1164 throw new RestException(403);
1165 }
1166
1167 $result = $this->invoice->fetch($id);
1168 if (!$result) {
1169 throw new RestException(404, 'Invoice not found');
1170 }
1171
1172 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1173 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1174 }
1175
1176 if ($this->invoice->paye) {
1177 throw new RestException(500, 'Alreay paid');
1178 }
1179
1180 $this->invoice->fetch($id);
1181 $this->invoice->fetch_thirdparty();
1182
1183 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1184 $discountcheck = new DiscountAbsolute($this->db);
1185 $result = $discountcheck->fetch(0, $this->invoice->id);
1186
1187 $canconvert = 0;
1188 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1189 $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)
1190 }
1191 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1192 $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)
1193 }
1194 if ($canconvert) {
1195 $this->db->begin();
1196
1197 $amount_ht = $amount_tva = $amount_ttc = array();
1198 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1199 '
1200 @phan-var-force array<string,float> $amount_ht
1201 @phan-var-force array<string,float> $amount_tva
1202 @phan-var-force array<string,float> $amount_ttc
1203 @phan-var-force array<string,float> $multicurrency_amount_ht
1204 @phan-var-force array<string,float> $multicurrency_amount_tva
1205 @phan-var-force array<string,float> $multicurrency_amount_ttc
1206 ';
1207
1208 // Loop on each vat rate
1209 $i = 0;
1210 foreach ($this->invoice->lines as $line) {
1211 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1212 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1213 $amount_ht[$line->tva_tx] = 0.0;
1214 $amount_tva[$line->tva_tx] = 0.0;
1215 $amount_ttc[$line->tva_tx] = 0.0;
1216 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1217 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1218 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1219 }
1220 // no need to create discount if amount is null
1221 $amount_ht[$line->tva_tx] += $line->total_ht;
1222 $amount_tva[$line->tva_tx] += $line->total_tva;
1223 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1224 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1225 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1226 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1227 $i++;
1228 }
1229 }
1230
1231 // Insert one discount by VAT rate category
1232 $discount = new DiscountAbsolute($this->db);
1233 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1234 $discount->description = '(CREDIT_NOTE)';
1235 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1236 $discount->description = '(DEPOSIT)';
1237 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1238 $discount->description = '(EXCESS RECEIVED)';
1239 } else {
1240 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1241 }
1242
1243 $discount->fk_soc = $this->invoice->socid;
1244 $discount->socid = $this->invoice->socid;
1245 $discount->fk_facture_source = $this->invoice->id;
1246
1247 $error = 0;
1248
1249 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1250 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1251
1252 // Total payments
1253 $sql = 'SELECT SUM(pf.amount) as total_payments';
1254 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1255 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1256 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1257 $sql .= ' AND pf.fk_paiement = p.rowid';
1258 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1259 $resql = $this->db->query($sql);
1260 if (!$resql) {
1261 dol_print_error($this->db);
1262 }
1263
1264 $res = $this->db->fetch_object($resql);
1265 $total_payments = $res->total_payments;
1266
1267 // Total credit note and deposit
1268 $total_creditnote_and_deposit = 0;
1269 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1270 $sql .= " re.description, re.fk_facture_source";
1271 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1272 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1273 $resql = $this->db->query($sql);
1274 if (!empty($resql)) {
1275 while ($obj = $this->db->fetch_object($resql)) {
1276 $total_creditnote_and_deposit += $obj->amount_ttc;
1277 }
1278 } else {
1279 dol_print_error($this->db);
1280 }
1281
1282 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1283 $discount->amount_tva = 0;
1284 $discount->tva_tx = 0;
1285
1286 $result = $discount->create(DolibarrApiAccess::$user);
1287 if ($result < 0) {
1288 $error++;
1289 }
1290 }
1291 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1292 foreach ($amount_ht as $tva_tx => $xxx) {
1293 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1294 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1295 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1296 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1297 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1298 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1299 $discount->tva_tx = abs((float) $tva_tx);
1300
1301 $result = $discount->create(DolibarrApiAccess::$user);
1302 if ($result < 0) {
1303 $error++;
1304 break;
1305 }
1306 }
1307 }
1308
1309 if (empty($error)) {
1310 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1311 // Set the invoice as paid
1312 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1313 if ($result >= 0) {
1314 $this->db->commit();
1315 } else {
1316 $this->db->rollback();
1317 throw new RestException(500, 'Could not set paid');
1318 }
1319 } else {
1320 $this->db->commit();
1321 }
1322 } else {
1323 $this->db->rollback();
1324 throw new RestException(500, 'Discount creation error');
1325 }
1326 }
1327
1328 return $this->_cleanObjectDatas($this->invoice);
1329 }
1330
1347 public function useDiscount($id, $discountid)
1348 {
1349 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1350 throw new RestException(403);
1351 }
1352 if (empty($id)) {
1353 throw new RestException(400, 'Invoice ID is mandatory');
1354 }
1355 if (empty($discountid)) {
1356 throw new RestException(400, 'Discount ID is mandatory');
1357 }
1358
1359 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1360 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1361 }
1362
1363 $result = $this->invoice->fetch($id);
1364 if (!$result) {
1365 throw new RestException(404, 'Invoice not found');
1366 }
1367
1368 $result = $this->invoice->insert_discount($discountid);
1369 if ($result < 0) {
1370 throw new RestException(405, $this->invoice->error);
1371 }
1372
1373 return $result;
1374 }
1375
1392 public function useCreditNote($id, $discountid)
1393 {
1394 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1395
1396 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1397 throw new RestException(403);
1398 }
1399 if (empty($id)) {
1400 throw new RestException(400, 'Invoice ID is mandatory');
1401 }
1402 if (empty($discountid)) {
1403 throw new RestException(400, 'Credit ID is mandatory');
1404 }
1405
1406 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1407 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1408 }
1409 $discount = new DiscountAbsolute($this->db);
1410 $result = $discount->fetch($discountid);
1411 if (!$result) {
1412 throw new RestException(404, 'Credit not found');
1413 }
1414
1415 $result = $discount->link_to_invoice(0, $id);
1416 if ($result < 0) {
1417 throw new RestException(405, $discount->error);
1418 }
1419
1420 return $result;
1421 }
1422
1436 public function getPayments($id)
1437 {
1438 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1439 throw new RestException(403);
1440 }
1441 if (empty($id)) {
1442 throw new RestException(400, 'Invoice ID is mandatory');
1443 }
1444
1445 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1446 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1447 }
1448
1449 $result = $this->invoice->fetch($id);
1450 if (!$result) {
1451 throw new RestException(404, 'Invoice not found');
1452 }
1453
1454 $result = $this->invoice->getListOfPayments();
1455 if (!is_array($result) && $result < 0) {
1456 throw new RestException(405, $this->invoice->error);
1457 }
1458
1459 return $result;
1460 }
1461
1462
1484 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1485 {
1486 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1487
1488 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1489 throw new RestException(403);
1490 }
1491 if (empty($id)) {
1492 throw new RestException(400, 'Invoice ID is mandatory');
1493 }
1494
1495 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1496 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1497 }
1498
1499 if (isModEnabled("bank")) {
1500 if (empty($accountid)) {
1501 throw new RestException(400, 'Account ID is mandatory');
1502 }
1503 }
1504
1505 if (empty($paymentid)) {
1506 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1507 }
1508
1509
1510 $result = $this->invoice->fetch($id);
1511 if (!$result) {
1512 throw new RestException(404, 'Invoice not found');
1513 }
1514
1515 // Calculate amount to pay
1516 $totalpaid = $this->invoice->getSommePaiement();
1517 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1518 $totaldeposits = $this->invoice->getSumDepositsUsed();
1519 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1520
1521 $this->db->begin();
1522
1523 $amounts = array();
1524 $multicurrency_amounts = array();
1525
1526 // Clean parameters amount if payment is for a credit note
1527 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1528 $resteapayer = price2num($resteapayer, 'MT');
1529 $amounts[$id] = (float) price2num(-1 * (float) $resteapayer, 'MT');
1530 // Multicurrency
1531 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1532 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1533 } else {
1534 $resteapayer = price2num($resteapayer, 'MT');
1535 $amounts[$id] = (float) $resteapayer;
1536 // Multicurrency
1537 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1538 $multicurrency_amounts[$id] = (float) $newvalue;
1539 }
1540
1541 // Creation of payment line
1542 $paymentobj = new Paiement($this->db);
1543 if (is_numeric($datepaye)) {
1544 $paymentobj->datepaye = $datepaye;
1545 } else {
1546 $paymentobj->datepaye = dol_stringtotime($datepaye);
1547 }
1548 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1549 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1550 $paymentobj->paiementid = $paymentid;
1551 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1552 $paymentobj->num_payment = $num_payment;
1553 $paymentobj->note_private = $comment;
1554
1555 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1556 if ($payment_id < 0) {
1557 $this->db->rollback();
1558 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1559 }
1560
1561 if (isModEnabled("bank")) {
1562 $label = '(CustomerInvoicePayment)';
1563
1564 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1565 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1566 }
1567 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1568 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1569 }
1570 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1571 if ($result < 0) {
1572 $this->db->rollback();
1573 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1574 }
1575 }
1576
1577 $this->db->commit();
1578
1579 return $payment_id;
1580 }
1581
1608 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1609 {
1610 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1611
1612 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1613 throw new RestException(403);
1614 }
1615 foreach ($arrayofamounts as $id => $amount) {
1616 if (empty($id)) {
1617 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1618 }
1619 if (!DolibarrApi::_checkAccessToResource('facture', (int) $id)) {
1620 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1621 }
1622 }
1623
1624 if (isModEnabled("bank")) {
1625 if (empty($accountid)) {
1626 throw new RestException(400, 'Account ID is mandatory');
1627 }
1628 }
1629 if (empty($paymentid)) {
1630 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1631 }
1632
1633 $this->db->begin();
1634
1635 $amounts = array();
1636 $multicurrency_amounts = array();
1637
1638 // Loop on each invoice to pay
1639 foreach ($arrayofamounts as $id => $amountarray) {
1640 $result = $this->invoice->fetch((int) $id);
1641 if (!$result) {
1642 $this->db->rollback();
1643 throw new RestException(404, 'Invoice ID '.$id.' not found');
1644 }
1645
1646 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1647 $this->db->rollback();
1648 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1649 }
1650
1651 $is_multicurrency = 0;
1652 $total_ttc = $this->invoice->total_ttc;
1653
1654 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1655 $is_multicurrency = 1;
1656 $total_ttc = $this->invoice->multicurrency_total_ttc;
1657 }
1658
1659 // Calculate amount to pay
1660 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1661 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1662 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1663 $remainstopay = $amount = (float) price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1664
1665 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1666 $amount = (float) price2num($amountarray["amount"], 'MT');
1667 }
1668
1669 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1670 $amount = (float) price2num($amountarray["multicurrency_amount"], 'MT');
1671 }
1672
1673 if (abs($amount) > abs($remainstopay) && !$accepthigherpayment) {
1674 $this->db->rollback();
1675 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1676 }
1677
1678 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1679 $amount = (float) price2num(-1 * abs((float) $amount), 'MT');
1680 }
1681
1682 if ($is_multicurrency) {
1683 $amounts[$id] = null;
1684 // Multicurrency
1685 $multicurrency_amounts[$id] = (float) $amount;
1686 } else {
1687 $amounts[$id] = (float) $amount;
1688 // Multicurrency
1689 $multicurrency_amounts[$id] = null;
1690 }
1691 }
1692
1693 // Creation of payment line
1694 $paymentobj = new Paiement($this->db);
1695 if (is_numeric($datepaye)) {
1696 $paymentobj->datepaye = $datepaye;
1697 } else {
1698 $paymentobj->datepaye = dol_stringtotime($datepaye);
1699 }
1700 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1701 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1702 $paymentobj->paiementid = $paymentid;
1703 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1704 $paymentobj->num_payment = $num_payment;
1705 $paymentobj->note_private = $comment;
1706 $paymentobj->ref_ext = $ref_ext;
1707 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1708 if ($payment_id < 0) {
1709 $this->db->rollback();
1710 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1711 }
1712 if (isModEnabled("bank")) {
1713 $label = '(CustomerInvoicePayment)';
1714 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1715 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1716 }
1717 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1718 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1719 }
1720 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1721 if ($result < 0) {
1722 $this->db->rollback();
1723 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1724 }
1725 }
1726
1727 $this->db->commit();
1728
1729 return $payment_id;
1730 }
1731
1746 public function putPayment($id, $num_payment = '')
1747 {
1748 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1749
1750 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1751 throw new RestException(403);
1752 }
1753 if (empty($id)) {
1754 throw new RestException(400, 'Payment ID is mandatory');
1755 }
1756
1757 $paymentobj = new Paiement($this->db);
1758 $result = $paymentobj->fetch($id);
1759
1760 if (!$result) {
1761 throw new RestException(404, 'Payment not found');
1762 }
1763
1764 if (!empty($num_payment)) {
1765 $result = $paymentobj->update_num($num_payment);
1766 if ($result < 0) {
1767 throw new RestException(500, 'Error when updating the payment num');
1768 }
1769 }
1770
1771 return [
1772 'success' => [
1773 'code' => 200,
1774 'message' => 'Payment updated'
1775 ]
1776 ];
1777 }
1778
1779 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1786 protected function _cleanObjectDatas($object)
1787 {
1788 // phpcs:enable
1789 $object = parent::_cleanObjectDatas($object);
1790
1791 unset($object->note);
1792 unset($object->address);
1793 unset($object->barcode_type);
1794 unset($object->barcode_type_code);
1795 unset($object->barcode_type_label);
1796 unset($object->barcode_type_coder);
1797 unset($object->canvas);
1798
1799 return $object;
1800 }
1801
1810 private function _validate($data)
1811 {
1812 if ($data === null) {
1813 $data = array();
1814 }
1815 $invoice = array();
1816 foreach (Invoices::$FIELDS as $field) {
1817 if (!isset($data[$field])) {
1818 throw new RestException(400, "$field field missing");
1819 }
1820 $invoice[$field] = $data[$field];
1821 }
1822 return $invoice;
1823 }
1824
1825
1839 public function getTemplateInvoice($id, $contact_list = 1)
1840 {
1841 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
1842 }
1843
1857 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
1858 {
1859 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1860 throw new RestException(403);
1861 }
1862
1863 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
1864 if (!$result) {
1865 throw new RestException(404, 'Template invoice not found');
1866 }
1867
1868 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
1869 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1870 }
1871
1872 // Add external contacts ids
1873 if ($contact_list > -1) {
1874 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
1875 if (is_array($tmparray)) {
1876 $this->template_invoice->contacts_ids = $tmparray;
1877 }
1878 }
1879
1880 $this->template_invoice->fetchObjectLinked();
1881 return $this->_cleanTemplateObjectDatas($this->template_invoice);
1882 }
1883
1884
1885 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1893 {
1894 // phpcs:enable
1895 $object = parent::_cleanObjectDatas($object);
1896
1897 unset($object->note);
1898 unset($object->address);
1899 unset($object->barcode_type);
1900 unset($object->barcode_type_code);
1901 unset($object->barcode_type_label);
1902 unset($object->barcode_type_coder);
1903 unset($object->canvas);
1904
1905 return $object;
1906 }
1907}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
Class to manage customers orders.
Class to manage absolute discounts.
Class for API REST v1.
Definition api.class.php:31
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:83
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.
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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false, $loadlinkedobjects=0)
List invoices.
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:431
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
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.