dolibarr 19.0.4
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 if ($field == 'array_options' && is_array($value)) {
278 foreach ($value as $index => $val) {
279 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
280 }
281 continue;
282 }
283
284 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
285 }
286
287 if ($this->invoice->update(DolibarrApiAccess::$user)) {
288 return $this->get($id);
289 }
290
291 return false;
292 }
293
305 public function delete($id)
306 {
307 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "supprimer")) {
308 throw new RestException(401);
309 }
310 $result = $this->invoice->fetch($id);
311 if (!$result) {
312 throw new RestException(404, 'Supplier invoice not found');
313 }
314
315 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
316 throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
317 }
318
319 if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) {
320 throw new RestException(500, 'Error when deleting invoice');
321 }
322
323 return array(
324 'success' => array(
325 'code' => 200,
326 'message' => 'Supplier invoice deleted'
327 )
328 );
329 }
330
348 public function validate($id, $idwarehouse = 0, $notrigger = 0)
349 {
350 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
351 throw new RestException(401);
352 }
353 $result = $this->invoice->fetch($id);
354 if (!$result) {
355 throw new RestException(404, 'Invoice not found');
356 }
357
358 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
359 throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
360 }
361
362 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
363 if ($result == 0) {
364 throw new RestException(304, 'Error nothing done. The invoice is already validated');
365 }
366 if ($result < 0) {
367 throw new RestException(500, 'Error when validating Invoice: ' . $this->invoice->error);
368 }
369
370 return array(
371 'success' => array(
372 'code' => 200,
373 'message' => 'Invoice validated (Ref=' . $this->invoice->ref . ')'
374 )
375 );
376 }
377
391 public function getPayments($id)
392 {
393 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
394 throw new RestException(401);
395 }
396 if (empty($id)) {
397 throw new RestException(400, 'Invoice ID is mandatory');
398 }
399
400 $result = $this->invoice->fetch($id);
401 if (!$result) {
402 throw new RestException(404, 'Invoice not found');
403 }
404
405 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
406 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
407 }
408
409 $result = $this->invoice->getListOfPayments();
410 if ($result < 0) {
411 throw new RestException(405, $this->invoice->error);
412 }
413
414 return $result;
415 }
416
417
439 public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $amount = null)
440 {
441 global $conf;
442
443 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
444 throw new RestException(403);
445 }
446 if (empty($id)) {
447 throw new RestException(400, 'Invoice ID is mandatory');
448 }
449
450 $result = $this->invoice->fetch($id);
451 if (!$result) {
452 throw new RestException(404, 'Invoice not found');
453 }
454
455 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
456 throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
457 }
458
459 if (isModEnabled("banque")) {
460 if (empty($accountid)) {
461 throw new RestException(400, 'Bank account ID is mandatory');
462 }
463 }
464
465 if (empty($payment_mode_id)) {
466 throw new RestException(400, 'Payment mode ID is mandatory');
467 }
468
469 if (null !== $amount && $amount > 0) {
470 // We use the amount given in parameter
471 $paymentamount = $amount;
472 } else {
473 // We calculate the remain to pay, and use it as amount
474 $totalpaid = $this->invoice->getSommePaiement();
475 $totaldeposits = $this->invoice->getSumDepositsUsed();
476 $paymentamount = price2num($this->invoice->total_ttc - $totalpaid - $totaldeposits, 'MT');
477 }
478
479 $this->db->begin();
480
481 $amounts = array();
482 $multicurrency_amounts = array();
483
484 $paymentamount = price2num($paymentamount, 'MT');
485
486 $amounts[$id] = $paymentamount;
487
488 // Multicurrency
489 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
490 $multicurrency_amounts[$id] = $newvalue;
491
492 // Creation of payment line
493 $paiement = new PaiementFourn($this->db);
494 $paiement->datepaye = $datepaye;
495 $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
496 $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
497 $paiement->paiementid = $payment_mode_id;
498 $paiement->paiementcode = dol_getIdFromCode($this->db, $payment_mode_id, 'c_paiement', 'id', 'code', 1);
499 $paiement->num_payment = $num_payment;
500 $paiement->note_public = $comment;
501
502 $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
503 if ($paiement_id < 0) {
504 $this->db->rollback();
505 throw new RestException(400, 'Payment error : ' . $paiement->error);
506 }
507
508 if (isModEnabled("banque")) {
509 $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank);
510 if ($result < 0) {
511 $this->db->rollback();
512 throw new RestException(400, 'Add payment to bank error : ' . $paiement->error);
513 }
514 }
515
516 $this->db->commit();
517
518 return $paiement_id;
519 }
520
530 public function getLines($id)
531 {
532 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
533 throw new RestException(401);
534 }
535
536 $result = $this->invoice->fetch($id);
537 if (!$result) {
538 throw new RestException(404, 'Supplier invoice not found');
539 }
540
541 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
542 throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
543 }
544 $this->invoice->fetch_lines();
545 $result = array();
546 foreach ($this->invoice->lines as $line) {
547 array_push($result, $this->_cleanObjectDatas($line));
548 }
549 return $result;
550 }
551
566 public function postLine($id, $request_data = null)
567 {
568 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
569 throw new RestException(401);
570 }
571
572 $result = $this->invoice->fetch($id);
573 if (!$result) {
574 throw new RestException(404, 'Supplier invoice not found');
575 }
576
577 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
578 throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
579 }
580
581 $request_data = (object) $request_data;
582
583 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
584 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
585
586 $updateRes = $this->invoice->addline(
587 $request_data->description,
588 $request_data->pu_ht,
589 $request_data->tva_tx,
590 $request_data->localtax1_tx,
591 $request_data->localtax2_tx,
592 $request_data->qty,
593 $request_data->fk_product,
594 $request_data->remise_percent,
595 $request_data->date_start,
596 $request_data->date_end,
597 $request_data->ventil,
598 $request_data->info_bits,
599 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
600 $request_data->product_type,
601 $request_data->rang,
602 false,
603 $request_data->array_options,
604 $request_data->fk_unit,
605 $request_data->origin_id,
606 $request_data->multicurrency_subprice,
607 $request_data->ref_supplier,
608 $request_data->special_code
609 );
610
611 if ($updateRes < 0) {
612 throw new RestException(400, 'Unable to insert the new line. Check your inputs. ' . $this->invoice->error);
613 }
614
615 return $updateRes;
616 }
617
633 public function putLine($id, $lineid, $request_data = null)
634 {
635 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
636 throw new RestException(401);
637 }
638
639 $result = $this->invoice->fetch($id);
640 if (!$result) {
641 throw new RestException(404, 'Supplier invoice not found');
642 }
643
644 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
645 throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
646 }
647
648 $request_data = (object) $request_data;
649
650 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
651 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
652
653 $updateRes = $this->invoice->updateline(
654 $lineid,
655 $request_data->description,
656 $request_data->pu_ht,
657 $request_data->tva_tx,
658 $request_data->localtax1_tx,
659 $request_data->localtax2_tx,
660 $request_data->qty,
661 $request_data->fk_product,
662 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
663 $request_data->info_bits,
664 $request_data->product_type,
665 $request_data->remise_percent,
666 false,
667 $request_data->date_start,
668 $request_data->date_end,
669 $request_data->array_options,
670 $request_data->fk_unit,
671 $request_data->multicurrency_subprice,
672 $request_data->ref_supplier,
673 $request_data->rang
674 );
675
676 if ($updateRes > 0) {
677 $result = $this->get($id);
678 unset($result->line);
679 return $this->_cleanObjectDatas($result);
680 } else {
681 throw new RestException(304, $this->invoice->error);
682 }
683 }
684
700 public function deleteLine($id, $lineid)
701 {
702 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
703 throw new RestException(401);
704 }
705
706 $result = $this->invoice->fetch($id);
707 if (!$result) {
708 throw new RestException(404, 'Supplier invoice not found');
709 }
710
711 if (empty($lineid)) {
712 throw new RestException(400, 'Line ID is mandatory');
713 }
714
715 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
716 throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
717 }
718
719 // TODO Check the lineid $lineid is a line of ojbect
720
721 $updateRes = $this->invoice->deleteline($lineid);
722 if ($updateRes > 0) {
723 return $this->get($id);
724 } else {
725 throw new RestException(405, $this->invoice->error);
726 }
727 }
728
729 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
736 protected function _cleanObjectDatas($object)
737 {
738 // phpcs:enable
739 $object = parent::_cleanObjectDatas($object);
740
741 unset($object->rowid);
742 unset($object->barcode_type);
743 unset($object->barcode_type_code);
744 unset($object->barcode_type_label);
745 unset($object->barcode_type_coder);
746
747 return $object;
748 }
749
758 private function _validate($data)
759 {
760 $invoice = array();
761 foreach (SupplierInvoices::$FIELDS as $field) {
762 if (!isset($data[$field])) {
763 throw new RestException(400, "$field field missing");
764 }
765 $invoice[$field] = $data[$field];
766 }
767 return $invoice;
768 }
769}
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.
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.