dolibarr  21.0.0-alpha
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(403);
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(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
77  }
78 
79  $this->order->fetchObjectLinked();
80  return $this->_cleanObjectDatas($this->order);
81  }
82 
102  public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $product_ids = '', $status = '', $sqlfilters = '', $sqlfilterlines = '', $properties = '')
103  {
104  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
105  throw new RestException(403);
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") && !empty($socids)) {
116  $search_sale = DolibarrApiAccess::$user->id;
117  }
118 
119  $sql = "SELECT t.rowid";
120  $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur AS t";
121  $sql .= " 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
122  if (!empty($product_ids)) {
123  $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
124  }
125  $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
126  if (!empty($product_ids)) {
127  $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$this->db->sanitize($product_ids).")";
128  }
129  if ($socids) {
130  $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
131  }
132  // Filter by status
133  if ($status == 'draft') {
134  $sql .= " AND t.fk_statut IN (0)";
135  }
136  if ($status == 'validated') {
137  $sql .= " AND t.fk_statut IN (1)";
138  }
139  if ($status == 'approved') {
140  $sql .= " AND t.fk_statut IN (2)";
141  }
142  if ($status == 'running') {
143  $sql .= " AND t.fk_statut IN (3)";
144  }
145  if ($status == 'received_start') {
146  $sql .= " AND t.fk_statut IN (4)";
147  }
148  if ($status == 'received_end') {
149  $sql .= " AND t.fk_statut IN (5)";
150  }
151  if ($status == 'cancelled') {
152  $sql .= " AND t.fk_statut IN (6,7)";
153  }
154  if ($status == 'refused') {
155  $sql .= " AND t.fk_statut IN (9)";
156  }
157  // Search on sale representative
158  if ($search_sale && $search_sale != '-1') {
159  if ($search_sale == -2) {
160  $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
161  } elseif ($search_sale > 0) {
162  $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).")";
163  }
164  }
165  // Add sql filters
166  if ($sqlfilters) {
167  $errormessage = '';
168  $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
169  if ($errormessage) {
170  throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
171  }
172  }
173  // Add sql filters for lines
174  if ($sqlfilterlines) {
175  $errormessage = '';
176  $sql .= " AND EXISTS (SELECT tl.rowid FROM ".MAIN_DB_PREFIX."commande_fournisseurdet AS tl WHERE tl.fk_commande = t.rowid";
177  $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilterlines, $errormessage);
178  $sql .= ")";
179  if ($errormessage) {
180  throw new RestException(400, 'Error when validating parameter sqlfilterlines -> '.$errormessage);
181  }
182  }
183 
184  $sql .= $this->db->order($sortfield, $sortorder);
185  if ($limit) {
186  if ($page < 0) {
187  $page = 0;
188  }
189  $offset = $limit * $page;
190 
191  $sql .= $this->db->plimit($limit + 1, $offset);
192  }
193 
194  $result = $this->db->query($sql);
195  if ($result) {
196  $i = 0;
197  $num = $this->db->num_rows($result);
198  $min = min($num, ($limit <= 0 ? $num : $limit));
199  while ($i < $min) {
200  $obj = $this->db->fetch_object($result);
201  $order_static = new CommandeFournisseur($this->db);
202  if ($order_static->fetch($obj->rowid)) {
203  $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($order_static), $properties);
204  }
205  $i++;
206  }
207  } else {
208  throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
209  }
210 
211  return $obj_ret;
212  }
213 
222  public function post($request_data = null)
223  {
224  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
225  throw new RestException(403, "Insuffisant rights");
226  }
227  // Check mandatory fields
228  $result = $this->_validate($request_data);
229 
230  foreach ($request_data as $field => $value) {
231  if ($field === 'caller') {
232  // 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
233  $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
234  continue;
235  }
236 
237  $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
238  }
239  if (!array_keys($request_data, 'date')) {
240  $this->order->date = dol_now();
241  }
242  /* We keep lines as an array
243  if (isset($request_data["lines"])) {
244  $lines = array();
245  foreach ($request_data["lines"] as $line) {
246  array_push($lines, (object) $line);
247  }
248  $this->order->lines = $lines;
249  }*/
250 
251  if ($this->order->create(DolibarrApiAccess::$user) < 0) {
252  throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
253  }
254  return $this->order->id;
255  }
256 
264  public function put($id, $request_data = null)
265  {
266  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
267  throw new RestException(403);
268  }
269 
270  $result = $this->order->fetch($id);
271  if (!$result) {
272  throw new RestException(404, 'Supplier order not found');
273  }
274 
275  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
276  throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
277  }
278 
279  foreach ($request_data as $field => $value) {
280  if ($field == 'id') {
281  continue;
282  }
283  if ($field === 'caller') {
284  // 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
285  $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
286  continue;
287  }
288  if ($field == 'array_options' && is_array($value)) {
289  foreach ($value as $index => $val) {
290  $this->order->array_options[$index] = $this->_checkValForAPI($field, $val, $this->order);
291  }
292  continue;
293  }
294  $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
295  }
296 
297  if ($this->order->update(DolibarrApiAccess::$user)) {
298  return $this->get($id);
299  }
300 
301  return false;
302  }
303 
318  public function getContacts($id, $source, $type = '')
319  {
320  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
321  throw new RestException(403);
322  }
323 
324  $result = $this->order->fetch($id);
325  if (!$result) {
326  throw new RestException(404, 'Supplier order not found');
327  }
328 
329  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
330  throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
331  }
332  $contacts = array();
333 
334  if ($source == 'all' || $source == 'external') {
335  $tmpContacts = $this->order->liste_contact(-1, 'external', 0, $type);
336  $contacts = array_merge($contacts, $tmpContacts);
337  }
338 
339  if ($source == 'all' || $source == 'internal') {
340  $tmpContacts = $this->order->liste_contact(-1, 'internal', 0, $type);
341  $contacts = array_merge($contacts, $tmpContacts);
342  }
343 
344  return $this->_cleanObjectDatas($contacts);
345  }
346 
361  public function postContact($id, $contactid, $type, $source)
362  {
363  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
364  throw new RestException(403);
365  }
366 
367  $result = $this->order->fetch($id);
368  if (!$result) {
369  throw new RestException(404, 'Supplier order not found');
370  }
371 
372  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
373  throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
374  }
375 
376  $result = $this->order->add_contact($contactid, $type, $source);
377 
378  if ($result < 0) {
379  throw new RestException(500, 'Error when added the contact');
380  }
381 
382  if ($result == 0) {
383  throw new RestException(304, 'contact already added');
384  }
385 
386  return array(
387  'success' => array(
388  'code' => 200,
389  'message' => 'Contact linked to the order'
390  )
391  );
392  }
393 
410  public function deleteContact($id, $contactid, $type, $source)
411  {
412  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
413  throw new RestException(403);
414  }
415 
416  $result = $this->order->fetch($id);
417  if (!$result) {
418  throw new RestException(404, 'Supplier order not found');
419  }
420 
421  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
422  throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
423  }
424 
425  $contacts = $this->order->liste_contact(-1, $source, 0, $type);
426 
427  $contactToUnlink = 0;
428  foreach ($contacts as $contact) {
429  if ($contact['id'] == $contactid && $contact['code'] == $type) {
430  $contactToUnlink = $contact['rowid'];
431  break;
432  }
433  }
434 
435  if ($contactToUnlink == 0) {
436  throw new RestException(404, 'Linked contact not found');
437  }
438 
439  $result = $this->order->delete_contact($contact['rowid']);
440 
441  if (!$result) {
442  throw new RestException(500, 'Error when deleted the contact');
443  }
444 
445  return array(
446  'success' => array(
447  'code' => 200,
448  'message' => 'Contact unlinked from supplier order'
449  )
450  );
451  }
452 
459  public function delete($id)
460  {
461  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "supprimer")) {
462  throw new RestException(403);
463  }
464  $result = $this->order->fetch($id);
465  if (!$result) {
466  throw new RestException(404, 'Supplier order not found');
467  }
468 
469  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
470  throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
471  }
472 
473  if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
474  throw new RestException(500, 'Error when deleting order');
475  }
476 
477  return array(
478  'success' => array(
479  'code' => 200,
480  'message' => 'Supplier order deleted'
481  )
482  );
483  }
484 
485 
504  public function validate($id, $idwarehouse = 0, $notrigger = 0)
505  {
506  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
507  throw new RestException(403);
508  }
509  $result = $this->order->fetch($id);
510  if (!$result) {
511  throw new RestException(404, 'Order not found');
512  }
513 
514  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
515  throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
516  }
517 
518  $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
519  if ($result == 0) {
520  throw new RestException(304, 'Error nothing done. May be object is already validated');
521  }
522  if ($result < 0) {
523  throw new RestException(500, 'Error when validating Order: '.$this->order->error);
524  }
525 
526  return array(
527  'success' => array(
528  'code' => 200,
529  'message' => 'Order validated (Ref='.$this->order->ref.')'
530  )
531  );
532  }
533 
552  public function approve($id, $idwarehouse = 0, $secondlevel = 0)
553  {
554  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
555  throw new RestException(403);
556  }
557  $result = $this->order->fetch($id);
558  if (!$result) {
559  throw new RestException(404, 'Order not found');
560  }
561 
562  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
563  throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
564  }
565 
566  $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
567  if ($result == 0) {
568  throw new RestException(304, 'Error nothing done. May be object is already approved');
569  }
570  if ($result < 0) {
571  throw new RestException(500, 'Error when approve Order: '.$this->order->error);
572  }
573 
574  return array(
575  'success' => array(
576  'code' => 200,
577  'message' => 'Order approved (Ref='.$this->order->ref.')'
578  )
579  );
580  }
581 
582 
603  public function makeOrder($id, $date, $method, $comment = '')
604  {
605  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
606  throw new RestException(403);
607  }
608  $result = $this->order->fetch($id);
609  if (!$result) {
610  throw new RestException(404, 'Order not found');
611  }
612 
613  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
614  throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
615  }
616 
617  $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
618  if ($result == 0) {
619  throw new RestException(304, 'Error nothing done. May be object is already sent');
620  }
621  if ($result < 0) {
622  throw new RestException(500, 'Error when sending Order: '.$this->order->error);
623  }
624 
625  return array(
626  'success' => array(
627  'code' => 200,
628  'message' => 'Order sent (Ref='.$this->order->ref.')'
629  )
630  );
631  }
632 
666  public function receiveOrder($id, $closeopenorder, $comment, $lines)
667  {
668  if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
669  throw new RestException(403);
670  }
671  $result = $this->order->fetch($id);
672  if (!$result) {
673  throw new RestException(404, 'Order not found');
674  }
675 
676  if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
677  throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
678  }
679 
680  foreach ($lines as $line) {
681  $lineObj =(object) $line;
682 
683  $result=$this->order->dispatchProduct(
684  DolibarrApiAccess::$user,
685  $lineObj->fk_product,
686  $lineObj->qty,
687  $lineObj->warehouse,
688  $lineObj->price,
689  $lineObj->comment,
690  $lineObj->eatby,
691  $lineObj->sellby,
692  $lineObj->batch,
693  $lineObj->id,
694  $lineObj->notrigger
695  );
696 
697  if ($result < 0) {
698  throw new RestException(500, 'Error dispatch order line '.$line->id.': '.$this->order->error);
699  }
700  }
701 
702  $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
703 
704  if ($result == 0) {
705  throw new RestException(304, 'Error nothing done. May be object is already dispatched');
706  }
707  if ($result < 0) {
708  throw new RestException(500, 'Error when receivce order: '.$this->order->error);
709  }
710 
711  return array(
712  'success' => array(
713  'code' => 200,
714  'message' => 'Order received (Ref='.$this->order->ref.')'
715  )
716  );
717  }
718 
719  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
726  protected function _cleanObjectDatas($object)
727  {
728  // phpcs:enable
729  $object = parent::_cleanObjectDatas($object);
730 
731  unset($object->rowid);
732  unset($object->barcode_type);
733  unset($object->barcode_type_code);
734  unset($object->barcode_type_label);
735  unset($object->barcode_type_coder);
736 
737  return $object;
738  }
739 
748  private function _validate($data)
749  {
750  $order = array();
751  foreach (SupplierOrders::$FIELDS as $field) {
752  if (!isset($data[$field])) {
753  throw new RestException(400, "$field field missing");
754  }
755  $order[$field] = $data[$field];
756  }
757  return $order;
758  }
759 }
if($user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition: card.php:58
Class to manage predefined suppliers products.
Class for API REST v1.
Definition: api.class.php:30
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
Definition: api.class.php:136
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:369
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition: api.class.php:82
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='', $sqlfilterlines='', $properties='')
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('invoice') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&!getDolGlobalString('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') && $user->hasRight('tax', 'charges', 'lire')) if(isModEnabled('invoice') &&isModEnabled('order') && $user->hasRight("commande", "lire") &&!getDolGlobalString('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')) $sql
Social contributions to pay.
Definition: index.php:751
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.