dolibarr 21.0.0-beta
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
877 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
878 {
879 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
880 throw new RestException(403);
881 }
882 $result = $this->invoice->fetch($id);
883 if (!$result) {
884 throw new RestException(404, 'Invoice not found');
885 }
886
887 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
888 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
889 }
890
891 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
892 if ($result < 0) {
893 throw new RestException(500, 'Error : '.$this->invoice->error);
894 }
895
896 $result = $this->invoice->fetch($id);
897 if (!$result) {
898 throw new RestException(404, 'Invoice not found');
899 }
900
901 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
902 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
903 }
904
905 return $this->_cleanObjectDatas($this->invoice);
906 }
907
908
909
925 public function settodraft($id, $idwarehouse = -1)
926 {
927 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
928 throw new RestException(403);
929 }
930 $result = $this->invoice->fetch($id);
931 if (!$result) {
932 throw new RestException(404, 'Invoice not found');
933 }
934
935 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
936 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
937 }
938
939 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
940 if ($result == 0) {
941 throw new RestException(304, 'Nothing done.');
942 }
943 if ($result < 0) {
944 throw new RestException(500, 'Error : '.$this->invoice->error);
945 }
946
947 $result = $this->invoice->fetch($id);
948 if (!$result) {
949 throw new RestException(404, 'Invoice not found');
950 }
951
952 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
953 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
954 }
955
956 return $this->_cleanObjectDatas($this->invoice);
957 }
958
959
977 public function validate($id, $force_number = '', $idwarehouse = 0, $notrigger = 0)
978 {
979 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
980 throw new RestException(403);
981 }
982 $result = $this->invoice->fetch($id);
983 if (!$result) {
984 throw new RestException(404, 'Invoice not found');
985 }
986
987 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
988 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
989 }
990
991 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
992 if ($result == 0) {
993 throw new RestException(304, 'Error nothing done. May be object is already validated');
994 }
995 if ($result < 0) {
996 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
997 }
998
999 $result = $this->invoice->fetch($id);
1000 if (!$result) {
1001 throw new RestException(404, 'Invoice not found');
1002 }
1003
1004 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1005 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1006 }
1007
1008 // copy from order
1009 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1010 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $this->invoice->ref);
1011
1012 return $this->_cleanObjectDatas($this->invoice);
1013 }
1014
1030 public function settopaid($id, $close_code = '', $close_note = '')
1031 {
1032 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1033 throw new RestException(403);
1034 }
1035 $result = $this->invoice->fetch($id);
1036 if (!$result) {
1037 throw new RestException(404, 'Invoice not found');
1038 }
1039
1040 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1041 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1042 }
1043
1044 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1045 if ($result == 0) {
1046 throw new RestException(304, 'Error nothing done. May be object is already validated');
1047 }
1048 if ($result < 0) {
1049 throw new RestException(500, 'Error : '.$this->invoice->error);
1050 }
1051
1052
1053 $result = $this->invoice->fetch($id);
1054 if (!$result) {
1055 throw new RestException(404, 'Invoice not found');
1056 }
1057
1058 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1059 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1060 }
1061
1062 return $this->_cleanObjectDatas($this->invoice);
1063 }
1064
1065
1079 public function settounpaid($id)
1080 {
1081 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1082 throw new RestException(403);
1083 }
1084 $result = $this->invoice->fetch($id);
1085 if (!$result) {
1086 throw new RestException(404, 'Invoice not found');
1087 }
1088
1089 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1090 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1091 }
1092
1093 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1094 if ($result == 0) {
1095 throw new RestException(304, 'Nothing done');
1096 }
1097 if ($result < 0) {
1098 throw new RestException(500, 'Error : '.$this->invoice->error);
1099 }
1100
1101
1102 $result = $this->invoice->fetch($id);
1103 if (!$result) {
1104 throw new RestException(404, 'Invoice not found');
1105 }
1106
1107 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1108 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1109 }
1110
1111 return $this->_cleanObjectDatas($this->invoice);
1112 }
1113
1122 public function getDiscount($id)
1123 {
1124 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1125
1126 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1127 throw new RestException(403);
1128 }
1129
1130 $result = $this->invoice->fetch($id);
1131 if (!$result) {
1132 throw new RestException(404, 'Invoice not found');
1133 }
1134
1135 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1136 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1137 }
1138
1139 $discountcheck = new DiscountAbsolute($this->db);
1140 $result = $discountcheck->fetch(0, $this->invoice->id);
1141
1142 if ($result == 0) {
1143 throw new RestException(404, 'Discount not found');
1144 }
1145 if ($result < 0) {
1146 throw new RestException(500, $discountcheck->error);
1147 }
1148
1149 return parent::_cleanObjectDatas($discountcheck);
1150 }
1151
1166 {
1167 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1168
1169 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1170 throw new RestException(403);
1171 }
1172
1173 $result = $this->invoice->fetch($id);
1174 if (!$result) {
1175 throw new RestException(404, 'Invoice not found');
1176 }
1177
1178 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1179 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1180 }
1181
1182 if ($this->invoice->paye) {
1183 throw new RestException(500, 'Alreay paid');
1184 }
1185
1186 $this->invoice->fetch($id);
1187 $this->invoice->fetch_thirdparty();
1188
1189 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1190 $discountcheck = new DiscountAbsolute($this->db);
1191 $result = $discountcheck->fetch(0, $this->invoice->id);
1192
1193 $canconvert = 0;
1194 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1195 $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)
1196 }
1197 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1198 $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)
1199 }
1200 if ($canconvert) {
1201 $this->db->begin();
1202
1203 $amount_ht = $amount_tva = $amount_ttc = array();
1204 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1205 '
1206 @phan-var-force array<string,float> $amount_ht
1207 @phan-var-force array<string,float> $amount_tva
1208 @phan-var-force array<string,float> $amount_ttc
1209 @phan-var-force array<string,float> $multicurrency_amount_ht
1210 @phan-var-force array<string,float> $multicurrency_amount_tva
1211 @phan-var-force array<string,float> $multicurrency_amount_ttc
1212 ';
1213
1214 // Loop on each vat rate
1215 $i = 0;
1216 foreach ($this->invoice->lines as $line) {
1217 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1218 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1219 $amount_ht[$line->tva_tx] = 0.0;
1220 $amount_tva[$line->tva_tx] = 0.0;
1221 $amount_ttc[$line->tva_tx] = 0.0;
1222 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1223 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1224 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1225 }
1226 // no need to create discount if amount is null
1227 $amount_ht[$line->tva_tx] += $line->total_ht;
1228 $amount_tva[$line->tva_tx] += $line->total_tva;
1229 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1230 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1231 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1232 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1233 $i++;
1234 }
1235 }
1236
1237 // Insert one discount by VAT rate category
1238 $discount = new DiscountAbsolute($this->db);
1239 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1240 $discount->description = '(CREDIT_NOTE)';
1241 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1242 $discount->description = '(DEPOSIT)';
1243 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1244 $discount->description = '(EXCESS RECEIVED)';
1245 } else {
1246 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1247 }
1248
1249 $discount->fk_soc = $this->invoice->socid;
1250 $discount->socid = $this->invoice->socid;
1251 $discount->fk_facture_source = $this->invoice->id;
1252
1253 $error = 0;
1254
1255 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1256 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1257
1258 // Total payments
1259 $sql = 'SELECT SUM(pf.amount) as total_payments';
1260 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1261 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1262 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1263 $sql .= ' AND pf.fk_paiement = p.rowid';
1264 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1265 $resql = $this->db->query($sql);
1266 if (!$resql) {
1267 dol_print_error($this->db);
1268 }
1269
1270 $res = $this->db->fetch_object($resql);
1271 $total_payments = $res->total_payments;
1272
1273 // Total credit note and deposit
1274 $total_creditnote_and_deposit = 0;
1275 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1276 $sql .= " re.description, re.fk_facture_source";
1277 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1278 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1279 $resql = $this->db->query($sql);
1280 if (!empty($resql)) {
1281 while ($obj = $this->db->fetch_object($resql)) {
1282 $total_creditnote_and_deposit += $obj->amount_ttc;
1283 }
1284 } else {
1285 dol_print_error($this->db);
1286 }
1287
1288 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1289 $discount->amount_tva = 0;
1290 $discount->tva_tx = 0;
1291
1292 $result = $discount->create(DolibarrApiAccess::$user);
1293 if ($result < 0) {
1294 $error++;
1295 }
1296 }
1297 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1298 foreach ($amount_ht as $tva_tx => $xxx) {
1299 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1300 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1301 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1302 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1303 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1304 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1305 $discount->tva_tx = abs((float) $tva_tx);
1306
1307 $result = $discount->create(DolibarrApiAccess::$user);
1308 if ($result < 0) {
1309 $error++;
1310 break;
1311 }
1312 }
1313 }
1314
1315 if (empty($error)) {
1316 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1317 // Set the invoice as paid
1318 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1319 if ($result >= 0) {
1320 $this->db->commit();
1321 } else {
1322 $this->db->rollback();
1323 throw new RestException(500, 'Could not set paid');
1324 }
1325 } else {
1326 $this->db->commit();
1327 }
1328 } else {
1329 $this->db->rollback();
1330 throw new RestException(500, 'Discount creation error');
1331 }
1332 }
1333
1334 return $this->_cleanObjectDatas($this->invoice);
1335 }
1336
1353 public function useDiscount($id, $discountid)
1354 {
1355 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1356 throw new RestException(403);
1357 }
1358 if (empty($id)) {
1359 throw new RestException(400, 'Invoice ID is mandatory');
1360 }
1361 if (empty($discountid)) {
1362 throw new RestException(400, 'Discount ID is mandatory');
1363 }
1364
1365 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1366 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1367 }
1368
1369 $result = $this->invoice->fetch($id);
1370 if (!$result) {
1371 throw new RestException(404, 'Invoice not found');
1372 }
1373
1374 $result = $this->invoice->insert_discount($discountid);
1375 if ($result < 0) {
1376 throw new RestException(405, $this->invoice->error);
1377 }
1378
1379 return $result;
1380 }
1381
1398 public function useCreditNote($id, $discountid)
1399 {
1400 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1401
1402 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1403 throw new RestException(403);
1404 }
1405 if (empty($id)) {
1406 throw new RestException(400, 'Invoice ID is mandatory');
1407 }
1408 if (empty($discountid)) {
1409 throw new RestException(400, 'Credit ID is mandatory');
1410 }
1411
1412 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1413 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1414 }
1415 $discount = new DiscountAbsolute($this->db);
1416 $result = $discount->fetch($discountid);
1417 if (!$result) {
1418 throw new RestException(404, 'Credit not found');
1419 }
1420
1421 $result = $discount->link_to_invoice(0, $id);
1422 if ($result < 0) {
1423 throw new RestException(405, $discount->error);
1424 }
1425
1426 return $result;
1427 }
1428
1442 public function getPayments($id)
1443 {
1444 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1445 throw new RestException(403);
1446 }
1447 if (empty($id)) {
1448 throw new RestException(400, 'Invoice ID is mandatory');
1449 }
1450
1451 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1452 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1453 }
1454
1455 $result = $this->invoice->fetch($id);
1456 if (!$result) {
1457 throw new RestException(404, 'Invoice not found');
1458 }
1459
1460 $result = $this->invoice->getListOfPayments();
1461 if ($result < 0) {
1462 throw new RestException(405, $this->invoice->error);
1463 }
1464
1465 return $result;
1466 }
1467
1468
1490 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1491 {
1492 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1493
1494 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1495 throw new RestException(403);
1496 }
1497 if (empty($id)) {
1498 throw new RestException(400, 'Invoice ID is mandatory');
1499 }
1500
1501 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1502 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1503 }
1504
1505 if (isModEnabled("bank")) {
1506 if (empty($accountid)) {
1507 throw new RestException(400, 'Account ID is mandatory');
1508 }
1509 }
1510
1511 if (empty($paymentid)) {
1512 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1513 }
1514
1515
1516 $result = $this->invoice->fetch($id);
1517 if (!$result) {
1518 throw new RestException(404, 'Invoice not found');
1519 }
1520
1521 // Calculate amount to pay
1522 $totalpaid = $this->invoice->getSommePaiement();
1523 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1524 $totaldeposits = $this->invoice->getSumDepositsUsed();
1525 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1526
1527 $this->db->begin();
1528
1529 $amounts = array();
1530 $multicurrency_amounts = array();
1531
1532 // Clean parameters amount if payment is for a credit note
1533 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1534 $resteapayer = price2num($resteapayer, 'MT');
1535 $amounts[$id] = (float) price2num(-1 * (float) $resteapayer, 'MT');
1536 // Multicurrency
1537 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1538 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1539 } else {
1540 $resteapayer = price2num($resteapayer, 'MT');
1541 $amounts[$id] = (float) $resteapayer;
1542 // Multicurrency
1543 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1544 $multicurrency_amounts[$id] = (float) $newvalue;
1545 }
1546
1547 // Creation of payment line
1548 $paymentobj = new Paiement($this->db);
1549 if (is_numeric($datepaye)) {
1550 $paymentobj->datepaye = $datepaye;
1551 } else {
1552 $paymentobj->datepaye = dol_stringtotime($datepaye);
1553 }
1554 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1555 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1556 $paymentobj->paiementid = $paymentid;
1557 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1558 $paymentobj->num_payment = $num_payment;
1559 $paymentobj->note_private = $comment;
1560
1561 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1562 if ($payment_id < 0) {
1563 $this->db->rollback();
1564 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1565 }
1566
1567 if (isModEnabled("bank")) {
1568 $label = '(CustomerInvoicePayment)';
1569
1570 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1571 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1572 }
1573 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1574 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1575 }
1576 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1577 if ($result < 0) {
1578 $this->db->rollback();
1579 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1580 }
1581 }
1582
1583 $this->db->commit();
1584
1585 return $payment_id;
1586 }
1587
1614 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1615 {
1616 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1617
1618 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1619 throw new RestException(403);
1620 }
1621 foreach ($arrayofamounts as $id => $amount) {
1622 if (empty($id)) {
1623 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1624 }
1625 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1626 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1627 }
1628 }
1629
1630 if (isModEnabled("bank")) {
1631 if (empty($accountid)) {
1632 throw new RestException(400, 'Account ID is mandatory');
1633 }
1634 }
1635 if (empty($paymentid)) {
1636 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1637 }
1638
1639 $this->db->begin();
1640
1641 $amounts = array();
1642 $multicurrency_amounts = array();
1643
1644 // Loop on each invoice to pay
1645 foreach ($arrayofamounts as $id => $amountarray) {
1646 $result = $this->invoice->fetch($id);
1647 if (!$result) {
1648 $this->db->rollback();
1649 throw new RestException(404, 'Invoice ID '.$id.' not found');
1650 }
1651
1652 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1653 $this->db->rollback();
1654 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1655 }
1656
1657 $is_multicurrency = 0;
1658 $total_ttc = $this->invoice->total_ttc;
1659
1660 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1661 $is_multicurrency = 1;
1662 $total_ttc = $this->invoice->multicurrency_total_ttc;
1663 }
1664
1665 // Calculate amount to pay
1666 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1667 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1668 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1669 $remainstopay = $amount = price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1670
1671 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1672 $amount = price2num($amountarray["amount"], 'MT');
1673 }
1674
1675 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1676 $amount = price2num($amountarray["multicurrency_amount"], 'MT');
1677 }
1678
1679 if ($amount > $remainstopay && !$accepthigherpayment) {
1680 $this->db->rollback();
1681 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1682 }
1683
1684 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1685 $amount = price2num(-1 * (float) $amount, 'MT');
1686 }
1687
1688 if ($is_multicurrency) {
1689 $amounts[$id] = null;
1690 // Multicurrency
1691 $multicurrency_amounts[$id] = (float) $amount;
1692 } else {
1693 $amounts[$id] = (float) $amount;
1694 // Multicurrency
1695 $multicurrency_amounts[$id] = null;
1696 }
1697 }
1698
1699 // Creation of payment line
1700 $paymentobj = new Paiement($this->db);
1701 if (is_numeric($datepaye)) {
1702 $paymentobj->datepaye = $datepaye;
1703 } else {
1704 $paymentobj->datepaye = dol_stringtotime($datepaye);
1705 }
1706 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1707 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1708 $paymentobj->paiementid = $paymentid;
1709 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1710 $paymentobj->num_payment = $num_payment;
1711 $paymentobj->note_private = $comment;
1712 $paymentobj->ref_ext = $ref_ext;
1713 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1714 if ($payment_id < 0) {
1715 $this->db->rollback();
1716 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1717 }
1718 if (isModEnabled("bank")) {
1719 $label = '(CustomerInvoicePayment)';
1720 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1721 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1722 }
1723 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1724 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1725 }
1726 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1727 if ($result < 0) {
1728 $this->db->rollback();
1729 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1730 }
1731 }
1732
1733 $this->db->commit();
1734
1735 return $payment_id;
1736 }
1737
1752 public function putPayment($id, $num_payment = '')
1753 {
1754 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1755
1756 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1757 throw new RestException(403);
1758 }
1759 if (empty($id)) {
1760 throw new RestException(400, 'Payment ID is mandatory');
1761 }
1762
1763 $paymentobj = new Paiement($this->db);
1764 $result = $paymentobj->fetch($id);
1765
1766 if (!$result) {
1767 throw new RestException(404, 'Payment not found');
1768 }
1769
1770 if (!empty($num_payment)) {
1771 $result = $paymentobj->update_num($num_payment);
1772 if ($result < 0) {
1773 throw new RestException(500, 'Error when updating the payment num');
1774 }
1775 }
1776
1777 return [
1778 'success' => [
1779 'code' => 200,
1780 'message' => 'Payment updated'
1781 ]
1782 ];
1783 }
1784
1785 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1792 protected function _cleanObjectDatas($object)
1793 {
1794 // phpcs:enable
1795 $object = parent::_cleanObjectDatas($object);
1796
1797 unset($object->note);
1798 unset($object->address);
1799 unset($object->barcode_type);
1800 unset($object->barcode_type_code);
1801 unset($object->barcode_type_label);
1802 unset($object->barcode_type_coder);
1803 unset($object->canvas);
1804
1805 return $object;
1806 }
1807
1816 private function _validate($data)
1817 {
1818 $invoice = array();
1819 foreach (Invoices::$FIELDS as $field) {
1820 if (!isset($data[$field])) {
1821 throw new RestException(400, "$field field missing");
1822 }
1823 $invoice[$field] = $data[$field];
1824 }
1825 return $invoice;
1826 }
1827
1828
1842 public function getTemplateInvoice($id, $contact_list = 1)
1843 {
1844 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
1845 }
1846
1860 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
1861 {
1862 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1863 throw new RestException(403);
1864 }
1865
1866 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
1867 if (!$result) {
1868 throw new RestException(404, 'Template invoice not found');
1869 }
1870
1871 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
1872 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1873 }
1874
1875 // Add external contacts ids
1876 if ($contact_list > -1) {
1877 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
1878 if (is_array($tmparray)) {
1879 $this->template_invoice->contacts_ids = $tmparray;
1880 }
1881 }
1882
1883 $this->template_invoice->fetchObjectLinked();
1884 return $this->_cleanTemplateObjectDatas($this->template_invoice);
1885 }
1886
1887
1888 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1896 {
1897 // phpcs:enable
1898 $object = parent::_cleanObjectDatas($object);
1899
1900 unset($object->note);
1901 unset($object->address);
1902 unset($object->barcode_type);
1903 unset($object->barcode_type_code);
1904 unset($object->barcode_type_label);
1905 unset($object->barcode_type_coder);
1906 unset($object->canvas);
1907
1908 return $object;
1909 }
1910}
$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: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.
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
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.