dolibarr  19.0.0-dev
api_supplier_orders.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 
19 use Luracast\Restler\RestException;
20 
21 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
22 
30 {
35  public static $FIELDS = array(
36  'socid'
37  );
38 
42  public $order;
43 
47  public function __construct()
48  {
49  global $db, $conf;
50  $this->db = $db;
51  $this->order = new CommandeFournisseur($this->db);
52  }
53 
64  public function get($id)
65  {
66  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
67  throw new RestException(401);
68  }
69 
70  $result = $this->order->fetch($id);
71  if (!$result) {
72  throw new RestException(404, 'Supplier order not found');
73  }
74 
75  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
76  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
77  }
78 
79  $this->order->fetchObjectLinked();
80  return $this->_cleanObjectDatas($this->order);
81  }
82 
100  public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $product_ids = '', $status = '', $sqlfilters = '')
101  {
102  global $db, $conf;
103 
104  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
105  throw new RestException(401);
106  }
107 
108  $obj_ret = array();
109 
110  // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
111  $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
112 
113  // If the internal user must only see his customers, force searching by him
114  $search_sale = 0;
115  if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") && !$socids) {
116  $search_sale = DolibarrApiAccess::$user->id;
117  }
118 
119  $sql = "SELECT t.rowid";
120  if ((!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") && !$socids) || $search_sale > 0) {
121  $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
122  }
123  $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur AS t LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur_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
124 
125  if ((!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") && !$socids) || $search_sale > 0) {
126  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
127  }
128 
129  if (!empty($product_ids)) {
130  $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
131  }
132 
133  $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
134  if ((!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") && !$socids) || $search_sale > 0) {
135  $sql .= " AND t.fk_soc = sc.fk_soc";
136  }
137  if (!empty($product_ids)) {
138  $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$this->db->sanitize($product_ids).")";
139  }
140  if ($socids) {
141  $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
142  }
143  if ($search_sale > 0) {
144  $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
145  }
146 
147  // Filter by status
148  if ($status == 'draft') {
149  $sql .= " AND t.fk_statut IN (0)";
150  }
151  if ($status == 'validated') {
152  $sql .= " AND t.fk_statut IN (1)";
153  }
154  if ($status == 'approved') {
155  $sql .= " AND t.fk_statut IN (2)";
156  }
157  if ($status == 'running') {
158  $sql .= " AND t.fk_statut IN (3)";
159  }
160  if ($status == 'received_start') {
161  $sql .= " AND t.fk_statut IN (4)";
162  }
163  if ($status == 'received_end') {
164  $sql .= " AND t.fk_statut IN (5)";
165  }
166  if ($status == 'cancelled') {
167  $sql .= " AND t.fk_statut IN (6,7)";
168  }
169  if ($status == 'refused') {
170  $sql .= " AND t.fk_statut IN (9)";
171  }
172  // Insert sale filter
173  if ($search_sale > 0) {
174  $sql .= " AND sc.fk_user = ".((int) $search_sale);
175  }
176  // Add sql filters
177  if ($sqlfilters) {
178  $errormessage = '';
179  $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
180  if ($errormessage) {
181  throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
182  }
183  }
184 
185  $sql .= $this->db->order($sortfield, $sortorder);
186  if ($limit) {
187  if ($page < 0) {
188  $page = 0;
189  }
190  $offset = $limit * $page;
191 
192  $sql .= $this->db->plimit($limit + 1, $offset);
193  }
194 
195  $result = $this->db->query($sql);
196  if ($result) {
197  $i = 0;
198  $num = $this->db->num_rows($result);
199  $min = min($num, ($limit <= 0 ? $num : $limit));
200  while ($i < $min) {
201  $obj = $this->db->fetch_object($result);
202  $order_static = new CommandeFournisseur($this->db);
203  if ($order_static->fetch($obj->rowid)) {
204  $obj_ret[] = $this->_cleanObjectDatas($order_static);
205  }
206  $i++;
207  }
208  } else {
209  throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
210  }
211  if (!count($obj_ret)) {
212  throw new RestException(404, 'No supplier order found');
213  }
214  return $obj_ret;
215  }
216 
225  public function post($request_data = null)
226  {
227  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
228  throw new RestException(401, "Insuffisant rights");
229  }
230  // Check mandatory fields
231  $result = $this->_validate($request_data);
232 
233  foreach ($request_data as $field => $value) {
234  $this->order->$field = $value;
235  }
236  if (!array_keys($request_data, 'date')) {
237  $this->order->date = dol_now();
238  }
239  /* We keep lines as an array
240  if (isset($request_data["lines"])) {
241  $lines = array();
242  foreach ($request_data["lines"] as $line) {
243  array_push($lines, (object) $line);
244  }
245  $this->order->lines = $lines;
246  }*/
247 
248  if ($this->order->create(DolibarrApiAccess::$user) < 0) {
249  throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
250  }
251  return $this->order->id;
252  }
253 
261  public function put($id, $request_data = null)
262  {
263  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
264  throw new RestException(401);
265  }
266 
267  $result = $this->order->fetch($id);
268  if (!$result) {
269  throw new RestException(404, 'Supplier order not found');
270  }
271 
272  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
273  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
274  }
275 
276  foreach ($request_data as $field => $value) {
277  if ($field == 'id') {
278  continue;
279  }
280  $this->order->$field = $value;
281  }
282 
283  if ($this->order->update(DolibarrApiAccess::$user)) {
284  return $this->get($id);
285  }
286 
287  return false;
288  }
289 
304  public function getContacts($id, $source, $type = '')
305  {
306  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
307  throw new RestException(401);
308  }
309 
310  $result = $this->order->fetch($id);
311  if (!$result) {
312  throw new RestException(404, 'Supplier order not found');
313  }
314 
315  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
316  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
317  }
318  $contacts = array();
319 
320  if ($source == 'all' || $source == 'external') {
321  $tmpContacts = $this->order->liste_contact(-1, 'external', 0, $type);
322  $contacts = array_merge($contacts, $tmpContacts);
323  }
324 
325  if ($source == 'all' || $source == 'internal') {
326  $tmpContacts = $this->order->liste_contact(-1, 'internal', 0, $type);
327  $contacts = array_merge($contacts, $tmpContacts);
328  }
329 
330  return $this->_cleanObjectDatas($contacts);
331  }
332 
347  public function postContact($id, $contactid, $type, $source)
348  {
349  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
350  throw new RestException(401);
351  }
352 
353  $result = $this->order->fetch($id);
354  if (!$result) {
355  throw new RestException(404, 'Supplier order not found');
356  }
357 
358  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
359  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
360  }
361 
362  $result = $this->order->add_contact($contactid, $type, $source);
363 
364  if ($result < 0) {
365  throw new RestException(500, 'Error when added the contact');
366  }
367 
368  if ($result == 0) {
369  throw new RestException(304, 'contact already added');
370  }
371 
372  return array(
373  'success' => array(
374  'code' => 200,
375  'message' => 'Contact linked to the order'
376  )
377  );
378  }
379 
396  public function deleteContact($id, $contactid, $type, $source)
397  {
398  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
399  throw new RestException(401);
400  }
401 
402  $result = $this->order->fetch($id);
403  if (!$result) {
404  throw new RestException(404, 'Supplier order not found');
405  }
406 
407  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
408  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
409  }
410 
411  $contacts = $this->order->liste_contact(-1, $source, 0, $type);
412 
413  $contactToUnlink = 0;
414  foreach ($contacts as $contact) {
415  if ($contact['id'] == $contactid && $contact['code'] == $type) {
416  $contactToUnlink = $contact['rowid'];
417  break;
418  }
419  }
420 
421  if ($contactToUnlink == 0) {
422  throw new RestException(404, 'Linked contact not found');
423  }
424 
425  $result = $this->order->delete_contact($contact['rowid']);
426 
427  if (!$result) {
428  throw new RestException(500, 'Error when deleted the contact');
429  }
430 
431  return array(
432  'success' => array(
433  'code' => 200,
434  'message' => 'Contact unlinked from supplier order'
435  )
436  );
437  }
438 
445  public function delete($id)
446  {
447  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "supprimer")) {
448  throw new RestException(401);
449  }
450  $result = $this->order->fetch($id);
451  if (!$result) {
452  throw new RestException(404, 'Supplier order not found');
453  }
454 
455  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
456  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
457  }
458 
459  if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
460  throw new RestException(500, 'Error when deleting order');
461  }
462 
463  return array(
464  'success' => array(
465  'code' => 200,
466  'message' => 'Supplier order deleted'
467  )
468  );
469  }
470 
471 
490  public function validate($id, $idwarehouse = 0, $notrigger = 0)
491  {
492  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
493  throw new RestException(401);
494  }
495  $result = $this->order->fetch($id);
496  if (!$result) {
497  throw new RestException(404, 'Order not found');
498  }
499 
500  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
501  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
502  }
503 
504  $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
505  if ($result == 0) {
506  throw new RestException(304, 'Error nothing done. May be object is already validated');
507  }
508  if ($result < 0) {
509  throw new RestException(500, 'Error when validating Order: '.$this->order->error);
510  }
511 
512  return array(
513  'success' => array(
514  'code' => 200,
515  'message' => 'Order validated (Ref='.$this->order->ref.')'
516  )
517  );
518  }
519 
538  public function approve($id, $idwarehouse = 0, $secondlevel = 0)
539  {
540  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
541  throw new RestException(401);
542  }
543  $result = $this->order->fetch($id);
544  if (!$result) {
545  throw new RestException(404, 'Order not found');
546  }
547 
548  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
549  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
550  }
551 
552  $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
553  if ($result == 0) {
554  throw new RestException(304, 'Error nothing done. May be object is already approved');
555  }
556  if ($result < 0) {
557  throw new RestException(500, 'Error when approve Order: '.$this->order->error);
558  }
559 
560  return array(
561  'success' => array(
562  'code' => 200,
563  'message' => 'Order approved (Ref='.$this->order->ref.')'
564  )
565  );
566  }
567 
568 
589  public function makeOrder($id, $date, $method, $comment = '')
590  {
591  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
592  throw new RestException(401);
593  }
594  $result = $this->order->fetch($id);
595  if (!$result) {
596  throw new RestException(404, 'Order not found');
597  }
598 
599  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
600  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
601  }
602 
603  $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
604  if ($result == 0) {
605  throw new RestException(304, 'Error nothing done. May be object is already sent');
606  }
607  if ($result < 0) {
608  throw new RestException(500, 'Error when sending Order: '.$this->order->error);
609  }
610 
611  return array(
612  'success' => array(
613  'code' => 200,
614  'message' => 'Order sent (Ref='.$this->order->ref.')'
615  )
616  );
617  }
618 
652  public function receiveOrder($id, $closeopenorder, $comment, $lines)
653  {
654  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
655  throw new RestException(401);
656  }
657  $result = $this->order->fetch($id);
658  if (!$result) {
659  throw new RestException(404, 'Order not found');
660  }
661 
662  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
663  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
664  }
665 
666  foreach ($lines as $line) {
667  $lineObj =(object) $line;
668 
669  $result=$this->order->dispatchProduct(DolibarrApiAccess::$user,
670  $lineObj->fk_product,
671  $lineObj->qty,
672  $lineObj->warehouse,
673  $lineObj->price,
674  $lineObj->comment,
675  $lineObj->eatby,
676  $lineObj->sellby,
677  $lineObj->batch,
678  $lineObj->id,
679  $lineObj->notrigger);
680 
681  if ($result < 0) {
682  throw new RestException(500, 'Error dispatch order line '.$line->id.': '.$this->order->error);
683  }
684  }
685 
686  $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
687 
688  if ($result == 0) {
689  throw new RestException(304, 'Error nothing done. May be object is already dispatched');
690  }
691  if ($result < 0) {
692  throw new RestException(500, 'Error when receivce order: '.$this->order->error);
693  }
694 
695  return array(
696  'success' => array(
697  'code' => 200,
698  'message' => 'Order received (Ref='.$this->order->ref.')'
699  )
700  );
701  }
702 
703  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
710  protected function _cleanObjectDatas($object)
711  {
712  // phpcs:enable
713  $object = parent::_cleanObjectDatas($object);
714 
715  unset($object->rowid);
716  unset($object->barcode_type);
717  unset($object->barcode_type_code);
718  unset($object->barcode_type_label);
719  unset($object->barcode_type_coder);
720 
721  return $object;
722  }
723 
732  private function _validate($data)
733  {
734  $order = array();
735  foreach (SupplierOrders::$FIELDS as $field) {
736  if (!isset($data[$field])) {
737  throw new RestException(400, "$field field missing");
738  }
739  $order[$field] = $data[$field];
740  }
741  return $order;
742  }
743 }
Class to manage predefined suppliers products.
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.
Definition: api.class.php:282
validate($id, $idwarehouse=0, $notrigger=0)
Validate an order.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $product_ids='', $status='', $sqlfilters='')
List orders.
put($id, $request_data=null)
Update supplier order.
post($request_data=null)
Create supplier order object.
_cleanObjectDatas($object)
Clean sensible object datas.
deleteContact($id, $contactid, $type, $source)
Unlink a contact type of given supplier order.
makeOrder($id, $date, $method, $comment='')
Sends an order to the vendor.
postContact($id, $contactid, $type, $source)
Add a contact type of given supplier order.
getContacts($id, $source, $type='')
Get contacts of given supplier order.
_validate($data)
Validate fields before create or update object.
approve($id, $idwarehouse=0, $secondlevel=0)
Approve an order.
receiveOrder($id, $closeopenorder, $comment, $lines)
Receives the order, dispatches products.
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.