dolibarr 20.0.0
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 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use Luracast\Restler\RestException;
22
23require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
24require_once DOL_DOCUMENT_ROOT . '/fourn/class/paiementfourn.class.php';
25
34{
39 public static $FIELDS = array(
40 'socid',
41 );
42
46 public $invoice;
47
51 public function __construct()
52 {
53 global $db;
54 $this->db = $db;
55 $this->invoice = new FactureFournisseur($this->db);
56 }
57
69 public function get($id)
70 {
71 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
72 throw new RestException(403);
73 }
74
75 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
76 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
77 }
78
79 $result = $this->invoice->fetch($id);
80 if (!$result) {
81 throw new RestException(404, 'Supplier invoice not found');
82 }
83
84 $this->invoice->fetchObjectLinked();
85 return $this->_cleanObjectDatas($this->invoice);
86 }
87
105 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '')
106 {
107 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
108 throw new RestException(403);
109 }
110
111 $obj_ret = array();
112
113 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
114 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
115
116 // If the internal user must only see his customers, force searching by him
117 $search_sale = 0;
118 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir")) {
119 $search_sale = DolibarrApiAccess::$user->id;
120 }
121
122 $sql = "SELECT t.rowid";
123 $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn AS t";
124 $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
125 $sql .= ' WHERE t.entity IN (' . getEntity('supplier_invoice') . ')';
126 if ($socids) {
127 $sql .= " AND t.fk_soc IN (" . $this->db->sanitize($socids) . ")";
128 }
129 // Filter by status
130 if ($status == 'draft') {
131 $sql .= " AND t.fk_statut IN (0)";
132 }
133 if ($status == 'unpaid') {
134 $sql .= " AND t.fk_statut IN (1)";
135 }
136 if ($status == 'paid') {
137 $sql .= " AND t.fk_statut IN (2)";
138 }
139 if ($status == 'cancelled') {
140 $sql .= " AND t.fk_statut IN (3)";
141 }
142 // Search on sale representative
143 if ($search_sale && $search_sale != '-1') {
144 if ($search_sale == -2) {
145 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
146 } elseif ($search_sale > 0) {
147 $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).")";
148 }
149 }
150 // Add sql filters
151 if ($sqlfilters) {
152 $errormessage = '';
153 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
154 if ($errormessage) {
155 throw new RestException(400, 'Error when validating parameter sqlfilters -> ' . $errormessage);
156 }
157 }
158
159 $sql .= $this->db->order($sortfield, $sortorder);
160 if ($limit) {
161 if ($page < 0) {
162 $page = 0;
163 }
164 $offset = $limit * $page;
165
166 $sql .= $this->db->plimit($limit + 1, $offset);
167 }
168
169 $result = $this->db->query($sql);
170 if ($result) {
171 $i = 0;
172 $num = $this->db->num_rows($result);
173 $min = min($num, ($limit <= 0 ? $num : $limit));
174 while ($i < $min) {
175 $obj = $this->db->fetch_object($result);
176 $invoice_static = new FactureFournisseur($this->db);
177 if ($invoice_static->fetch($obj->rowid)) {
178 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
179 }
180 $i++;
181 }
182 } else {
183 throw new RestException(503, 'Error when retrieve supplier invoice list : ' . $this->db->lasterror());
184 }
185
186 return $obj_ret;
187 }
188
203 public function post($request_data = null)
204 {
205 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
206 throw new RestException(403, "Insuffisant rights");
207 }
208 // Check mandatory fields
209 $result = $this->_validate($request_data);
210
211 foreach ($request_data as $field => $value) {
212 if ($field === 'caller') {
213 // 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
214 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
215 continue;
216 }
217
218 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
219 }
220 if (!array_key_exists('date', $request_data)) {
221 $this->invoice->date = dol_now();
222 }
223
224 if ($this->invoice->create(DolibarrApiAccess::$user) < 0) {
225 throw new RestException(500, "Error creating invoice ", array_merge(array($this->invoice->error), $this->invoice->errors));
226 }
227 return $this->invoice->id;
228 }
229
240 public function put($id, $request_data = null)
241 {
242 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
243 throw new RestException(403);
244 }
245
246 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
247 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
248 }
249
250 $result = $this->invoice->fetch($id);
251 if (!$result) {
252 throw new RestException(404, 'Supplier invoice not found');
253 }
254
255 foreach ($request_data as $field => $value) {
256 if ($field == 'id') {
257 continue;
258 }
259 if ($field === 'caller') {
260 // 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
261 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
262 continue;
263 }
264 if ($field == 'array_options' && is_array($value)) {
265 foreach ($value as $index => $val) {
266 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
267 }
268 continue;
269 }
270 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
271 }
272
273 if ($this->invoice->update(DolibarrApiAccess::$user)) {
274 return $this->get($id);
275 }
276
277 return false;
278 }
279
291 public function delete($id)
292 {
293 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "supprimer")) {
294 throw new RestException(403);
295 }
296 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
297 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
298 }
299 $result = $this->invoice->fetch($id);
300 if (!$result) {
301 throw new RestException(404, 'Supplier invoice not found');
302 }
303
304 if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) {
305 throw new RestException(500, 'Error when deleting invoice');
306 }
307
308 return array(
309 'success' => array(
310 'code' => 200,
311 'message' => 'Supplier invoice deleted'
312 )
313 );
314 }
315
333 public function validate($id, $idwarehouse = 0, $notrigger = 0)
334 {
335 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
336 throw new RestException(403);
337 }
338
339 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
340 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
341 }
342
343 $result = $this->invoice->fetch($id);
344 if (!$result) {
345 throw new RestException(404, 'Invoice not found');
346 }
347
348 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
349 if ($result == 0) {
350 throw new RestException(304, 'Error nothing done. The invoice is already validated');
351 }
352 if ($result < 0) {
353 throw new RestException(500, 'Error when validating Invoice: ' . $this->invoice->error);
354 }
355
356 return array(
357 'success' => array(
358 'code' => 200,
359 'message' => 'Invoice validated (Ref=' . $this->invoice->ref . ')'
360 )
361 );
362 }
363
377 public function getPayments($id)
378 {
379 if (empty($id)) {
380 throw new RestException(400, 'Invoice ID is mandatory');
381 }
382
383 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
384 throw new RestException(403);
385 }
386 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
387 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
388 }
389
390 $result = $this->invoice->fetch($id);
391 if (!$result) {
392 throw new RestException(404, 'Invoice not found');
393 }
394
395 $result = $this->invoice->getListOfPayments();
396 if ($this->invoice->error !== '') {
397 throw new RestException(405, $this->invoice->error);
398 }
399
400 return $result;
401 }
402
403
426 public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $amount = null)
427 {
428 if (empty($id)) {
429 throw new RestException(400, 'Invoice ID is mandatory');
430 }
431
432 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
433 throw new RestException(403);
434 }
435 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
436 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
437 }
438
439 $result = $this->invoice->fetch($id);
440 if (!$result) {
441 throw new RestException(404, 'Invoice not found');
442 }
443
444 if (isModEnabled("bank")) {
445 if (empty($accountid)) {
446 throw new RestException(400, 'Bank account ID is mandatory');
447 }
448 }
449
450 if (empty($payment_mode_id)) {
451 throw new RestException(400, 'Payment mode ID is mandatory');
452 }
453
454 if (null !== $amount && $amount > 0) {
455 // We use the amount given in parameter
456 $paymentamount = $amount;
457 } else {
458 // We calculate the remain to pay, and use it as amount
459 $totalpaid = $this->invoice->getSommePaiement();
460 $totaldeposits = $this->invoice->getSumDepositsUsed();
461 $paymentamount = price2num($this->invoice->total_ttc - $totalpaid - $totaldeposits, 'MT');
462 }
463
464 $this->db->begin();
465
466 $amounts = array();
467 $multicurrency_amounts = array();
468
469 $paymentamount = (float) price2num($paymentamount, 'MT');
470
471 $amounts[$id] = $paymentamount;
472
473 // Multicurrency
474 $newvalue = (float) price2num($this->invoice->multicurrency_total_ttc, 'MT');
475 $multicurrency_amounts[$id] = $newvalue;
476
477 // Creation of payment line
478 $paiement = new PaiementFourn($this->db);
479 $paiement->datepaye = $datepaye;
480 $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
481 $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
482 $paiement->paiementid = $payment_mode_id;
483 $paiement->paiementcode = (string) dol_getIdFromCode($this->db, $payment_mode_id, 'c_paiement', 'id', 'code', 1);
484 $paiement->num_payment = $num_payment;
485 $paiement->note_public = $comment;
486
487 $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
488 if ($paiement_id < 0) {
489 $this->db->rollback();
490 throw new RestException(400, 'Payment error : ' . $paiement->error);
491 }
492
493 if (isModEnabled("bank")) {
494 $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank);
495 if ($result < 0) {
496 $this->db->rollback();
497 throw new RestException(400, 'Add payment to bank error : ' . $paiement->error);
498 }
499 }
500
501 $this->db->commit();
502
503 return $paiement_id;
504 }
505
518 public function getLines($id)
519 {
520 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
521 throw new RestException(403);
522 }
523 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
524 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
525 }
526
527 $result = $this->invoice->fetch($id);
528 if (!$result) {
529 throw new RestException(404, 'Supplier invoice not found');
530 }
531
532 $this->invoice->fetch_lines();
533 $result = array();
534 foreach ($this->invoice->lines as $line) {
535 array_push($result, $this->_cleanObjectDatas($line));
536 }
537 return $result;
538 }
539
557 public function postLine($id, $request_data = null)
558 {
559 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
560 throw new RestException(403);
561 }
562
563 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
564 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
565 }
566
567 $result = $this->invoice->fetch($id);
568 if (!$result) {
569 throw new RestException(404, 'Supplier invoice not found');
570 }
571
572 $request_data = (object) $request_data;
573
574 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
575 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
576
577 $updateRes = $this->invoice->addline(
578 $request_data->description,
579 $request_data->pu_ht,
580 $request_data->tva_tx,
581 $request_data->localtax1_tx,
582 $request_data->localtax2_tx,
583 $request_data->qty,
584 $request_data->fk_product,
585 $request_data->remise_percent,
586 $request_data->date_start,
587 $request_data->date_end,
588 $request_data->fk_code_ventilation,
589 $request_data->info_bits,
590 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
591 $request_data->product_type,
592 $request_data->rang,
593 false,
594 $request_data->array_options,
595 $request_data->fk_unit,
596 $request_data->origin_id,
597 $request_data->multicurrency_subprice,
598 $request_data->ref_supplier,
599 $request_data->special_code
600 );
601
602 if ($updateRes < 0) {
603 throw new RestException(400, 'Unable to insert the new line. Check your inputs. ' . $this->invoice->error);
604 }
605
606 return $updateRes;
607 }
608
624 public function putLine($id, $lineid, $request_data = null)
625 {
626 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
627 throw new RestException(403);
628 }
629
630 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
631 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
632 }
633
634 $result = $this->invoice->fetch($id);
635 if (!$result) {
636 throw new RestException(404, 'Supplier invoice not found');
637 }
638
639 $request_data = (object) $request_data;
640
641 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
642 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
643
644 $updateRes = $this->invoice->updateline(
645 $lineid,
646 $request_data->description,
647 $request_data->pu_ht,
648 $request_data->tva_tx,
649 $request_data->localtax1_tx,
650 $request_data->localtax2_tx,
651 $request_data->qty,
652 $request_data->fk_product,
653 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
654 $request_data->info_bits,
655 $request_data->product_type,
656 $request_data->remise_percent,
657 false,
658 $request_data->date_start,
659 $request_data->date_end,
660 $request_data->array_options,
661 $request_data->fk_unit,
662 $request_data->multicurrency_subprice,
663 $request_data->ref_supplier,
664 $request_data->rang
665 );
666
667 if ($updateRes > 0) {
668 $result = $this->get($id);
669 unset($result->line);
670 return $this->_cleanObjectDatas($result);
671 } else {
672 throw new RestException(304, $this->invoice->error);
673 }
674 }
675
691 public function deleteLine($id, $lineid)
692 {
693 if (empty($lineid)) {
694 throw new RestException(400, 'Line ID is mandatory');
695 }
696
697 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
698 throw new RestException(403);
699 }
700 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
701 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
702 }
703
704 $result = $this->invoice->fetch($id);
705 if (!$result) {
706 throw new RestException(404, 'Supplier invoice not found');
707 }
708
709 // TODO Check the lineid $lineid is a line of object
710
711 $updateRes = $this->invoice->deleteLine($lineid);
712 if ($updateRes > 0) {
713 return array(
714 'success' => array(
715 'code' => 200,
716 'message' => 'line '.$lineid.' deleted'
717 )
718 );
719 } else {
720 throw new RestException(405, $this->invoice->error);
721 }
722 }
723
724 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
731 protected function _cleanObjectDatas($object)
732 {
733 // phpcs:enable
734 $object = parent::_cleanObjectDatas($object);
735
736 unset($object->rowid);
737 unset($object->barcode_type);
738 unset($object->barcode_type_code);
739 unset($object->barcode_type_label);
740 unset($object->barcode_type_coder);
741
742 return $object;
743 }
744
753 private function _validate($data)
754 {
755 $invoice = array();
756 foreach (SupplierInvoices::$FIELDS as $field) {
757 if (!isset($data[$field])) {
758 throw new RestException(400, "$field field missing");
759 }
760 $invoice[$field] = $data[$field];
761 }
762 return $invoice;
763 }
764}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
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 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.
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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='')
List invoices.
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.
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.