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