Passed
Branch develop (05352a)
by
unknown
27:04
created

Orders::_fetch()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
nc 4
nop 5
dl 0
loc 19
rs 9.9332
c 2
b 0
f 0
1
<?php
2
/* Copyright (C) 2015   Jean-François Ferry     <[email protected]>
3
 * Copyright (C) 2016	Laurent Destailleur		<[email protected]>
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.'/commande/class/commande.class.php';
22
23
/**
24
 * API class for orders
25
 *
26
 * @access protected
27
 * @class  DolibarrApiAccess {@requires user,external}
28
 */
29
class Orders extends DolibarrApi
30
{
31
32
    /**
33
     * @var array   $FIELDS     Mandatory fields, checked when create and update object
34
     */
35
    static $FIELDS = array(
36
        'socid'
37
    );
38
39
    /**
40
     * @var Commande $commande {@type Commande}
41
     */
42
    public $commande;
43
44
    /**
45
     * Constructor
46
     */
47
    public function __construct()
48
    {
49
        global $db, $conf;
50
        $this->db = $db;
51
        $this->commande = new Commande($this->db);
52
    }
53
54
    /**
55
     * Get properties of an order object by id
56
     *
57
     * Return an array with order informations
58
     *
59
     * @param       int         $id            ID of order
60
     * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
61
     * @return 	array|mixed data without useless information
62
	 *
63
     * @throws 	RestException
64
     */
65
    public function get($id, $contact_list = 1)
66
    {
67
        return $this->_fetch($id, '', '', '', $contact_list);
68
    }
69
70
    /**
71
     * Get properties of an order object by ref
72
     *
73
     * Return an array with order informations
74
     *
75
     * @param       string		$ref			Ref of object
76
     * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
77
     * @return 	array|mixed data without useless information
78
     *
79
     * @url GET    byRef/{ref}
80
     *
81
     * @throws 	RestException
82
     */
83
    public function getByRef($ref, $contact_list = 1)
84
    {
85
        return $this->_fetch('', $ref, '', '', $contact_list);
86
    }
87
88
    /**
89
     * Get properties of an order object by ref_ext
90
     *
91
     * Return an array with order informations
92
     *
93
     * @param       string		$ref_ext			External reference of object
94
     * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
95
     * @return 	array|mixed data without useless information
96
     *
97
     * @url GET    byRefExt/{ref_ext}
98
     *
99
     * @throws 	RestException
100
     */
101
    public function getByRefExt($ref_ext, $contact_list = 1)
102
    {
103
        return $this->_fetch('', '', $ref_ext, '', $contact_list);
104
    }
105
106
    /**
107
     * Get properties of an order object
108
     *
109
     * Return an array with order informations
110
     *
111
     * @param       int         $id            ID of order
112
	 * @param		string		$ref			Ref of object
113
	 * @param		string		$ref_ext		External reference of object
114
	 * @param		string		$ref_int		Internal reference of other objec
115
     * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
116
     * @return 	array|mixed data without useless information
117
     *
118
     * @throws 	RestException
119
     */
120
    private function _fetch($id, $ref = '', $ref_ext = '', $ref_int = '', $contact_list = 1)
121
    {
122
        if(! DolibarrApiAccess::$user->rights->commande->lire) {
123
            throw new RestException(401);
124
        }
125
126
        $result = $this->commande->fetch($id, $ref, $ref_ext, $ref_int);
127
        if( ! $result ) {
128
            throw new RestException(404, 'Order not found');
129
        }
130
131
        if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
132
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
133
        }
134
135
        // Add external contacts ids
136
        $this->commande->contacts_ids = $this->commande->liste_contact(-1, 'external', $contact_list);
0 ignored issues
show
Bug introduced by
The property contacts_ids does not exist on Commande. Did you mean contact?
Loading history...
137
        $this->commande->fetchObjectLinked();
138
        return $this->_cleanObjectDatas($this->commande);
139
    }
140
141
    /**
142
     * List orders
143
     *
144
     * Get a list of orders
145
     *
146
     * @param string	       $sortfield	        Sort field
147
     * @param string	       $sortorder	        Sort order
148
     * @param int		       $limit		        Limit for list
149
     * @param int		       $page		        Page number
150
     * @param string   	       $thirdparty_ids	    Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
151
     * @param string           $sqlfilters          Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
152
     * @return  array                               Array of order objects
153
     *
154
     * @throws RestException
155
     */
156
    public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
157
    {
158
        global $db, $conf;
159
160
        $obj_ret = array();
161
162
        // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
163
        $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
164
165
        // If the internal user must only see his customers, force searching by him
166
        $search_sale = 0;
167
        if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
168
169
        $sql = "SELECT t.rowid";
170
        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $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)
171
        $sql.= " FROM ".MAIN_DB_PREFIX."commande as t";
172
173
        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
174
175
        $sql.= ' WHERE t.entity IN ('.getEntity('commande').')';
176
        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc";
177
        if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")";
178
        if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc";		// Join for the needed table to filter by sale
179
        // Insert sale filter
180
        if ($search_sale > 0)
181
        {
182
            $sql .= " AND sc.fk_user = ".$search_sale;
183
        }
184
        // Add sql filters
185
        if ($sqlfilters)
186
        {
187
            if (! DolibarrApi::_checkFilters($sqlfilters))
188
            {
189
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
190
            }
191
	        $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
192
            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
193
        }
194
195
        $sql.= $db->order($sortfield, $sortorder);
196
        if ($limit)	{
197
            if ($page < 0)
198
            {
199
                $page = 0;
200
            }
201
            $offset = $limit * $page;
202
203
            $sql.= $db->plimit($limit + 1, $offset);
204
        }
205
206
        dol_syslog("API Rest request");
207
        $result = $db->query($sql);
208
209
        if ($result)
210
        {
211
            $num = $db->num_rows($result);
212
            $min = min($num, ($limit <= 0 ? $num : $limit));
213
            $i=0;
214
            while ($i < $min)
215
            {
216
                $obj = $db->fetch_object($result);
217
                $commande_static = new Commande($db);
218
                if($commande_static->fetch($obj->rowid)) {
219
                    // Add external contacts ids
220
                    $commande_static->contacts_ids = $commande_static->liste_contact(-1, 'external', 1);
0 ignored issues
show
Bug introduced by
The property contacts_ids does not exist on Commande. Did you mean contact?
Loading history...
221
                    $obj_ret[] = $this->_cleanObjectDatas($commande_static);
222
                }
223
                $i++;
224
            }
225
        }
226
        else {
227
            throw new RestException(503, 'Error when retrieve commande list : '.$db->lasterror());
228
        }
229
        if( ! count($obj_ret)) {
230
            throw new RestException(404, 'No order found');
231
        }
232
		return $obj_ret;
233
    }
234
235
    /**
236
     * Create order object
237
     *
238
     * @param   array   $request_data   Request data
239
     * @return  int     ID of order
240
     */
241
    public function post($request_data = null)
242
    {
243
        if(! DolibarrApiAccess::$user->rights->commande->creer) {
244
			throw new RestException(401, "Insuffisant rights");
245
        }
246
        // Check mandatory fields
247
        $result = $this->_validate($request_data);
248
249
        foreach($request_data as $field => $value) {
250
            $this->commande->$field = $value;
251
        }
252
        /*if (isset($request_data["lines"])) {
253
          $lines = array();
254
          foreach ($request_data["lines"] as $line) {
255
            array_push($lines, (object) $line);
256
          }
257
          $this->commande->lines = $lines;
258
        }*/
259
260
        if ($this->commande->create(DolibarrApiAccess::$user) < 0) {
261
            throw new RestException(500, "Error creating order", array_merge(array($this->commande->error), $this->commande->errors));
262
        }
263
264
        return $this->commande->id;
265
    }
266
267
    /**
268
     * Get lines of an order
269
     *
270
     * @param int   $id             Id of order
271
     *
272
     * @url	GET {id}/lines
273
     *
274
     * @return int
275
     */
276
    public function getLines($id)
277
    {
278
        if(! DolibarrApiAccess::$user->rights->commande->lire) {
279
			throw new RestException(401);
280
		}
281
282
        $result = $this->commande->fetch($id);
283
        if( ! $result ) {
284
            throw new RestException(404, 'Order not found');
285
        }
286
287
		if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
288
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
289
        }
290
        $this->commande->getLinesArray();
291
        $result = array();
292
        foreach ($this->commande->lines as $line) {
293
            array_push($result, $this->_cleanObjectDatas($line));
294
        }
295
        return $result;
296
    }
297
298
    /**
299
     * Add a line to given order
300
     *
301
     * @param int   $id             Id of order to update
302
     * @param array $request_data   OrderLine data
303
     *
304
     * @url	POST {id}/lines
305
     *
306
     * @return int
307
     */
308
    public function postLine($id, $request_data = null)
309
    {
310
        if(! DolibarrApiAccess::$user->rights->commande->creer) {
311
			throw new RestException(401);
312
		}
313
314
        $result = $this->commande->fetch($id);
315
        if( ! $result ) {
316
            throw new RestException(404, 'Order not found');
317
        }
318
319
		if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
320
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
321
        }
322
		$request_data = (object) $request_data;
323
        $updateRes = $this->commande->addline(
324
                        $request_data->desc,
325
                        $request_data->subprice,
326
                        $request_data->qty,
327
                        $request_data->tva_tx,
328
                        $request_data->localtax1_tx,
329
                        $request_data->localtax2_tx,
330
                        $request_data->fk_product,
331
                        $request_data->remise_percent,
332
                        $request_data->info_bits,
333
                        $request_data->fk_remise_except,
334
                        'HT',
335
                        0,
336
                        $request_data->date_start,
337
                        $request_data->date_end,
338
                        $request_data->product_type,
339
                        $request_data->rang,
340
                        $request_data->special_code,
341
                        $request_data->fk_parent_line,
342
                        $request_data->fk_fournprice,
343
                        $request_data->pa_ht,
344
                        $request_data->label,
345
                        $request_data->array_options,
346
                        $request_data->fk_unit,
347
                        $request_data->origin,
348
                        $request_data->origin_id,
349
                        $request_data->multicurrency_subprice
350
        );
351
352
        if ($updateRes > 0) {
353
            return $updateRes;
354
        } else {
355
            throw new RestException(400, $this->commande->error);
356
        }
357
    }
358
359
    /**
360
     * Update a line to given order
361
     *
362
     * @param int   $id             Id of order to update
363
     * @param int   $lineid         Id of line to update
364
     * @param array $request_data   OrderLine data
365
     *
366
     * @url	PUT {id}/lines/{lineid}
367
     *
368
     * @return array|bool
369
     */
370
    public function putLine($id, $lineid, $request_data = null)
371
    {
372
        if(! DolibarrApiAccess::$user->rights->commande->creer) {
373
			throw new RestException(401);
374
		}
375
376
        $result = $this->commande->fetch($id);
377
        if( ! $result ) {
378
            throw new RestException(404, 'Order not found');
379
        }
380
381
		if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
382
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
383
        }
384
		$request_data = (object) $request_data;
385
        $updateRes = $this->commande->updateline(
386
            $lineid,
387
            $request_data->desc,
388
            $request_data->subprice,
389
            $request_data->qty,
390
            $request_data->remise_percent,
391
            $request_data->tva_tx,
392
            $request_data->localtax1_tx,
393
            $request_data->localtax2_tx,
394
            'HT',
395
            $request_data->info_bits,
396
            $request_data->date_start,
397
            $request_data->date_end,
398
            $request_data->product_type,
399
            $request_data->fk_parent_line,
400
            0,
401
            $request_data->fk_fournprice,
402
            $request_data->pa_ht,
403
            $request_data->label,
404
            $request_data->special_code,
405
            $request_data->array_options,
406
            $request_data->fk_unit,
407
      		$request_data->multicurrency_subprice
408
        );
409
410
        if ($updateRes > 0) {
411
            $result = $this->get($id);
412
            unset($result->line);
413
            return $this->_cleanObjectDatas($result);
414
        }
415
        return false;
416
    }
417
418
    /**
419
     * Delete a line to given order
420
     *
421
     *
422
     * @param int   $id             Id of order to update
423
     * @param int   $lineid         Id of line to delete
424
     *
425
     * @url	DELETE {id}/lines/{lineid}
426
     *
427
     * @return int
428
     * @throws 401
429
     * @throws 404
430
     */
431
    public function deleteLine($id, $lineid)
432
    {
433
        if(! DolibarrApiAccess::$user->rights->commande->creer) {
434
			throw new RestException(401);
435
		}
436
437
        $result = $this->commande->fetch($id);
438
        if( ! $result ) {
439
            throw new RestException(404, 'Order not found');
440
        }
441
442
		if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
443
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
444
        }
445
446
        // TODO Check the lineid $lineid is a line of ojbect
447
448
        $updateRes = $this->commande->deleteline(DolibarrApiAccess::$user, $lineid);
449
        if ($updateRes > 0) {
450
            return $this->get($id);
451
        } else {
452
            throw new RestException(405, $this->commande->error);
453
        }
454
    }
455
456
    /**
457
	 * Add a contact type of given order
458
	 *
459
	 * @param int    $id             Id of order to update
460
	 * @param int    $contactid      Id of contact to add
461
	 * @param string $type           Type of the contact (BILLING, SHIPPING, CUSTOMER)
462
	 *
463
	 * @url	POST {id}/contact/{contactid}/{type}
464
	 *
465
	 * @return int
466
     * @throws 401
467
     * @throws 404
468
	 */
469
    public function postContact($id, $contactid, $type)
470
    {
471
        if (! DolibarrApiAccess::$user->rights->commande->creer) {
472
			throw new RestException(401);
473
		}
474
475
        $result = $this->commande->fetch($id);
476
        if (! $result) {
477
            throw new RestException(404, 'Order not found');
478
        }
479
480
		if (! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
481
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
482
		}
483
484
        $result = $this->commande->add_contact($contactid, $type, 'external');
485
486
        if (!$result) {
487
            throw new RestException(500, 'Error when added the contact');
488
        }
489
490
        return $this->commande;
491
    }
492
493
    /**
494
	 * Delete a contact type of given order
495
	 *
496
	 * @param int    $id             Id of order to update
497
	 * @param int    $rowid          Row key of the contact in the array contact_ids.
498
	 *
499
	 * @url	DELETE {id}/contact/{rowid}
500
	 *
501
	 * @return int
502
     * @throws 401
503
     * @throws 404
504
     * @throws 500
505
	 */
506
    public function deleteContact($id, $rowid)
507
    {
508
        if (! DolibarrApiAccess::$user->rights->commande->creer) {
509
			throw new RestException(401);
510
		}
511
512
        $result = $this->commande->fetch($id);
513
        if (! $result) {
514
            throw new RestException(404, 'Order not found');
515
        }
516
517
		if (! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
518
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
519
		}
520
521
        $result = $this->commande->delete_contact($rowid);
522
523
        if (!$result) {
524
            throw new RestException(500, 'Error when deleted the contact');
525
        }
526
527
        return $this->commande;
528
    }
529
530
    /**
531
     * Update order general fields (won't touch lines of order)
532
     *
533
     * @param int   $id             Id of order to update
534
     * @param array $request_data   Datas
535
     *
536
     * @return int
537
     */
538
    public function put($id, $request_data = null)
539
    {
540
        if (! DolibarrApiAccess::$user->rights->commande->creer) {
541
			throw new RestException(401);
542
		}
543
544
        $result = $this->commande->fetch($id);
545
        if (! $result) {
546
            throw new RestException(404, 'Order not found');
547
        }
548
549
		if (! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
550
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
551
		}
552
        foreach($request_data as $field => $value) {
553
            if ($field == 'id') continue;
554
            $this->commande->$field = $value;
555
        }
556
557
		// Update availability
558
		if (!empty($this->commande->availability_id)) {
559
		    if ($this->commande->availability($this->commande->availability_id) < 0)
560
			throw new RestException(400, 'Error while updating availability');
561
		}
562
563
        if ($this->commande->update(DolibarrApiAccess::$user) > 0)
564
        {
565
            return $this->get($id);
566
        }
567
        else
568
        {
569
        	throw new RestException(500, $this->commande->error);
570
        }
571
    }
572
573
    /**
574
     * Delete order
575
     *
576
     * @param   int     $id         Order ID
577
     * @return  array
578
     */
579
    public function delete($id)
580
    {
581
        if(! DolibarrApiAccess::$user->rights->commande->supprimer) {
582
			throw new RestException(401);
583
		}
584
        $result = $this->commande->fetch($id);
585
        if( ! $result ) {
586
            throw new RestException(404, 'Order not found');
587
        }
588
589
		if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
590
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
591
		}
592
593
        if( ! $this->commande->delete(DolibarrApiAccess::$user)) {
594
            throw new RestException(500, 'Error when deleting order : '.$this->commande->error);
595
        }
596
597
        return array(
598
            'success' => array(
599
                'code' => 200,
600
                'message' => 'Order deleted'
601
            )
602
        );
603
    }
604
605
    /**
606
     * Validate an order
607
     *
608
	 * If you get a bad value for param notrigger check, provide this in body
609
     * {
610
     *   "idwarehouse": 0,
611
     *   "notrigger": 0
612
     * }
613
     *
614
     * @param   int $id             Order ID
615
     * @param   int $idwarehouse    Warehouse ID
616
     * @param   int $notrigger      1=Does not execute triggers, 0= execute triggers
617
     *
618
     * @url POST    {id}/validate
619
     *
620
	 * @throws 304
621
     * @throws 401
622
     * @throws 404
623
     * @throws 500
624
     *
625
     * @return  array
626
     */
627
    public function validate($id, $idwarehouse = 0, $notrigger = 0)
628
    {
629
        if(! DolibarrApiAccess::$user->rights->commande->creer) {
630
			throw new RestException(401);
631
		}
632
        $result = $this->commande->fetch($id);
633
        if( ! $result ) {
634
            throw new RestException(404, 'Order not found');
635
        }
636
637
		if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
638
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
639
		}
640
641
		$result = $this->commande->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
642
		if ($result == 0) {
643
		    throw new RestException(304, 'Error nothing done. May be object is already validated');
644
		}
645
		if ($result < 0) {
646
		    throw new RestException(500, 'Error when validating Order: '.$this->commande->error);
647
		}
648
        $result = $this->commande->fetch($id);
649
        if( ! $result ) {
650
            throw new RestException(404, 'Order not found');
651
        }
652
653
        if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
654
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
655
        }
656
657
        $this->commande->fetchObjectLinked();
658
659
        return $this->_cleanObjectDatas($this->commande);
660
    }
661
662
    /**
663
     *  Tag the order as validated (opened)
664
     *
665
     *  Function used when order is reopend after being closed.
666
     *
667
     * @param int   $id       Id of the order
668
     *
669
     * @url     POST {id}/reopen
670
     *
671
     * @return int
672
     *
673
     * @throws 304
674
     * @throws 400
675
     * @throws 401
676
     * @throws 404
677
     * @throws 405
678
     */
679
    public function reopen($id)
680
    {
681
682
        if(! DolibarrApiAccess::$user->rights->commande->creer) {
683
            throw new RestException(401);
684
        }
685
        if(empty($id)) {
686
            throw new RestException(400, 'Order ID is mandatory');
687
        }
688
        $result = $this->commande->fetch($id);
689
        if( ! $result ) {
690
            throw new RestException(404, 'Order not found');
691
        }
692
693
        $result = $this->commande->set_reopen(DolibarrApiAccess::$user);
694
        if( $result < 0) {
695
            throw new RestException(405, $this->commande->error);
696
        }elseif( $result == 0) {
697
            throw new RestException(304);
698
        }
699
700
        return $result;
701
    }
702
703
    /**
704
     * Classify the order as invoiced. Could be also called setbilled
705
     *
706
     * @param int   $id           Id of the order
707
     *
708
     * @url     POST {id}/setinvoiced
709
     *
710
     * @return int
711
     *
712
     * @throws 400
713
     * @throws 401
714
     * @throws 404
715
     * @throws 405
716
     */
717
    public function setinvoiced($id)
718
    {
719
720
        if(! DolibarrApiAccess::$user->rights->commande->creer) {
721
            throw new RestException(401);
722
        }
723
        if(empty($id)) {
724
            throw new RestException(400, 'Order ID is mandatory');
725
        }
726
        $result = $this->commande->fetch($id);
727
        if( ! $result ) {
728
            throw new RestException(404, 'Order not found');
729
        }
730
731
        $result = $this->commande->classifyBilled(DolibarrApiAccess::$user);
732
        if( $result < 0) {
733
            throw new RestException(400, $this->commande->error);
734
        }
735
736
        $result = $this->commande->fetch($id);
737
        if( ! $result ) {
738
        	throw new RestException(404, 'Order not found');
739
        }
740
741
        if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
742
        	throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
743
        }
744
745
        $this->commande->fetchObjectLinked();
746
747
        return $this->_cleanObjectDatas($this->commande);
748
    }
749
750
    /**
751
     * Close an order (Classify it as "Delivered")
752
     *
753
     * @param   int     $id             Order ID
754
     * @param   int     $notrigger      Disabled triggers
755
     *
756
     * @url POST    {id}/close
757
     *
758
     * @return  int
759
     */
760
    public function close($id, $notrigger = 0)
761
    {
762
    	if(! DolibarrApiAccess::$user->rights->commande->creer) {
763
    		throw new RestException(401);
764
    	}
765
    	$result = $this->commande->fetch($id);
766
    	if( ! $result ) {
767
    		throw new RestException(404, 'Order not found');
768
    	}
769
770
    	if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
771
    		throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
772
    	}
773
774
    	$result = $this->commande->cloture(DolibarrApiAccess::$user, $notrigger);
775
    	if ($result == 0) {
776
    		throw new RestException(304, 'Error nothing done. May be object is already closed');
777
    	}
778
    	if ($result < 0) {
779
    		throw new RestException(500, 'Error when closing Order: '.$this->commande->error);
780
    	}
781
782
    	$result = $this->commande->fetch($id);
783
    	if( ! $result ) {
784
    		throw new RestException(404, 'Order not found');
785
    	}
786
787
    	if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
788
    		throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
789
    	}
790
791
    	$this->commande->fetchObjectLinked();
792
793
    	return $this->_cleanObjectDatas($this->commande);
794
    }
795
796
    /**
797
     * Set an order to draft
798
     *
799
     * @param   int     $id             Order ID
800
     * @param   int 	$idwarehouse    Warehouse ID to use for stock change (Used only if option STOCK_CALCULATE_ON_VALIDATE_ORDER is on)
801
     *
802
     * @url POST    {id}/settodraft
803
     *
804
     * @return  array
805
     */
806
    public function settodraft($id, $idwarehouse = -1)
807
    {
808
        if(! DolibarrApiAccess::$user->rights->commande->creer) {
809
            throw new RestException(401);
810
        }
811
        $result = $this->commande->fetch($id);
812
        if( ! $result ) {
813
            throw new RestException(404, 'Order not found');
814
        }
815
816
        if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
817
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
818
        }
819
820
        $result = $this->commande->setDraft(DolibarrApiAccess::$user, $idwarehouse);
821
        if ($result == 0) {
822
            throw new RestException(304, 'Nothing done. May be object is already closed');
823
        }
824
        if ($result < 0) {
825
            throw new RestException(500, 'Error when closing Order: '.$this->commande->error);
826
        }
827
828
		$result = $this->commande->fetch($id);
829
        if( ! $result ) {
830
            throw new RestException(404, 'Order not found');
831
        }
832
833
        if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
834
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
835
        }
836
837
        $this->commande->fetchObjectLinked();
838
839
        return $this->_cleanObjectDatas($this->commande);
840
    }
841
842
843
    /**
844
     * Create an order using an existing proposal.
845
     *
846
     *
847
     * @param int   $proposalid       Id of the proposal
848
     *
849
     * @url     POST /createfromproposal/{proposalid}
850
     *
851
     * @return int
852
     * @throws 400
853
     * @throws 401
854
     * @throws 404
855
     * @throws 405
856
     */
857
    public function createOrderFromProposal($proposalid)
858
    {
859
860
        require_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php';
861
862
        if(! DolibarrApiAccess::$user->rights->propal->lire) {
863
            throw new RestException(401);
864
        }
865
        if(! DolibarrApiAccess::$user->rights->commande->creer) {
866
            throw new RestException(401);
867
        }
868
        if(empty($proposalid)) {
869
            throw new RestException(400, 'Proposal ID is mandatory');
870
        }
871
872
        $propal = new Propal($this->db);
873
        $result = $propal->fetch($proposalid);
874
        if( ! $result ) {
875
            throw new RestException(404, 'Proposal not found');
876
        }
877
878
        $result = $this->commande->createFromProposal($propal, DolibarrApiAccess::$user);
879
        if( $result < 0) {
880
            throw new RestException(405, $this->commande->error);
881
        }
882
        $this->commande->fetchObjectLinked();
883
884
        return $this->_cleanObjectDatas($this->commande);
885
    }
886
887
888
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
889
    /**
890
     * Clean sensible object datas
891
     *
892
     * @param   object  $object    Object to clean
893
     * @return    array    Array of cleaned object properties
894
     */
895
    protected function _cleanObjectDatas($object)
896
    {
897
        // phpcs:enable
898
        $object = parent::_cleanObjectDatas($object);
899
900
        unset($object->note);
901
        unset($object->address);
902
        unset($object->barcode_type);
903
        unset($object->barcode_type_code);
904
        unset($object->barcode_type_label);
905
        unset($object->barcode_type_coder);
906
907
        return $object;
908
    }
909
910
    /**
911
     * Validate fields before create or update object
912
     *
913
     * @param   array           $data   Array with data to verify
914
     * @return  array
915
     * @throws  RestException
916
     */
917
    private function _validate($data)
918
    {
919
        $commande = array();
920
        foreach (Orders::$FIELDS as $field) {
921
            if (!isset($data[$field]))
922
                throw new RestException(400, $field ." field missing");
923
            $commande[$field] = $data[$field];
924
        }
925
        return $commande;
926
    }
927
}
928