dolibarr 20.0.5
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
271 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
272 }
273
274 if ($this->invoice->update(DolibarrApiAccess::$user)) {
275 return $this->get($id);
276 }
277
278 return false;
279 }
280
292 public function delete($id)
293 {
294 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "supprimer")) {
295 throw new RestException(403);
296 }
297 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
298 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
299 }
300 $result = $this->invoice->fetch($id);
301 if (!$result) {
302 throw new RestException(404, 'Supplier invoice not found');
303 }
304
305 if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) {
306 throw new RestException(500, 'Error when deleting invoice');
307 }
308
309 return array(
310 'success' => array(
311 'code' => 200,
312 'message' => 'Supplier invoice deleted'
313 )
314 );
315 }
316
334 public function validate($id, $idwarehouse = 0, $notrigger = 0)
335 {
336 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
337 throw new RestException(403);
338 }
339
340 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
341 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
342 }
343
344 $result = $this->invoice->fetch($id);
345 if (!$result) {
346 throw new RestException(404, 'Invoice not found');
347 }
348
349 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
350 if ($result == 0) {
351 throw new RestException(304, 'Error nothing done. The invoice is already validated');
352 }
353 if ($result < 0) {
354 throw new RestException(500, 'Error when validating Invoice: ' . $this->invoice->error);
355 }
356
357 return array(
358 'success' => array(
359 'code' => 200,
360 'message' => 'Invoice validated (Ref=' . $this->invoice->ref . ')'
361 )
362 );
363 }
364
378 public function getPayments($id)
379 {
380 if (empty($id)) {
381 throw new RestException(400, 'Invoice ID is mandatory');
382 }
383
384 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
385 throw new RestException(403);
386 }
387 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
388 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
389 }
390
391 $result = $this->invoice->fetch($id);
392 if (!$result) {
393 throw new RestException(404, 'Invoice not found');
394 }
395
396 $result = $this->invoice->getListOfPayments();
397 if ($this->invoice->error !== '') {
398 throw new RestException(405, $this->invoice->error);
399 }
400
401 return $result;
402 }
403
404
427 public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $amount = null)
428 {
429 if (empty($id)) {
430 throw new RestException(400, 'Invoice ID is mandatory');
431 }
432
433 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
434 throw new RestException(403);
435 }
436 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
437 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
438 }
439
440 $result = $this->invoice->fetch($id);
441 if (!$result) {
442 throw new RestException(404, 'Invoice not found');
443 }
444
445 if (isModEnabled("bank")) {
446 if (empty($accountid)) {
447 throw new RestException(400, 'Bank account ID is mandatory');
448 }
449 }
450
451 if (empty($payment_mode_id)) {
452 throw new RestException(400, 'Payment mode ID is mandatory');
453 }
454
455 if (null !== $amount && $amount > 0) {
456 // We use the amount given in parameter
457 $paymentamount = $amount;
458 } else {
459 // We calculate the remain to pay, and use it as amount
460 $totalpaid = $this->invoice->getSommePaiement();
461 $totaldeposits = $this->invoice->getSumDepositsUsed();
462 $paymentamount = price2num($this->invoice->total_ttc - $totalpaid - $totaldeposits, 'MT');
463 }
464
465 $this->db->begin();
466
467 $amounts = array();
468 $multicurrency_amounts = array();
469
470 $paymentamount = (float) price2num($paymentamount, 'MT');
471
472 $amounts[$id] = $paymentamount;
473
474 // Multicurrency
475 $newvalue = (float) price2num($this->invoice->multicurrency_total_ttc, 'MT');
476 $multicurrency_amounts[$id] = $newvalue;
477
478 // Creation of payment line
479 $paiement = new PaiementFourn($this->db);
480 $paiement->datepaye = $datepaye;
481 $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
482 $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
483 $paiement->paiementid = $payment_mode_id;
484 $paiement->paiementcode = (string) dol_getIdFromCode($this->db, $payment_mode_id, 'c_paiement', 'id', 'code', 1);
485 $paiement->num_payment = $num_payment;
486 $paiement->note_public = $comment;
487
488 $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
489 if ($paiement_id < 0) {
490 $this->db->rollback();
491 throw new RestException(400, 'Payment error : ' . $paiement->error);
492 }
493
494 if (isModEnabled("bank")) {
495 $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank);
496 if ($result < 0) {
497 $this->db->rollback();
498 throw new RestException(400, 'Add payment to bank error : ' . $paiement->error);
499 }
500 }
501
502 $this->db->commit();
503
504 return $paiement_id;
505 }
506
519 public function getLines($id)
520 {
521 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
522 throw new RestException(403);
523 }
524 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
525 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
526 }
527
528 $result = $this->invoice->fetch($id);
529 if (!$result) {
530 throw new RestException(404, 'Supplier invoice not found');
531 }
532
533 $this->invoice->fetch_lines();
534 $result = array();
535 foreach ($this->invoice->lines as $line) {
536 array_push($result, $this->_cleanObjectDatas($line));
537 }
538 return $result;
539 }
540
558 public function postLine($id, $request_data = null)
559 {
560 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
561 throw new RestException(403);
562 }
563
564 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
565 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
566 }
567
568 $result = $this->invoice->fetch($id);
569 if (!$result) {
570 throw new RestException(404, 'Supplier invoice not found');
571 }
572
573 $request_data = (object) $request_data;
574
575 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
576 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
577
578 $updateRes = $this->invoice->addline(
579 $request_data->description,
580 $request_data->pu_ht,
581 $request_data->tva_tx,
582 $request_data->localtax1_tx,
583 $request_data->localtax2_tx,
584 $request_data->qty,
585 $request_data->fk_product,
586 $request_data->remise_percent,
587 $request_data->date_start,
588 $request_data->date_end,
589 $request_data->fk_code_ventilation,
590 $request_data->info_bits,
591 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
592 $request_data->product_type,
593 $request_data->rang,
594 false,
595 $request_data->array_options,
596 $request_data->fk_unit,
597 $request_data->origin_id,
598 $request_data->multicurrency_subprice,
599 $request_data->ref_supplier,
600 $request_data->special_code
601 );
602
603 if ($updateRes < 0) {
604 throw new RestException(400, 'Unable to insert the new line. Check your inputs. ' . $this->invoice->error);
605 }
606
607 return $updateRes;
608 }
609
625 public function putLine($id, $lineid, $request_data = null)
626 {
627 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
628 throw new RestException(403);
629 }
630
631 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
632 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
633 }
634
635 $result = $this->invoice->fetch($id);
636 if (!$result) {
637 throw new RestException(404, 'Supplier invoice not found');
638 }
639
640 $request_data = (object) $request_data;
641
642 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
643 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
644
645 $updateRes = $this->invoice->updateline(
646 $lineid,
647 $request_data->description,
648 $request_data->pu_ht,
649 $request_data->tva_tx,
650 $request_data->localtax1_tx,
651 $request_data->localtax2_tx,
652 $request_data->qty,
653 $request_data->fk_product,
654 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
655 $request_data->info_bits,
656 $request_data->product_type,
657 $request_data->remise_percent,
658 false,
659 $request_data->date_start,
660 $request_data->date_end,
661 $request_data->array_options,
662 $request_data->fk_unit,
663 $request_data->multicurrency_subprice,
664 $request_data->ref_supplier,
665 $request_data->rang
666 );
667
668 if ($updateRes > 0) {
669 $result = $this->get($id);
670 unset($result->line);
671 return $this->_cleanObjectDatas($result);
672 } else {
673 throw new RestException(304, $this->invoice->error);
674 }
675 }
676
692 public function deleteLine($id, $lineid)
693 {
694 if (empty($lineid)) {
695 throw new RestException(400, 'Line ID is mandatory');
696 }
697
698 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
699 throw new RestException(403);
700 }
701 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
702 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
703 }
704
705 $result = $this->invoice->fetch($id);
706 if (!$result) {
707 throw new RestException(404, 'Supplier invoice not found');
708 }
709
710 // TODO Check the lineid $lineid is a line of object
711
712 $updateRes = $this->invoice->deleteLine($lineid);
713 if ($updateRes > 0) {
714 return array(
715 'success' => array(
716 'code' => 200,
717 'message' => 'line '.$lineid.' deleted'
718 )
719 );
720 } else {
721 throw new RestException(405, $this->invoice->error);
722 }
723 }
724
725 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
732 protected function _cleanObjectDatas($object)
733 {
734 // phpcs:enable
735 $object = parent::_cleanObjectDatas($object);
736
737 unset($object->rowid);
738 unset($object->barcode_type);
739 unset($object->barcode_type_code);
740 unset($object->barcode_type_label);
741 unset($object->barcode_type_coder);
742
743 return $object;
744 }
745
754 private function _validate($data)
755 {
756 $invoice = array();
757 foreach (SupplierInvoices::$FIELDS as $field) {
758 if (!isset($data[$field])) {
759 throw new RestException(400, "$field field missing");
760 }
761 $invoice[$field] = $data[$field];
762 }
763 return $invoice;
764 }
765}
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.
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.