dolibarr 21.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 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 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
293 }
294
295 if ($this->invoice->update(DolibarrApiAccess::$user)) {
296 return $this->get($id);
297 }
298
299 return false;
300 }
301
313 public function delete($id)
314 {
315 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "supprimer")) {
316 throw new RestException(403);
317 }
318 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
319 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
320 }
321 $result = $this->invoice->fetch($id);
322 if (!$result) {
323 throw new RestException(404, 'Supplier invoice not found');
324 }
325
326 if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) {
327 throw new RestException(500, 'Error when deleting invoice');
328 }
329
330 return array(
331 'success' => array(
332 'code' => 200,
333 'message' => 'Supplier invoice deleted'
334 )
335 );
336 }
337
355 public function validate($id, $idwarehouse = 0, $notrigger = 0)
356 {
357 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
358 throw new RestException(403);
359 }
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
365 $result = $this->invoice->fetch($id);
366 if (!$result) {
367 throw new RestException(404, 'Invoice not found');
368 }
369
370 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
371 if ($result == 0) {
372 throw new RestException(304, 'Error nothing done. The invoice is already validated');
373 }
374 if ($result < 0) {
375 throw new RestException(500, 'Error when validating Invoice: ' . $this->invoice->error);
376 }
377
378 return array(
379 'success' => array(
380 'code' => 200,
381 'message' => 'Invoice validated (Ref=' . $this->invoice->ref . ')'
382 )
383 );
384 }
385
399 public function getPayments($id)
400 {
401 if (empty($id)) {
402 throw new RestException(400, 'Invoice ID is mandatory');
403 }
404
405 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
406 throw new RestException(403);
407 }
408 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
409 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
410 }
411
412 $result = $this->invoice->fetch($id);
413 if (!$result) {
414 throw new RestException(404, 'Invoice not found');
415 }
416
417 $result = $this->invoice->getListOfPayments();
418 if ($this->invoice->error !== '') {
419 throw new RestException(405, $this->invoice->error);
420 }
421
422 return $result;
423 }
424
425
448 public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $amount = null)
449 {
450 if (empty($id)) {
451 throw new RestException(400, 'Invoice ID is mandatory');
452 }
453
454 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
455 throw new RestException(403);
456 }
457 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
458 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
459 }
460
461 $result = $this->invoice->fetch($id);
462 if (!$result) {
463 throw new RestException(404, 'Invoice not found');
464 }
465
466 if (isModEnabled("bank")) {
467 if (empty($accountid)) {
468 throw new RestException(400, 'Bank account ID is mandatory');
469 }
470 }
471
472 if (empty($payment_mode_id)) {
473 throw new RestException(400, 'Payment mode ID is mandatory');
474 }
475
476 if (null !== $amount && $amount > 0) {
477 // We use the amount given in parameter
478 $paymentamount = $amount;
479 } else {
480 // We calculate the remain to pay, and use it as amount
481 $totalpaid = $this->invoice->getSommePaiement();
482 $totaldeposits = $this->invoice->getSumDepositsUsed();
483 $paymentamount = price2num($this->invoice->total_ttc - $totalpaid - $totaldeposits, 'MT');
484 }
485
486 $this->db->begin();
487
488 $amounts = array();
489 $multicurrency_amounts = array();
490
491 $paymentamount = (float) price2num($paymentamount, 'MT');
492
493 $amounts[$id] = $paymentamount;
494
495 // Multicurrency
496 $newvalue = (float) price2num($this->invoice->multicurrency_total_ttc, 'MT');
497 $multicurrency_amounts[$id] = $newvalue;
498
499 // Creation of payment line
500 $paiement = new PaiementFourn($this->db);
501 $paiement->datepaye = $datepaye;
502 $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
503 $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
504 $paiement->paiementid = $payment_mode_id;
505 $paiement->paiementcode = (string) dol_getIdFromCode($this->db, (string) $payment_mode_id, 'c_paiement', 'id', 'code', 1);
506 $paiement->num_payment = $num_payment;
507 $paiement->note_public = $comment;
508
509 $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
510 if ($paiement_id < 0) {
511 $this->db->rollback();
512 throw new RestException(400, 'Payment error : ' . $paiement->error);
513 }
514
515 if (isModEnabled("bank")) {
516 $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank);
517 if ($result < 0) {
518 $this->db->rollback();
519 throw new RestException(400, 'Add payment to bank error : ' . $paiement->error);
520 }
521 }
522
523 $this->db->commit();
524
525 return $paiement_id;
526 }
527
540 public function getLines($id)
541 {
542 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
543 throw new RestException(403);
544 }
545 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
546 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
547 }
548
549 $result = $this->invoice->fetch($id);
550 if (!$result) {
551 throw new RestException(404, 'Supplier invoice not found');
552 }
553
554 $this->invoice->fetch_lines();
555 $result = array();
556 foreach ($this->invoice->lines as $line) {
557 array_push($result, $this->_cleanObjectDatas($line));
558 }
559 return $result;
560 }
561
579 public function postLine($id, $request_data = null)
580 {
581 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
582 throw new RestException(403);
583 }
584
585 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
586 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
587 }
588
589 $result = $this->invoice->fetch($id);
590 if (!$result) {
591 throw new RestException(404, 'Supplier invoice not found');
592 }
593
594 $request_data = (object) $request_data;
595
596 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
597 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
598
599 $updateRes = $this->invoice->addline(
600 $request_data->description,
601 $request_data->pu_ht,
602 $request_data->tva_tx,
603 $request_data->localtax1_tx,
604 $request_data->localtax2_tx,
605 $request_data->qty,
606 $request_data->fk_product,
607 $request_data->remise_percent,
608 $request_data->date_start,
609 $request_data->date_end,
610 $request_data->fk_code_ventilation,
611 $request_data->info_bits,
612 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
613 $request_data->product_type,
614 $request_data->rang,
615 false,
616 $request_data->array_options,
617 $request_data->fk_unit,
618 $request_data->origin_id,
619 $request_data->multicurrency_subprice,
620 $request_data->ref_supplier,
621 $request_data->special_code
622 );
623
624 if ($updateRes < 0) {
625 throw new RestException(400, 'Unable to insert the new line. Check your inputs. ' . $this->invoice->error);
626 }
627
628 return $updateRes;
629 }
630
646 public function putLine($id, $lineid, $request_data = null)
647 {
648 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
649 throw new RestException(403);
650 }
651
652 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
653 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
654 }
655
656 $result = $this->invoice->fetch($id);
657 if (!$result) {
658 throw new RestException(404, 'Supplier invoice not found');
659 }
660
661 $request_data = (object) $request_data;
662
663 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
664 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
665
666 $updateRes = $this->invoice->updateline(
667 $lineid,
668 $request_data->description,
669 $request_data->pu_ht,
670 $request_data->tva_tx,
671 $request_data->localtax1_tx,
672 $request_data->localtax2_tx,
673 $request_data->qty,
674 $request_data->fk_product,
675 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
676 $request_data->info_bits,
677 $request_data->product_type,
678 $request_data->remise_percent,
679 false,
680 $request_data->date_start,
681 $request_data->date_end,
682 $request_data->array_options,
683 $request_data->fk_unit,
684 $request_data->multicurrency_subprice,
685 $request_data->ref_supplier,
686 $request_data->rang
687 );
688
689 if ($updateRes > 0) {
690 $result = $this->get($id);
691 unset($result->line);
692 return $this->_cleanObjectDatas($result);
693 } else {
694 throw new RestException(304, $this->invoice->error);
695 }
696 }
697
713 public function deleteLine($id, $lineid)
714 {
715 if (empty($lineid)) {
716 throw new RestException(400, 'Line ID is mandatory');
717 }
718
719 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
720 throw new RestException(403);
721 }
722 if (!DolibarrApi::_checkAccessToResource('fournisseur', $id, 'facture_fourn', 'facture')) {
723 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
724 }
725
726 $result = $this->invoice->fetch($id);
727 if (!$result) {
728 throw new RestException(404, 'Supplier invoice not found');
729 }
730
731 // TODO Check the lineid $lineid is a line of object
732
733 $updateRes = $this->invoice->deleteLine($lineid);
734 if ($updateRes > 0) {
735 return array(
736 'success' => array(
737 'code' => 200,
738 'message' => 'line '.$lineid.' deleted'
739 )
740 );
741 } else {
742 throw new RestException(405, $this->invoice->error);
743 }
744 }
745
746 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
753 protected function _cleanObjectDatas($object)
754 {
755 // phpcs:enable
756 $object = parent::_cleanObjectDatas($object);
757
758 unset($object->rowid);
759 unset($object->barcode_type);
760 unset($object->barcode_type_code);
761 unset($object->barcode_type_label);
762 unset($object->barcode_type_coder);
763
764 return $object;
765 }
766
775 private function _validate($data)
776 {
777 $invoice = array();
778 foreach (SupplierInvoices::$FIELDS as $field) {
779 if (!isset($data[$field])) {
780 throw new RestException(400, "$field field missing");
781 }
782 $invoice[$field] = $data[$field];
783 }
784 return $invoice;
785 }
786}
$id
Definition account.php:39
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.
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.
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.