dolibarr 25.0.0-alpha
api_supplier_invoices.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2023-2026 Joachim Kueter <git-jk@bloxera.com>
5 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2026 William Mead <william@m34d.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23use Luracast\Restler\RestException;
24
25require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
26require_once DOL_DOCUMENT_ROOT . '/fourn/class/paiementfourn.class.php';
27require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
28
39{
43 public static $FIELDS = array(
44 'socid',
45 );
46
50 public $invoice;
51
55 public function __construct()
56 {
57 global $db;
58 $this->db = $db;
59 $this->invoice = new FactureFournisseur($this->db);
60 }
61
75 public function get($id)
76 {
77 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
78 throw new RestException(403);
79 }
80
81 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
82 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
83 }
84
85 $result = $this->invoice->fetch($id);
86 if (!$result) {
87 throw new RestException(404, 'Supplier invoice not found');
88 }
89
90 // Retrieve credit note ids
91 $this->invoice->getListIdAvoirFromInvoice();
92
93 $this->invoice->fetchObjectLinked();
94 return $this->_cleanObjectDatas($this->invoice);
95 }
96
121 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false)
122 {
123 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
124 throw new RestException(403);
125 }
126
127 $obj_ret = array();
128
129 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
130 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
131
132 // If the internal user must only see his customers, force searching by him
133 $search_sale = 0;
134 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir")) {
135 $search_sale = DolibarrApiAccess::$user->id;
136 }
137
138 $sql = "SELECT t.rowid";
139 $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn AS t";
140 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture_fourn_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
141 $sql .= ' WHERE t.entity IN (' . getEntity('supplier_invoice') . ')';
142 if ($socids) {
143 $sql .= " AND t.fk_soc IN (" . $this->db->sanitize($socids) . ")";
144 }
145 // An unknown value used to be ignored, so the whole list came back as if it were the filtered one
146 if ((string) $status !== '' && !in_array($status, array('draft', 'unpaid', 'paid', 'cancelled'), true)) {
147 throw new RestException(400, "Bad value for parameter status. Expected one of: draft, unpaid, paid, cancelled");
148 }
149 // Filter by status
150 if ($status == 'draft') {
151 $sql .= " AND t.fk_statut IN (0)";
152 }
153 if ($status == 'unpaid') {
154 $sql .= " AND t.fk_statut IN (1)";
155 }
156 if ($status == 'paid') {
157 $sql .= " AND t.fk_statut IN (2)";
158 }
159 if ($status == 'cancelled') {
160 $sql .= " AND t.fk_statut IN (3)";
161 }
162 // Search on sale representative
163 if ($search_sale && $search_sale != '-1') {
164 if ($search_sale == -2) {
165 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
166 } elseif ($search_sale > 0) {
167 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
168 }
169 }
170 // Add sql filters
171 if ($sqlfilters) {
172 $errormessage = '';
173 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
174 if ($errormessage) {
175 throw new RestException(400, 'Error when validating parameter sqlfilters -> ' . $errormessage);
176 }
177 }
178
179 //this query will return total supplier invoices with the filters given
180 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
181
182 $sql .= $this->db->order($sortfield, $sortorder);
183 if ($limit) {
184 if ($page < 0) {
185 $page = 0;
186 }
187 $offset = $limit * $page;
188
189 $sql .= $this->db->plimit($limit + 1, $offset);
190 }
191
192 $result = $this->db->query($sql);
193 if ($result) {
194 $i = 0;
195 $num = $this->db->num_rows($result);
196 $min = min($num, ($limit <= 0 ? $num : $limit));
197 while ($i < $min) {
198 $obj = $this->db->fetch_object($result);
199 $invoice_static = new FactureFournisseur($this->db);
200 if ($invoice_static->fetch($obj->rowid)) {
201 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
202 }
203 $i++;
204 }
205 } else {
206 throw new RestException(503, 'Error when retrieve supplier invoice list : ' . $this->db->lasterror());
207 }
208
209 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
210 if ($pagination_data) {
211 $totalsResult = $this->db->query($sqlTotals);
212 $total = $this->db->fetch_object($totalsResult)->total;
213
214 $tmp = $obj_ret;
215 $obj_ret = [];
216
217 $obj_ret['data'] = $tmp;
218 $obj_ret['pagination'] = [
219 'total' => (int) $total,
220 'page' => $page, //count starts from 0
221 'page_count' => ceil((int) $total / $limit),
222 'limit' => $limit
223 ];
224 }
225
226 return $obj_ret;
227 }
228
247 public function post($request_data = null)
248 {
249 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
250 throw new RestException(403, "Insufficiant rights");
251 }
252
253 if (!is_array($request_data)) {
254 $request_data = array();
255 }
256
257 // Check mandatory fields (not using output, only possible exception is important)
258 $this->_validate($request_data);
259
260 foreach ($request_data as $field => $value) {
261 if ($field === 'caller') {
262 // 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
263 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
264 continue;
265 }
266
267 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
268 }
269 if (!array_key_exists('date', $request_data)) {
270 $this->invoice->date = dol_now();
271 }
272
273 if ($this->invoice->create(DolibarrApiAccess::$user) < 0) {
274 throw new RestException(500, "Error creating invoice ", array_merge(array($this->invoice->error), $this->invoice->errors));
275 }
276 return $this->invoice->id;
277 }
278
293 public function put($id, $request_data = null)
294 {
295 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
296 throw new RestException(403);
297 }
298
299 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
300 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
301 }
302
303 $result = $this->invoice->fetch($id);
304 if (!$result) {
305 throw new RestException(404, 'Supplier invoice not found');
306 }
307
308 if (!is_array($request_data)) {
309 $request_data = array();
310 }
311
312 // Keep the previous values so triggers on BILL_SUPPLIER_MODIFY can see what changed
313 $this->invoice->oldcopy = dol_clone($this->invoice, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
314
315 foreach ($request_data as $field => $value) {
316 if ($field == 'id') {
317 continue;
318 }
319 if ($field === 'caller') {
320 // 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
321 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
322 continue;
323 }
324 if ($field == 'array_options' && is_array($value)) {
325 foreach ($value as $index => $val) {
326 $this->invoice->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->invoice);
327 }
328 continue;
329 }
330
331 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
332 }
333
334 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
335 return $this->get($id);
336 } else {
337 throw new RestException(500, $this->invoice->errorsToString());
338 }
339 }
340
356 public function delete($id)
357 {
358 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "supprimer")) {
359 throw new RestException(403);
360 }
361 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
362 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
363 }
364 $result = $this->invoice->fetch($id);
365 if (!$result) {
366 throw new RestException(404, 'Supplier invoice not found');
367 }
368
369 $result = $this->invoice->delete(DolibarrApiAccess::$user);
370 if ($result < 0) {
371 throw new RestException(500, 'Error when deleting invoice');
372 } elseif ($result == 0) {
373 throw new RestException(403, 'Invoice not erasable');
374 }
375
376 return array(
377 'success' => array(
378 'code' => 200,
379 'message' => 'Supplier invoice deleted'
380 )
381 );
382 }
383
405 public function validate($id, $idwarehouse = 0, $notrigger = 0)
406 {
407 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
408 throw new RestException(403);
409 }
410
411 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
412 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
413 }
414
415 $result = $this->invoice->fetch($id);
416 if (!$result) {
417 throw new RestException(404, 'Invoice not found');
418 }
419
420 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
421 if ($result == 0) {
422 throw new RestException(304, 'Error nothing done. The invoice is already validated');
423 }
424 if ($result < 0) {
425 throw new RestException(500, 'Error when validating Invoice: ' . $this->invoice->errorsToString());
426 }
427
428 return array(
429 'success' => array(
430 'code' => 200,
431 'message' => 'Invoice validated (Ref=' . $this->invoice->ref . ')'
432 )
433 );
434 }
435
453 public function settodraft($id, $idwarehouse = -1, $notrigger = 0)
454 {
455 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
456 throw new RestException(403);
457 }
458 $result = $this->invoice->fetch($id);
459 if (!$result) {
460 throw new RestException(404, 'Invoice not found');
461 }
462
463 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
464 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
465 }
466
467 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
468 if ($result == 0) {
469 throw new RestException(304, 'Nothing done.');
470 }
471 if ($result < 0) {
472 throw new RestException(500, 'Error : ' . $this->invoice->errorsToString());
473 }
474
475 $result = $this->invoice->fetch($id);
476 if (!$result) {
477 throw new RestException(404, 'Invoice not found');
478 }
479
480 return $this->_cleanObjectDatas($this->invoice);
481 }
482
500 public function getPayments($id)
501 {
502 if (empty($id)) {
503 throw new RestException(400, 'Invoice ID is mandatory');
504 }
505
506 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
507 throw new RestException(403);
508 }
509 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
510 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
511 }
512
513 $result = $this->invoice->fetch($id);
514 if (!$result) {
515 throw new RestException(404, 'Invoice not found');
516 }
517
518 $result = $this->invoice->getListOfPayments();
519 if ($this->invoice->errorsToString() !== '') {
520 throw new RestException(405, $this->invoice->errorsToString());
521 }
522
523 return $result;
524 }
525
526
552 public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $amount = null)
553 {
554 if (empty($id)) {
555 throw new RestException(400, 'Invoice ID is mandatory');
556 }
557
558 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
559 throw new RestException(403);
560 }
561 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
562 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
563 }
564
565 $result = $this->invoice->fetch($id);
566 if (!$result) {
567 throw new RestException(404, 'Invoice not found');
568 }
569
570 if (isModEnabled("bank")) {
571 if (empty($accountid)) {
572 throw new RestException(400, 'Bank account ID is mandatory');
573 }
574 }
575
576 if (empty($payment_mode_id)) {
577 throw new RestException(400, 'Payment mode ID is mandatory');
578 }
579
580 if (null !== $amount && $amount > 0) {
581 // We use the amount given in parameter
582 $paymentamount = $amount;
583 } else {
584 // We calculate the remain to pay, and use it as amount
585 $totalpaid = $this->invoice->getSommePaiement();
586 $totaldeposits = $this->invoice->getSumDepositsUsed();
587 $paymentamount = price2num($this->invoice->total_ttc - $totalpaid - $totaldeposits, 'MT');
588 }
589
590 $this->db->begin();
591
592 $amounts = array();
593 $multicurrency_amounts = array();
594
595 $paymentamount = (float) price2num($paymentamount, 'MT');
596
597 $amounts[$id] = $paymentamount;
598
599 // Multicurrency
600 // getWay() switches the payment to the invoice currency as soon as a multicurrency amount is set, so
601 // this value must match the partial amount, not always the full invoice TTC. When a partial amount was
602 // requested, convert it at the invoice rate (multicurrency_total_ttc / total_ttc); otherwise use the
603 // full multicurrency TTC (full payment).
604 if (null !== $amount && $amount > 0 && !empty($this->invoice->total_ttc)) {
605 $newvalue = (float) price2num($paymentamount * $this->invoice->multicurrency_total_ttc / $this->invoice->total_ttc, 'MT');
606 } else {
607 $newvalue = (float) price2num($this->invoice->multicurrency_total_ttc, 'MT');
608 }
609 $multicurrency_amounts[$id] = $newvalue;
610
611 // Creation of payment line
612 $paiement = new PaiementFourn($this->db);
613 $paiement->datepaye = $datepaye;
614 $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
615 $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
616 $paiement->paiementid = $payment_mode_id;
617 $paiement->paiementcode = (string) dol_getIdFromCode($this->db, (string) $payment_mode_id, 'c_paiement', 'id', 'code', 1);
618 $paiement->num_payment = $num_payment;
619 $paiement->note_private = $comment;
620
621 $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
622 if ($paiement_id < 0) {
623 $this->db->rollback();
624 throw new RestException(400, 'Payment error : ' . $paiement->errorsToString());
625 }
626
627 if (isModEnabled("bank")) {
628 $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank);
629 if ($result < 0) {
630 $this->db->rollback();
631 throw new RestException(400, 'Add payment to bank error : ' . $paiement->errorsToString());
632 }
633 }
634
635 $this->db->commit();
636
637 return $paiement_id;
638 }
639
657 public function settopaid($id, $close_code = '', $close_note = '')
658 {
659 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'facture', 'creer')) {
660 throw new RestException(403);
661 }
662
663 $result = $this->invoice->fetch($id);
664 if (!$result) {
665 throw new RestException(404, 'Supplier invoice not found');
666 }
667
668 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
669 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
670 }
671
672 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
673 if ($result == 0) {
674 throw new RestException(304, 'Error nothing done. Maybe object is already paid or not payable.');
675 }
676 if ($result < 0) {
677 throw new RestException(500, 'Error: ' . $this->invoice->errorsToString());
678 }
679
680 $result = $this->invoice->fetch($id);
681 if (!$result) {
682 throw new RestException(404, 'Supplier invoice not found');
683 }
684
685 return $this->_cleanObjectDatas($this->invoice);
686 }
687
703 public function settounpaid($id)
704 {
705 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'facture', 'creer')) {
706 throw new RestException(403);
707 }
708
709 $result = $this->invoice->fetch($id);
710 if (!$result) {
711 throw new RestException(404, 'Supplier invoice not found');
712 }
713
714 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
715 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
716 }
717
718 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
719 if ($result == 0) {
720 throw new RestException(304, 'Nothing done.');
721 }
722 if ($result < 0) {
723 throw new RestException(500, 'Error: ' . $this->invoice->errorsToString());
724 }
725
726 $result = $this->invoice->fetch($id);
727 if (!$result) {
728 throw new RestException(404, 'Supplier invoice not found');
729 }
730
731 return $this->_cleanObjectDatas($this->invoice);
732 }
733
750 public function markAsCreditAvailable($id)
751 {
752 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
753
754 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'facture', 'creer')) {
755 throw new RestException(403);
756 }
757
758 $result = $this->invoice->fetch($id);
759 if ($result <= 0) {
760 throw new RestException(404, 'Supplier invoice not found');
761 }
762
763 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
764 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
765 }
766
767 // Check if there is already a discount (protection to avoid duplicate creation)
768 $discountcheck = new DiscountAbsolute($this->db);
769 $discountcheck->fetch(0, 0, $this->invoice->id);
770 if (!empty($discountcheck->id)) {
771 throw new RestException(409, 'A credit already exists for this supplier invoice');
772 }
773
774 // Same conditions as the button "Convert into credit" of the supplier invoice card
775 $remaintopay = (float) $this->invoice->getRemainToPay(0);
776 if ($this->invoice->status == FactureFournisseur::STATUS_DRAFT) {
777 throw new RestException(400, 'Supplier invoice must be validated');
778 }
779 if ($this->invoice->type == FactureFournisseur::TYPE_STANDARD) {
780 if (!empty($this->invoice->paid) || $remaintopay >= 0) {
781 throw new RestException(400, 'No excess paid on this supplier invoice');
782 }
783 $discountdesc = '(EXCESS PAID)';
784 } elseif ($this->invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
785 if (!empty($this->invoice->paid)) {
786 throw new RestException(400, 'Supplier credit note is already refunded or converted');
787 }
788 if (!getDolGlobalString('SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED') && $this->invoice->getSommePaiement() != 0) {
789 throw new RestException(400, 'Supplier credit note is partially refunded');
790 }
791 $discountdesc = '(CREDIT_NOTE)';
792 } elseif ($this->invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
793 $discountdesc = '(DEPOSIT)';
794 } else {
795 throw new RestException(400, 'Cannot convert into credit a supplier invoice of this type');
796 }
797
798 $this->db->begin();
799
800 $discount = new DiscountAbsolute($this->db);
801 $discount->description = $discountdesc;
802 $discount->discount_type = 1; // Supplier discount
803 $discount->fk_soc = $this->invoice->socid;
804 $discount->socid = $this->invoice->socid;
805 $discount->fk_invoice_supplier_source = $this->invoice->id;
806 $discount->multicurrency_code = $this->invoice->multicurrency_code;
807 $discount->multicurrency_tx = $this->invoice->multicurrency_tx;
808
809 $error = 0;
810
811 if ($this->invoice->type == FactureFournisseur::TYPE_STANDARD) {
812 // Excess paid: one credit with tax included and no VAT
813 $discount->amount_ht = $discount->amount_ttc = -$remaintopay;
814 $discount->amount_tva = 0;
815 $discount->tva_tx = 0;
816 $discount->vat_src_code = '';
817 $discount->multicurrency_total_ht = $discount->multicurrency_total_ttc = (float) price2num((float) $discount->amount_ttc * (float) $this->invoice->multicurrency_tx, 'MT');
818 $discount->multicurrency_total_tva = 0;
819 $discount->multicurrency_amount_ht = $discount->multicurrency_amount_ttc = $discount->multicurrency_total_ttc;
820 $discount->multicurrency_amount_tva = 0;
821
822 if ($discount->create(DolibarrApiAccess::$user) < 0) {
823 $error++;
824 }
825 } else {
826 // One credit per VAT rate
827 $amounts = array();
828 foreach ($this->invoice->lines as $line) {
829 if ($line->product_type < 9 && $line->total_ht != 0) {
830 $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
831 if (!array_key_exists($keyforvatrate, $amounts)) {
832 $amounts[$keyforvatrate] = array('ht' => 0.0, 'tva' => 0.0, 'ttc' => 0.0, 'mht' => 0.0, 'mtva' => 0.0, 'mttc' => 0.0);
833 }
834 $amounts[$keyforvatrate]['ht'] += (float) $line->total_ht;
835 $amounts[$keyforvatrate]['tva'] += (float) $line->total_tva;
836 $amounts[$keyforvatrate]['ttc'] += (float) $line->total_ttc;
837 $amounts[$keyforvatrate]['mht'] += (float) $line->multicurrency_total_ht;
838 $amounts[$keyforvatrate]['mtva'] += (float) $line->multicurrency_total_tva;
839 $amounts[$keyforvatrate]['mttc'] += (float) $line->multicurrency_total_ttc;
840 }
841 }
842
843 // If some payments were already done on the credit note, the credit is reduced with the same prorata
844 if (getDolGlobalString('SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED') && $this->invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
845 $alreadypaid = $this->invoice->getSommePaiement();
846 if ($alreadypaid && abs($alreadypaid) < abs($this->invoice->total_ttc)) {
847 $ratio = abs(($this->invoice->total_ttc - $alreadypaid) / $this->invoice->total_ttc);
848 foreach ($amounts as $keyforvatrate => $vals) {
849 foreach ($vals as $k => $val) {
850 $amounts[$keyforvatrate][$k] = (float) price2num($val * $ratio, 'MU');
851 }
852 }
853 }
854 }
855
856 foreach ($amounts as $keyforvatrate => $vals) {
857 $discount->amount_ht = abs($vals['ht']);
858 $discount->amount_tva = abs($vals['tva']);
859 $discount->amount_ttc = abs($vals['ttc']);
860 $discount->multicurrency_total_ht = $discount->multicurrency_amount_ht = abs($vals['mht']);
861 $discount->multicurrency_total_tva = $discount->multicurrency_amount_tva = abs($vals['mtva']);
862 $discount->multicurrency_total_ttc = $discount->multicurrency_amount_ttc = abs($vals['mttc']);
863
864 $reg = array();
865 $discount->vat_src_code = '';
866 if (preg_match('/\‍((.*)\‍)/', (string) $keyforvatrate, $reg)) {
867 $discount->vat_src_code = $reg[1];
868 }
869 $discount->tva_tx = abs((float) preg_replace('/\s*\‍(.*\‍)/', '', (string) $keyforvatrate));
870
871 if ($discount->create(DolibarrApiAccess::$user) < 0) {
872 $error++;
873 break;
874 }
875 }
876 }
877
878 if ($error) {
879 $this->db->rollback();
880 throw new RestException(500, 'Discount creation error: '.$discount->errorsToString());
881 }
882
883 if ($this->invoice->type != FactureFournisseur::TYPE_DEPOSIT) {
884 if ($this->invoice->setPaid(DolibarrApiAccess::$user) < 0) {
885 $this->db->rollback();
886 throw new RestException(500, 'Could not set paid: '.$this->invoice->errorsToString());
887 }
888 }
889
890 $this->db->commit();
891
892 $this->invoice->fetch($id);
893
894 return $this->_cleanObjectDatas($this->invoice);
895 }
896
916 public function useCreditNote($id, $discountid)
917 {
918 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
919
920 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'facture', 'creer')) {
921 throw new RestException(403);
922 }
923
924 $result = $this->invoice->fetch($id);
925 if ($result <= 0) {
926 throw new RestException(404, 'Supplier invoice not found');
927 }
928
929 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
930 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
931 }
932
933 $discount = new DiscountAbsolute($this->db);
934 $result = $discount->fetch($discountid);
935 if ($result <= 0 || empty($discount->discount_type)) {
936 throw new RestException(404, 'Supplier credit not found');
937 }
938 if ($discount->fk_soc != $this->invoice->socid) {
939 throw new RestException(400, 'Credit does not belong to the supplier of the invoice');
940 }
941 if (!empty($discount->fk_invoice_supplier) || !empty($discount->fk_invoice_supplier_line)) {
942 throw new RestException(409, 'Credit already used');
943 }
944 if ($this->invoice->status != FactureFournisseur::STATUS_VALIDATED) {
945 throw new RestException(400, 'Supplier invoice must be validated and unpaid');
946 }
947 if (price2num($discount->amount_ttc) > price2num($this->invoice->getRemainToPay(0))) {
948 throw new RestException(400, 'Credit is larger than remain to pay, split it before');
949 }
950
951 $this->db->begin();
952
953 $result = $discount->link_to_invoice(0, $this->invoice->id);
954 if ($result < 0) {
955 $this->db->rollback();
956 throw new RestException(500, $discount->errorsToString());
957 }
958
959 if (price2num($this->invoice->getRemainToPay(0)) == 0) {
960 if ($this->invoice->setPaid(DolibarrApiAccess::$user) < 0) {
961 $this->db->rollback();
962 throw new RestException(500, 'Could not set paid: '.$this->invoice->errorsToString());
963 }
964 }
965
966 $this->db->commit();
967
968 return $result;
969 }
970
987 public function getLines($id)
988 {
989 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
990 throw new RestException(403);
991 }
992 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
993 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
994 }
995
996 $result = $this->invoice->fetch($id);
997 if (!$result) {
998 throw new RestException(404, 'Supplier invoice not found');
999 }
1000
1001 $this->invoice->fetch_lines();
1002 $result = array();
1003 foreach ($this->invoice->lines as $line) {
1004 array_push($result, $this->_cleanObjectDatas($line));
1005 }
1006 return $result;
1007 }
1008
1030 public function postLine($id, $request_data = null)
1031 {
1032 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
1033 throw new RestException(403);
1034 }
1035
1036 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
1037 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1038 }
1039
1040 $result = $this->invoice->fetch($id);
1041 if (!$result) {
1042 throw new RestException(404, 'Supplier invoice not found');
1043 }
1044
1045 $request_data = (object) $request_data;
1046
1047 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
1048 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
1049
1050 $updateRes = $this->invoice->addline(
1051 $request_data->description,
1052 $request_data->pu_ht,
1053 $request_data->tva_tx,
1054 $request_data->localtax1_tx,
1055 $request_data->localtax2_tx,
1056 $request_data->qty,
1057 $request_data->fk_product,
1058 $request_data->remise_percent,
1059 $request_data->date_start,
1060 $request_data->date_end,
1061 $request_data->fk_code_ventilation,
1062 $request_data->info_bits,
1063 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
1064 $request_data->product_type,
1065 $request_data->rang,
1066 0,
1067 $request_data->array_options,
1068 $request_data->fk_unit,
1069 $request_data->origin_id,
1070 $request_data->multicurrency_subprice,
1071 $request_data->ref_supplier,
1072 $request_data->special_code
1073 );
1074
1075 if ($updateRes < 0) {
1076 throw new RestException(400, 'Unable to insert the new line. Check your inputs. ' . $this->invoice->errorsToString());
1077 }
1078
1079 return $updateRes;
1080 }
1081
1101 public function putLine($id, $lineid, $request_data = null)
1102 {
1103 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
1104 throw new RestException(403);
1105 }
1106
1107 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
1108 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1109 }
1110
1111 $result = $this->invoice->fetch($id);
1112 if (!$result) {
1113 throw new RestException(404, 'Supplier invoice not found');
1114 }
1115
1116 $invoiceline = new SupplierInvoiceLine($this->db);
1117 if ($invoiceline->fetch($lineid) <= 0) {
1118 throw new RestException(404, 'Supplier invoice line not found');
1119 }
1120 if ($invoiceline->fk_facture_fourn != $this->invoice->id) {
1121 throw new RestException(403, 'Line does not belong to this supplier invoice');
1122 }
1123
1124 $request_data = (object) $request_data;
1125
1126 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
1127 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
1128
1129 $updateRes = $this->invoice->updateline(
1130 $lineid,
1131 $request_data->description,
1132 $request_data->pu_ht,
1133 $request_data->tva_tx,
1134 $request_data->localtax1_tx,
1135 $request_data->localtax2_tx,
1136 $request_data->qty,
1137 $request_data->fk_product,
1138 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
1139 $request_data->info_bits,
1140 $request_data->product_type,
1141 $request_data->remise_percent,
1142 0,
1143 $request_data->date_start,
1144 $request_data->date_end,
1145 $request_data->array_options,
1146 $request_data->fk_unit,
1147 $request_data->multicurrency_subprice,
1148 $request_data->ref_supplier,
1149 $request_data->rang
1150 );
1151
1152 if ($updateRes > 0) {
1153 $result = $this->get($id);
1154 unset($result->line);
1155 return $this->_cleanObjectDatas($result);
1156 } else {
1157 throw new RestException(304, $this->invoice->errorsToString());
1158 }
1159 }
1160
1180 public function deleteLine($id, $lineid)
1181 {
1182 if (empty($lineid)) {
1183 throw new RestException(400, 'Line ID is mandatory');
1184 }
1185
1186 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
1187 throw new RestException(403);
1188 }
1189 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
1190 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1191 }
1192
1193 $result = $this->invoice->fetch($id);
1194 if (!$result) {
1195 throw new RestException(404, 'Supplier invoice not found');
1196 }
1197
1198 $invoiceline = new SupplierInvoiceLine($this->db);
1199 if ($invoiceline->fetch($lineid) <= 0) {
1200 throw new RestException(404, 'Supplier invoice line not found');
1201 }
1202 if ($invoiceline->fk_facture_fourn != $this->invoice->id) {
1203 throw new RestException(403, 'Line does not belong to this supplier invoice');
1204 }
1205
1206 $updateRes = $this->invoice->deleteLine($lineid);
1207 if ($updateRes > 0) {
1208 return array(
1209 'success' => array(
1210 'code' => 200,
1211 'message' => 'line '.$lineid.' deleted'
1212 )
1213 );
1214 } else {
1215 throw new RestException(405, $this->invoice->errorsToString());
1216 }
1217 }
1218
1238 public function useDiscount($id, $discountid)
1239 {
1240 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1241
1242 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'facture', 'creer')) {
1243 throw new RestException(403);
1244 }
1245
1246 $result = $this->invoice->fetch($id);
1247 if ($result <= 0) {
1248 throw new RestException(404, 'Supplier invoice not found');
1249 }
1250
1251 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
1252 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1253 }
1254
1255 // Same conditions as the discount selector of the supplier invoice card
1256 if ($this->invoice->status != FactureFournisseur::STATUS_DRAFT) {
1257 throw new RestException(400, 'Supplier invoice must be a draft');
1258 }
1259 if ($this->invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE || $this->invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
1260 throw new RestException(400, 'A discount cannot be used on a supplier credit note or deposit');
1261 }
1262
1263 $discount = new DiscountAbsolute($this->db);
1264 $result = $discount->fetch($discountid);
1265 if ($result <= 0 || empty($discount->discount_type)) {
1266 throw new RestException(404, 'Supplier discount not found');
1267 }
1268 if ($discount->fk_soc != $this->invoice->socid) {
1269 throw new RestException(400, 'Discount does not belong to the supplier of the invoice');
1270 }
1271 if (!empty($discount->fk_invoice_supplier) || !empty($discount->fk_invoice_supplier_line)) {
1272 throw new RestException(409, 'Discount already used');
1273 }
1274 if (price2num($discount->amount_ttc) > price2num($this->invoice->total_ttc)) {
1275 throw new RestException(400, 'Discount is larger than the invoice, split it before');
1276 }
1277
1278 $result = $this->invoice->insert_discount($discount->id);
1279 if ($result < 0) {
1280 throw new RestException(500, $this->invoice->errorsToString());
1281 }
1282
1283 return $result;
1284 }
1285
1286 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1296 protected function _cleanObjectDatas($object)
1297 {
1298 // phpcs:enable
1299 $object = parent::_cleanObjectDatas($object);
1300
1301 unset($object->rowid);
1302 unset($object->barcode_type);
1303 unset($object->barcode_type_code);
1304 unset($object->barcode_type_label);
1305 unset($object->barcode_type_coder);
1306
1307 return $object;
1308 }
1309
1318 private function _validate($data)
1319 {
1320 if ($data === null) {
1321 $data = array();
1322 }
1323 $invoice = array();
1324 foreach (SupplierInvoices::$FIELDS as $field) {
1325 if (!isset($data[$field])) {
1326 throw new RestException(400, "$field field missing");
1327 }
1328 $invoice[$field] = $data[$field];
1329 }
1330 return $invoice;
1331 }
1332}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class to manage absolute discounts.
Class for API REST v1.
Definition api.class.php:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
Class to manage suppliers invoices.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
const STATUS_VALIDATED
Validated (need to be paid)
const TYPE_STANDARD
Standard invoice.
Class to manage payments for supplier invoices.
Class to manage line invoices.
settodraft($id, $idwarehouse=-1, $notrigger=0)
Sets an invoice as draft.
validate($id, $idwarehouse=0, $notrigger=0)
Validate an invoice.
settopaid($id, $close_code='', $close_note='')
Sets a supplier invoice as paid.
deleteLine($id, $lineid)
Deletes a line of a given supplier invoice.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false)
List invoices.
markAsCreditAvailable($id)
Create a discount (credit available) from a supplier credit note, a supplier deposit or the excess pa...
getLines($id)
Get lines of a supplier invoice.
getPayments($id)
Get list of payments of a given supplier invoice.
useDiscount($id, $discountid)
Add a discount line into a draft supplier invoice using an available supplier discount.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
settounpaid($id)
Sets a supplier invoice as unpaid.
useCreditNote($id, $discountid)
Use an available supplier credit (coming from a credit note, a deposit or an excess paid) to pay a su...
addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='', $amount=null)
Add payment line to a specific supplier invoice with the remain to pay as amount.
post($request_data=null)
Create supplier invoice object.
postLine($id, $request_data=null)
Add a line to given supplier invoice.
put($id, $request_data=null)
Update supplier invoice.
_validate($data)
Validate fields before create or update object.
putLine($id, $lineid, $request_data=null)
Update a line to a given supplier invoice.
dol_now($mode='gmt')
Return date for now.
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, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.