dolibarr 21.0.3
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 Joachim Kueter <git-jk@bloxera.com>
5 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
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 . '/fourn/class/fournisseur.facture.class.php';
25require_once DOL_DOCUMENT_ROOT . '/fourn/class/paiementfourn.class.php';
26
35{
40 public static $FIELDS = array(
41 'socid',
42 );
43
47 public $invoice;
48
52 public function __construct()
53 {
54 global $db;
55 $this->db = $db;
56 $this->invoice = new FactureFournisseur($this->db);
57 }
58
70 public function get($id)
71 {
72 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
73 throw new RestException(403);
74 }
75
76 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
77 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
78 }
79
80 $result = $this->invoice->fetch($id);
81 if (!$result) {
82 throw new RestException(404, 'Supplier invoice not found');
83 }
84
85 $this->invoice->fetchObjectLinked();
86 return $this->_cleanObjectDatas($this->invoice);
87 }
88
107 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false)
108 {
109 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
110 throw new RestException(403);
111 }
112
113 $obj_ret = array();
114
115 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
116 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
117
118 // If the internal user must only see his customers, force searching by him
119 $search_sale = 0;
120 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir")) {
121 $search_sale = DolibarrApiAccess::$user->id;
122 }
123
124 $sql = "SELECT t.rowid";
125 $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn AS t";
126 $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
127 $sql .= ' WHERE t.entity IN (' . getEntity('supplier_invoice') . ')';
128 if ($socids) {
129 $sql .= " AND t.fk_soc IN (" . $this->db->sanitize($socids) . ")";
130 }
131 // Filter by status
132 if ($status == 'draft') {
133 $sql .= " AND t.fk_statut IN (0)";
134 }
135 if ($status == 'unpaid') {
136 $sql .= " AND t.fk_statut IN (1)";
137 }
138 if ($status == 'paid') {
139 $sql .= " AND t.fk_statut IN (2)";
140 }
141 if ($status == 'cancelled') {
142 $sql .= " AND t.fk_statut IN (3)";
143 }
144 // Search on sale representative
145 if ($search_sale && $search_sale != '-1') {
146 if ($search_sale == -2) {
147 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
148 } elseif ($search_sale > 0) {
149 $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).")";
150 }
151 }
152 // Add sql filters
153 if ($sqlfilters) {
154 $errormessage = '';
155 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
156 if ($errormessage) {
157 throw new RestException(400, 'Error when validating parameter sqlfilters -> ' . $errormessage);
158 }
159 }
160
161 //this query will return total supplier invoices with the filters given
162 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
163
164 $sql .= $this->db->order($sortfield, $sortorder);
165 if ($limit) {
166 if ($page < 0) {
167 $page = 0;
168 }
169 $offset = $limit * $page;
170
171 $sql .= $this->db->plimit($limit + 1, $offset);
172 }
173
174 $result = $this->db->query($sql);
175 if ($result) {
176 $i = 0;
177 $num = $this->db->num_rows($result);
178 $min = min($num, ($limit <= 0 ? $num : $limit));
179 while ($i < $min) {
180 $obj = $this->db->fetch_object($result);
181 $invoice_static = new FactureFournisseur($this->db);
182 if ($invoice_static->fetch($obj->rowid)) {
183 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
184 }
185 $i++;
186 }
187 } else {
188 throw new RestException(503, 'Error when retrieve supplier invoice list : ' . $this->db->lasterror());
189 }
190
191 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
192 if ($pagination_data) {
193 $totalsResult = $this->db->query($sqlTotals);
194 $total = $this->db->fetch_object($totalsResult)->total;
195
196 $tmp = $obj_ret;
197 $obj_ret = [];
198
199 $obj_ret['data'] = $tmp;
200 $obj_ret['pagination'] = [
201 'total' => (int) $total,
202 'page' => $page, //count starts from 0
203 'page_count' => ceil((int) $total / $limit),
204 'limit' => $limit
205 ];
206 }
207
208 return $obj_ret;
209 }
210
225 public function post($request_data = null)
226 {
227 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
228 throw new RestException(403, "Insuffisant rights");
229 }
230 // Check mandatory fields
231 $result = $this->_validate($request_data);
232
233 foreach ($request_data as $field => $value) {
234 if ($field === 'caller') {
235 // 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
236 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
237 continue;
238 }
239
240 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
241 }
242 if (!array_key_exists('date', $request_data)) {
243 $this->invoice->date = dol_now();
244 }
245
246 if ($this->invoice->create(DolibarrApiAccess::$user) < 0) {
247 throw new RestException(500, "Error creating invoice ", array_merge(array($this->invoice->error), $this->invoice->errors));
248 }
249 return $this->invoice->id;
250 }
251
262 public function put($id, $request_data = null)
263 {
264 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
265 throw new RestException(403);
266 }
267
268 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
269 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
270 }
271
272 $result = $this->invoice->fetch($id);
273 if (!$result) {
274 throw new RestException(404, 'Supplier invoice not found');
275 }
276
277 foreach ($request_data as $field => $value) {
278 if ($field == 'id') {
279 continue;
280 }
281 if ($field === 'caller') {
282 // 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
283 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
284 continue;
285 }
286 if ($field == 'array_options' && is_array($value)) {
287 foreach ($value as $index => $val) {
288 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
289 }
290 continue;
291 }
292
293 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
294 }
295
296 if ($this->invoice->update(DolibarrApiAccess::$user)) {
297 return $this->get($id);
298 }
299
300 return false;
301 }
302
314 public function delete($id)
315 {
316 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "supprimer")) {
317 throw new RestException(403);
318 }
319 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
320 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
321 }
322 $result = $this->invoice->fetch($id);
323 if (!$result) {
324 throw new RestException(404, 'Supplier invoice not found');
325 }
326
327 if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) {
328 throw new RestException(500, 'Error when deleting invoice');
329 }
330
331 return array(
332 'success' => array(
333 'code' => 200,
334 'message' => 'Supplier invoice deleted'
335 )
336 );
337 }
338
356 public function validate($id, $idwarehouse = 0, $notrigger = 0)
357 {
358 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
359 throw new RestException(403);
360 }
361
362 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
363 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
364 }
365
366 $result = $this->invoice->fetch($id);
367 if (!$result) {
368 throw new RestException(404, 'Invoice not found');
369 }
370
371 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
372 if ($result == 0) {
373 throw new RestException(304, 'Error nothing done. The invoice is already validated');
374 }
375 if ($result < 0) {
376 throw new RestException(500, 'Error when validating Invoice: ' . $this->invoice->error);
377 }
378
379 return array(
380 'success' => array(
381 'code' => 200,
382 'message' => 'Invoice validated (Ref=' . $this->invoice->ref . ')'
383 )
384 );
385 }
386
400 public function getPayments($id)
401 {
402 if (empty($id)) {
403 throw new RestException(400, 'Invoice ID is mandatory');
404 }
405
406 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
407 throw new RestException(403);
408 }
409 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
410 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
411 }
412
413 $result = $this->invoice->fetch($id);
414 if (!$result) {
415 throw new RestException(404, 'Invoice not found');
416 }
417
418 $result = $this->invoice->getListOfPayments();
419 if ($this->invoice->error !== '') {
420 throw new RestException(405, $this->invoice->error);
421 }
422
423 return $result;
424 }
425
426
449 public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $amount = null)
450 {
451 if (empty($id)) {
452 throw new RestException(400, 'Invoice ID is mandatory');
453 }
454
455 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
456 throw new RestException(403);
457 }
458 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
459 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
460 }
461
462 $result = $this->invoice->fetch($id);
463 if (!$result) {
464 throw new RestException(404, 'Invoice not found');
465 }
466
467 if (isModEnabled("bank")) {
468 if (empty($accountid)) {
469 throw new RestException(400, 'Bank account ID is mandatory');
470 }
471 }
472
473 if (empty($payment_mode_id)) {
474 throw new RestException(400, 'Payment mode ID is mandatory');
475 }
476
477 if (null !== $amount && $amount > 0) {
478 // We use the amount given in parameter
479 $paymentamount = $amount;
480 } else {
481 // We calculate the remain to pay, and use it as amount
482 $totalpaid = $this->invoice->getSommePaiement();
483 $totaldeposits = $this->invoice->getSumDepositsUsed();
484 $paymentamount = price2num($this->invoice->total_ttc - $totalpaid - $totaldeposits, 'MT');
485 }
486
487 $this->db->begin();
488
489 $amounts = array();
490 $multicurrency_amounts = array();
491
492 $paymentamount = (float) price2num($paymentamount, 'MT');
493
494 $amounts[$id] = $paymentamount;
495
496 // Multicurrency
497 $newvalue = (float) price2num($this->invoice->multicurrency_total_ttc, 'MT');
498 $multicurrency_amounts[$id] = $newvalue;
499
500 // Creation of payment line
501 $paiement = new PaiementFourn($this->db);
502 $paiement->datepaye = $datepaye;
503 $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
504 $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
505 $paiement->paiementid = $payment_mode_id;
506 $paiement->paiementcode = (string) dol_getIdFromCode($this->db, (string) $payment_mode_id, 'c_paiement', 'id', 'code', 1);
507 $paiement->num_payment = $num_payment;
508 $paiement->note_public = $comment;
509
510 $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
511 if ($paiement_id < 0) {
512 $this->db->rollback();
513 throw new RestException(400, 'Payment error : ' . $paiement->error);
514 }
515
516 if (isModEnabled("bank")) {
517 $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank);
518 if ($result < 0) {
519 $this->db->rollback();
520 throw new RestException(400, 'Add payment to bank error : ' . $paiement->error);
521 }
522 }
523
524 $this->db->commit();
525
526 return $paiement_id;
527 }
528
541 public function getLines($id)
542 {
543 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
544 throw new RestException(403);
545 }
546 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
547 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
548 }
549
550 $result = $this->invoice->fetch($id);
551 if (!$result) {
552 throw new RestException(404, 'Supplier invoice not found');
553 }
554
555 $this->invoice->fetch_lines();
556 $result = array();
557 foreach ($this->invoice->lines as $line) {
558 array_push($result, $this->_cleanObjectDatas($line));
559 }
560 return $result;
561 }
562
580 public function postLine($id, $request_data = null)
581 {
582 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
583 throw new RestException(403);
584 }
585
586 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
587 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
588 }
589
590 $result = $this->invoice->fetch($id);
591 if (!$result) {
592 throw new RestException(404, 'Supplier invoice not found');
593 }
594
595 $request_data = (object) $request_data;
596
597 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
598 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
599
600 $updateRes = $this->invoice->addline(
601 $request_data->description,
602 $request_data->pu_ht,
603 $request_data->tva_tx,
604 $request_data->localtax1_tx,
605 $request_data->localtax2_tx,
606 $request_data->qty,
607 $request_data->fk_product,
608 $request_data->remise_percent,
609 $request_data->date_start,
610 $request_data->date_end,
611 $request_data->fk_code_ventilation,
612 $request_data->info_bits,
613 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
614 $request_data->product_type,
615 $request_data->rang,
616 false,
617 $request_data->array_options,
618 $request_data->fk_unit,
619 $request_data->origin_id,
620 $request_data->multicurrency_subprice,
621 $request_data->ref_supplier,
622 $request_data->special_code
623 );
624
625 if ($updateRes < 0) {
626 throw new RestException(400, 'Unable to insert the new line. Check your inputs. ' . $this->invoice->error);
627 }
628
629 return $updateRes;
630 }
631
647 public function putLine($id, $lineid, $request_data = null)
648 {
649 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
650 throw new RestException(403);
651 }
652
653 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
654 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
655 }
656
657 $result = $this->invoice->fetch($id);
658 if (!$result) {
659 throw new RestException(404, 'Supplier invoice not found');
660 }
661
662 $request_data = (object) $request_data;
663
664 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
665 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
666
667 $updateRes = $this->invoice->updateline(
668 $lineid,
669 $request_data->description,
670 $request_data->pu_ht,
671 $request_data->tva_tx,
672 $request_data->localtax1_tx,
673 $request_data->localtax2_tx,
674 $request_data->qty,
675 $request_data->fk_product,
676 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
677 $request_data->info_bits,
678 $request_data->product_type,
679 $request_data->remise_percent,
680 false,
681 $request_data->date_start,
682 $request_data->date_end,
683 $request_data->array_options,
684 $request_data->fk_unit,
685 $request_data->multicurrency_subprice,
686 $request_data->ref_supplier,
687 $request_data->rang
688 );
689
690 if ($updateRes > 0) {
691 $result = $this->get($id);
692 unset($result->line);
693 return $this->_cleanObjectDatas($result);
694 } else {
695 throw new RestException(304, $this->invoice->error);
696 }
697 }
698
714 public function deleteLine($id, $lineid)
715 {
716 if (empty($lineid)) {
717 throw new RestException(400, 'Line ID is mandatory');
718 }
719
720 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
721 throw new RestException(403);
722 }
723 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
724 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
725 }
726
727 $result = $this->invoice->fetch($id);
728 if (!$result) {
729 throw new RestException(404, 'Supplier invoice not found');
730 }
731
732 // TODO Check the lineid $lineid is a line of object
733
734 $updateRes = $this->invoice->deleteLine($lineid);
735 if ($updateRes > 0) {
736 return array(
737 'success' => array(
738 'code' => 200,
739 'message' => 'line '.$lineid.' deleted'
740 )
741 );
742 } else {
743 throw new RestException(405, $this->invoice->error);
744 }
745 }
746
747 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
754 protected function _cleanObjectDatas($object)
755 {
756 // phpcs:enable
757 $object = parent::_cleanObjectDatas($object);
758
759 unset($object->rowid);
760 unset($object->barcode_type);
761 unset($object->barcode_type_code);
762 unset($object->barcode_type_label);
763 unset($object->barcode_type_coder);
764
765 return $object;
766 }
767
776 private function _validate($data)
777 {
778 $invoice = array();
779 foreach (SupplierInvoices::$FIELDS as $field) {
780 if (!isset($data[$field])) {
781 throw new RestException(400, "$field field missing");
782 }
783 $invoice[$field] = $data[$field];
784 }
785 return $invoice;
786 }
787}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
Class for API REST v1.
Definition api.class.php:31
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:83
Class to manage suppliers invoices.
Class to manage payments for supplier invoices.
validate($id, $idwarehouse=0, $notrigger=0)
Validate an invoice.
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.
getLines($id)
Get lines of a supplier invoice.
getPayments($id)
Get list of payments of a given supplier invoice.
_cleanObjectDatas($object)
Clean sensible object datas.
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_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.