dolibarr 18.0.6
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
101 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '')
102 {
103 global $db;
104
105 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
106 throw new RestException(401);
107 }
108
109 $obj_ret = array();
110
111 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
112 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
113
114 // If the internal user must only see his customers, force searching by him
115 $search_sale = 0;
116 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir")) {
117 $search_sale = DolibarrApiAccess::$user->id;
118 }
119
120 $sql = "SELECT t.rowid";
121 // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
122 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") || $search_sale > 0) {
123 $sql .= ", sc.fk_soc, sc.fk_user";
124 }
125 $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
126
127 // We need this table joined to the select in order to filter by sale
128 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") || $search_sale > 0) {
129 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
130 }
131
132 $sql .= ' WHERE t.entity IN ('.getEntity('supplier_invoice').')';
133 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") || $search_sale > 0) {
134 $sql .= " AND t.fk_soc = sc.fk_soc";
135 }
136 if ($socids) {
137 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
138 }
139 if ($search_sale > 0) {
140 $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
141 }
142
143 // Filter by status
144 if ($status == 'draft') {
145 $sql .= " AND t.fk_statut IN (0)";
146 }
147 if ($status == 'unpaid') {
148 $sql .= " AND t.fk_statut IN (1)";
149 }
150 if ($status == 'paid') {
151 $sql .= " AND t.fk_statut IN (2)";
152 }
153 if ($status == 'cancelled') {
154 $sql .= " AND t.fk_statut IN (3)";
155 }
156 // Insert sale filter
157 if ($search_sale > 0) {
158 $sql .= " AND sc.fk_user = ".((int) $search_sale);
159 }
160 // Add sql filters
161 if ($sqlfilters) {
162 $errormessage = '';
163 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
164 if ($errormessage) {
165 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
166 }
167 }
168
169 $sql .= $this->db->order($sortfield, $sortorder);
170 if ($limit) {
171 if ($page < 0) {
172 $page = 0;
173 }
174 $offset = $limit * $page;
175
176 $sql .= $this->db->plimit($limit + 1, $offset);
177 }
178
179 $result = $this->db->query($sql);
180 if ($result) {
181 $i = 0;
182 $num = $this->db->num_rows($result);
183 $min = min($num, ($limit <= 0 ? $num : $limit));
184 while ($i < $min) {
185 $obj = $this->db->fetch_object($result);
186 $invoice_static = new FactureFournisseur($this->db);
187 if ($invoice_static->fetch($obj->rowid)) {
188 $obj_ret[] = $this->_cleanObjectDatas($invoice_static);
189 }
190 $i++;
191 }
192 } else {
193 throw new RestException(503, 'Error when retrieve supplier invoice list : '.$this->db->lasterror());
194 }
195 if (!count($obj_ret)) {
196 throw new RestException(404, 'No supplier invoice found');
197 }
198 return $obj_ret;
199 }
200
215 public function post($request_data = null)
216 {
217 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
218 throw new RestException(401, "Insuffisant rights");
219 }
220 // Check mandatory fields
221 $result = $this->_validate($request_data);
222
223 foreach ($request_data as $field => $value) {
224 $this->invoice->$field = $value;
225 }
226 if (!array_key_exists('date', $request_data)) {
227 $this->invoice->date = dol_now();
228 }
229
230 if ($this->invoice->create(DolibarrApiAccess::$user) < 0) {
231 throw new RestException(500, "Error creating invoice ", array_merge(array($this->invoice->error), $this->invoice->errors));
232 }
233 return $this->invoice->id;
234 }
235
247 public function put($id, $request_data = null)
248 {
249 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
250 throw new RestException(401);
251 }
252
253 $result = $this->invoice->fetch($id);
254 if (!$result) {
255 throw new RestException(404, 'Supplier invoice not found');
256 }
257
258 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
259 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
260 }
261
262 foreach ($request_data as $field => $value) {
263 if ($field == 'id') {
264 continue;
265 }
266 if ($field == 'array_options' && is_array($value)) {
267 foreach ($value as $index => $val) {
268 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
269 }
270 continue;
271 }
272 $this->invoice->$field = $value;
273 }
274
275 if ($this->invoice->update(DolibarrApiAccess::$user)) {
276 return $this->get($id);
277 }
278
279 return false;
280 }
281
293 public function delete($id)
294 {
295 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "supprimer")) {
296 throw new RestException(401);
297 }
298 $result = $this->invoice->fetch($id);
299 if (!$result) {
300 throw new RestException(404, 'Supplier invoice not found');
301 }
302
303 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
304 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
305 }
306
307 if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) {
308 throw new RestException(500, 'Error when deleting invoice');
309 }
310
311 return array(
312 'success' => array(
313 'code' => 200,
314 'message' => 'Supplier invoice deleted'
315 )
316 );
317 }
318
336 public function validate($id, $idwarehouse = 0, $notrigger = 0)
337 {
338 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
339 throw new RestException(401);
340 }
341 $result = $this->invoice->fetch($id);
342 if (!$result) {
343 throw new RestException(404, 'Invoice not found');
344 }
345
346 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
347 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
348 }
349
350 $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
351 if ($result == 0) {
352 throw new RestException(304, 'Error nothing done. The invoice is already validated');
353 }
354 if ($result < 0) {
355 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
356 }
357
358 return array(
359 'success' => array(
360 'code' => 200,
361 'message' => 'Invoice validated (Ref='.$this->invoice->ref.')'
362 )
363 );
364 }
365
379 public function getPayments($id)
380 {
381 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "lire")) {
382 throw new RestException(401);
383 }
384 if (empty($id)) {
385 throw new RestException(400, 'Invoice ID is mandatory');
386 }
387
388 $result = $this->invoice->fetch($id);
389 if (!$result) {
390 throw new RestException(404, 'Invoice not found');
391 }
392
393 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
394 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
395 }
396
397 $result = $this->invoice->getListOfPayments();
398 if ($result < 0) {
399 throw new RestException(405, $this->invoice->error);
400 }
401
402 return $result;
403 }
404
405
426 public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
427 {
428 global $conf;
429
430 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
431 throw new RestException(403);
432 }
433 if (empty($id)) {
434 throw new RestException(400, 'Invoice ID is mandatory');
435 }
436
437 $result = $this->invoice->fetch($id);
438 if (!$result) {
439 throw new RestException(404, 'Invoice not found');
440 }
441
442 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
443 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
444 }
445
446 if (isModEnabled("banque")) {
447 if (empty($accountid)) {
448 throw new RestException(400, 'Bank account ID is mandatory');
449 }
450 }
451
452 if (empty($payment_mode_id)) {
453 throw new RestException(400, 'Payment mode ID is mandatory');
454 }
455
456 // Calculate amount to pay
457 $totalpaid = $this->invoice->getSommePaiement();
458 $totaldeposits = $this->invoice->getSumDepositsUsed();
459 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totaldeposits, 'MT');
460
461 $this->db->begin();
462
463 $amounts = array();
464 $multicurrency_amounts = array();
465
466 $resteapayer = price2num($resteapayer, 'MT');
467 $amounts[$id] = $resteapayer;
468
469 // Multicurrency
470 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
471 $multicurrency_amounts[$id] = $newvalue;
472
473 // Creation of payment line
474 $paiement = new PaiementFourn($this->db);
475 $paiement->datepaye = $datepaye;
476 $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
477 $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
478 $paiement->paiementid = $payment_mode_id;
479 $paiement->paiementcode = dol_getIdFromCode($this->db, $payment_mode_id, 'c_paiement', 'id', 'code', 1);
480 $paiement->num_payment = $num_payment;
481 $paiement->note_public = $comment;
482
483 $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
484 if ($paiement_id < 0) {
485 $this->db->rollback();
486 throw new RestException(400, 'Payment error : '.$paiement->error);
487 }
488
489 if (isModEnabled("banque")) {
490 $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank);
491 if ($result < 0) {
492 $this->db->rollback();
493 throw new RestException(400, 'Add payment to bank error : '.$paiement->error);
494 }
495 }
496
497 $this->db->commit();
498
499 return $paiement_id;
500 }
501
511 public function getLines($id)
512 {
513 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
514 throw new RestException(401);
515 }
516
517 $result = $this->invoice->fetch($id);
518 if (!$result) {
519 throw new RestException(404, 'Supplier invoice not found');
520 }
521
522 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
523 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
524 }
525 $this->invoice->fetch_lines();
526 $result = array();
527 foreach ($this->invoice->lines as $line) {
528 array_push($result, $this->_cleanObjectDatas($line));
529 }
530 return $result;
531 }
532
547 public function postLine($id, $request_data = null)
548 {
549 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
550 throw new RestException(401);
551 }
552
553 $result = $this->invoice->fetch($id);
554 if (!$result) {
555 throw new RestException(404, 'Supplier invoice not found');
556 }
557
558 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
559 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
560 }
561
562 $request_data = (object) $request_data;
563
564 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
565 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
566
567 $updateRes = $this->invoice->addline(
568 $request_data->description,
569 $request_data->pu_ht,
570 $request_data->tva_tx,
571 $request_data->localtax1_tx,
572 $request_data->localtax2_tx,
573 $request_data->qty,
574 $request_data->fk_product,
575 $request_data->remise_percent,
576 $request_data->date_start,
577 $request_data->date_end,
578 $request_data->ventil,
579 $request_data->info_bits,
580 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
581 $request_data->product_type,
582 $request_data->rang,
583 false,
584 $request_data->array_options,
585 $request_data->fk_unit,
586 $request_data->origin_id,
587 $request_data->multicurrency_subprice,
588 $request_data->ref_supplier,
589 $request_data->special_code
590 );
591
592 if ($updateRes < 0) {
593 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
594 }
595
596 return $updateRes;
597 }
598
614 public function putLine($id, $lineid, $request_data = null)
615 {
616 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
617 throw new RestException(401);
618 }
619
620 $result = $this->invoice->fetch($id);
621 if (!$result) {
622 throw new RestException(404, 'Supplier invoice not found');
623 }
624
625 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
626 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
627 }
628
629 $request_data = (object) $request_data;
630
631 $request_data->description = sanitizeVal($request_data->description, 'restricthtml');
632 $request_data->ref_supplier = sanitizeVal($request_data->ref_supplier);
633
634 $updateRes = $this->invoice->updateline(
635 $lineid,
636 $request_data->description,
637 $request_data->pu_ht,
638 $request_data->tva_tx,
639 $request_data->localtax1_tx,
640 $request_data->localtax2_tx,
641 $request_data->qty,
642 $request_data->fk_product,
643 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
644 $request_data->info_bits,
645 $request_data->product_type,
646 $request_data->remise_percent,
647 false,
648 $request_data->date_start,
649 $request_data->date_end,
650 $request_data->array_options,
651 $request_data->fk_unit,
652 $request_data->multicurrency_subprice,
653 $request_data->ref_supplier,
654 $request_data->rang
655 );
656
657 if ($updateRes > 0) {
658 $result = $this->get($id);
659 unset($result->line);
660 return $this->_cleanObjectDatas($result);
661 } else {
662 throw new RestException(304, $this->invoice->error);
663 }
664 }
665
681 public function deleteLine($id, $lineid)
682 {
683 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "facture", "creer")) {
684 throw new RestException(401);
685 }
686
687 $result = $this->invoice->fetch($id);
688 if (!$result) {
689 throw new RestException(404, 'Supplier invoice not found');
690 }
691
692 if (empty($lineid)) {
693 throw new RestException(400, 'Line ID is mandatory');
694 }
695
696 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
697 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
698 }
699
700 // TODO Check the lineid $lineid is a line of ojbect
701
702 $updateRes = $this->invoice->deleteline($lineid);
703 if ($updateRes > 0) {
704 return $this->get($id);
705 } else {
706 throw new RestException(405, $this->invoice->error);
707 }
708 }
709
710 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
717 protected function _cleanObjectDatas($object)
718 {
719 // phpcs:enable
720 $object = parent::_cleanObjectDatas($object);
721
722 unset($object->rowid);
723 unset($object->barcode_type);
724 unset($object->barcode_type_code);
725 unset($object->barcode_type_label);
726 unset($object->barcode_type_coder);
727
728 return $object;
729 }
730
739 private function _validate($data)
740 {
741 $invoice = array();
742 foreach (SupplierInvoices::$FIELDS as $field) {
743 if (!isset($data[$field])) {
744 throw new RestException(400, "$field field missing");
745 }
746 $invoice[$field] = $data[$field];
747 }
748 return $invoice;
749 }
750}
Class for API REST v1.
Definition api.class.php:31
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:86
Class to manage suppliers invoices.
Class to manage payments for supplier invoices.
validate($id, $idwarehouse=0, $notrigger=0)
Validate an invoice.
addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='')
Add payment line to a specific supplier invoice with the remain to pay as amount.
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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='')
List invoices.
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.
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.