Passed
Branch develop (f6c1a1)
by
unknown
28:54
created

Orders::delete()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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