Passed
Branch develop (2b65df)
by
unknown
40:00
created

Proposals::_fetch()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 4
nop 5
dl 0
loc 19
rs 9.9332
1
<?php
2
/* Copyright (C) 2015   Jean-François Ferry     <[email protected]>
3
 * Copyright (C) 2016   Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2020   Thibault FOUCART   		<[email protected]>
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
use Luracast\Restler\RestException;
21
22
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
23
24
25
/**
26
 * API class for orders
27
 *
28
 * @access protected
29
 * @class  DolibarrApiAccess {@requires user,external}
30
 */
31
class Proposals extends DolibarrApi
32
{
33
    /**
34
	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
35
	 */
36
	static $FIELDS = array(
37
		'socid'
38
	);
39
40
	/**
41
	 * @var Propal $propal {@type Propal}
42
	 */
43
	public $propal;
44
45
	/**
46
	 * Constructor
47
	 */
48
	public function __construct()
49
	{
50
		global $db, $conf;
51
		$this->db = $db;
52
		$this->propal = new Propal($this->db);
53
	}
54
55
	/**
56
	 * Get properties of a commercial proposal object
57
	 *
58
	 * Return an array with commercial proposal informations
59
	 *
60
	 * @param       int         $id           ID of commercial proposal
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 proposal object by ref
73
     *
74
     * Return an array with proposal 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 proposal object by ref_ext
91
     *
92
     * Return an array with proposal 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 proposal object
109
     *
110
     * Return an array with proposal 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		string		$ref_int		Internal reference of other objec
116
     * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
117
     * @return 	array|mixed data without useless information
118
     *
119
     * @throws 	RestException
120
     */
121
    private function _fetch($id, $ref = '', $ref_ext = '', $ref_int = '', $contact_list = 1)
122
    {
123
		if(! DolibarrApiAccess::$user->rights->propal->lire) {
124
			throw new RestException(401);
125
		}
126
127
		$result = $this->propal->fetch($id, $ref, $ref_ext, $ref_int);
0 ignored issues
show
Unused Code introduced by
The call to Propal::fetch() has too many arguments starting with $ref_ext. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

127
		/** @scrutinizer ignore-call */ 
128
  $result = $this->propal->fetch($id, $ref, $ref_ext, $ref_int);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
128
		if( ! $result ) {
129
			throw new RestException(404, 'Commercial Proposal not found');
130
		}
131
132
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
133
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
134
		}
135
136
		// Add external contacts ids.
137
		$this->propal->contacts_ids = $this->propal->liste_contact(-1, 'external', $contact_list);
0 ignored issues
show
Bug introduced by
The property contacts_ids does not exist on Propal. Did you mean contact?
Loading history...
138
		$this->propal->fetchObjectLinked();
139
		return $this->_cleanObjectDatas($this->propal);
140
	}
141
142
	/**
143
	 * List commercial proposals
144
	 *
145
	 * Get a list of commercial proposals
146
	 *
147
	 * @param string	$sortfield	        Sort field
148
	 * @param string	$sortorder	        Sort order
149
	 * @param int		$limit		        Limit for list
150
	 * @param int		$page		        Page number
151
	 * @param string   	$thirdparty_ids	    Thirdparty ids to filter commercial proposals (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
152
	 * @param string    $sqlfilters         Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')"
153
	 * @return  array                       Array of order objects
154
	 */
155
    public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
156
    {
157
		global $db, $conf;
158
159
		$obj_ret = array();
160
161
		// case of external user, $thirdparty_ids param is ignored and replaced by user's socid
162
		$socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
163
164
		// If the internal user must only see his customers, force searching by him
165
		$search_sale = 0;
166
		if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
167
168
		$sql = "SELECT t.rowid";
169
		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)
170
		$sql.= " FROM ".MAIN_DB_PREFIX."propal as t";
171
172
		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
173
174
		$sql.= ' WHERE t.entity IN ('.getEntity('propal').')';
175
		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc";
176
		if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")";
177
		if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc";		// Join for the needed table to filter by sale
178
		// Insert sale filter
179
		if ($search_sale > 0)
180
		{
181
			$sql .= " AND sc.fk_user = ".$search_sale;
182
		}
183
		// Add sql filters
184
		if ($sqlfilters)
185
		{
186
			if (! DolibarrApi::_checkFilters($sqlfilters))
187
			{
188
				throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
189
			}
190
			$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
191
			$sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
192
		}
193
194
		$sql.= $db->order($sortfield, $sortorder);
195
		if ($limit)	{
196
			if ($page < 0)
197
			{
198
				$page = 0;
199
			}
200
			$offset = $limit * $page;
201
202
			$sql.= $db->plimit($limit + 1, $offset);
203
		}
204
205
        dol_syslog("API Rest request");
206
		$result = $db->query($sql);
207
208
		if ($result)
209
		{
210
			$num = $db->num_rows($result);
211
			$min = min($num, ($limit <= 0 ? $num : $limit));
212
			$i = 0;
213
			while ($i < $min)
214
			{
215
				$obj = $db->fetch_object($result);
216
				$proposal_static = new Propal($db);
217
				if($proposal_static->fetch($obj->rowid)) {
218
					// Add external contacts ids
219
					$proposal_static->contacts_ids = $proposal_static->liste_contact(-1, 'external', 1);
0 ignored issues
show
Bug introduced by
The property contacts_ids does not exist on Propal. Did you mean contact?
Loading history...
220
					$obj_ret[] = $this->_cleanObjectDatas($proposal_static);
221
				}
222
				$i++;
223
			}
224
		}
225
		else {
226
			throw new RestException(503, 'Error when retrieve propal list : '.$db->lasterror());
227
		}
228
		if( ! count($obj_ret)) {
229
			throw new RestException(404, 'No proposal found');
230
		}
231
		return $obj_ret;
232
	}
233
234
	/**
235
	 * Create commercial proposal object
236
	 *
237
	 * @param   array   $request_data   Request data
238
	 * @return  int     ID of proposal
239
	 */
240
    public function post($request_data = null)
241
    {
242
        if(! DolibarrApiAccess::$user->rights->propal->creer) {
243
            throw new RestException(401, "Insuffisant rights");
244
        }
245
        // Check mandatory fields
246
        $result = $this->_validate($request_data);
247
248
		foreach($request_data as $field => $value) {
249
			$this->propal->$field = $value;
250
		}
251
		/*if (isset($request_data["lines"])) {
252
          $lines = array();
253
          foreach ($request_data["lines"] as $line) {
254
            array_push($lines, (object) $line);
255
          }
256
          $this->propal->lines = $lines;
257
        }*/
258
		if ($this->propal->create(DolibarrApiAccess::$user) < 0) {
259
			throw new RestException(500, "Error creating order", array_merge(array($this->propal->error), $this->propal->errors));
260
		}
261
262
		return $this->propal->id;
263
    }
264
265
	/**
266
	 * Get lines of a commercial proposal
267
	 *
268
	 * @param int   $id             Id of commercial proposal
269
	 *
270
	 * @url	GET {id}/lines
271
	 *
272
	 * @return int
273
	 */
274
    public function getLines($id)
275
    {
276
        if(! DolibarrApiAccess::$user->rights->propal->lire) {
277
            throw new RestException(401);
278
        }
279
280
	    $result = $this->propal->fetch($id);
281
	    if( ! $result ) {
282
		    throw new RestException(404, 'Commercial Proposal not found');
283
	    }
284
285
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
286
		    throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
287
	    }
288
	    $this->propal->getLinesArray();
289
	    $result = array();
290
	    foreach ($this->propal->lines as $line) {
291
		    array_push($result, $this->_cleanObjectDatas($line));
292
	    }
293
	    return $result;
294
	}
295
296
	/**
297
	 * Add a line to given commercial proposal
298
	 *
299
	 * @param int   $id             Id of commercial proposal to update
300
	 * @param array $request_data   Commercial proposal line data
301
	 *
302
	 * @url	POST {id}/lines
303
	 *
304
	 * @return int
305
	 */
306
	public function postLine($id, $request_data = null)
307
	{
308
		if (! DolibarrApiAccess::$user->rights->propal->creer) {
309
		  	throw new RestException(401);
310
		}
311
312
		$result = $this->propal->fetch($id);
313
		if (! $result) {
314
		    throw new RestException(404, 'Commercial Proposal not found');
315
		}
316
317
		if (! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
318
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
319
		}
320
321
        $request_data = (object) $request_data;
322
323
        $updateRes = $this->propal->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
                        'HT',
333
                        0,
334
                        $request_data->info_bits,
335
                        $request_data->product_type,
336
                        $request_data->rang,
337
                        $request_data->special_code,
338
      					$request_data->fk_parent_line,
339
                        $request_data->fk_fournprice,
340
                        $request_data->pa_ht,
341
                        $request_data->label,
342
                        $request_data->date_start,
343
                        $request_data->date_end,
344
                        $request_data->array_options,
345
                        $request_data->fk_unit,
346
                        $request_data->origin,
347
                        $request_data->origin_id,
348
                        $request_data->multicurrency_subprice,
349
                        $request_data->fk_remise_except
350
        );
351
352
        if ($updateRes > 0) {
353
            return $updateRes;
354
        } else {
355
            throw new RestException(400, $this->propal->error);
356
        }
357
    }
358
359
	/**
360
	 * Update a line of given commercial proposal
361
	 *
362
	 * @param int   $id             Id of commercial proposal to update
363
	 * @param int   $lineid         Id of line to update
364
	 * @param array $request_data   Commercial proposal line data
365
	 *
366
	 * @url	PUT {id}/lines/{lineid}
367
	 *
368
	 * @return object
369
	 */
370
	public function putLine($id, $lineid, $request_data = null)
371
	{
372
		if(! DolibarrApiAccess::$user->rights->propal->creer) {
373
			throw new RestException(401);
374
		}
375
376
		$result = $this->propal->fetch($id);
377
		if($result <= 0) {
378
			throw new RestException(404, 'Proposal not found');
379
		}
380
381
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
382
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
383
	  	}
384
385
	  	$request_data = (object) $request_data;
386
387
	  	$propalline = new PropaleLigne($this->db);
388
	  	$result = $propalline->fetch($lineid);
389
	  	if ($result <= 0) {
390
	  		throw new RestException(404, 'Proposal line not found');
391
	  	}
392
393
        $updateRes = $this->propal->updateline(
394
            $lineid,
395
            isset($request_data->subprice)?$request_data->subprice:$propalline->subprice,
396
            isset($request_data->qty)?$request_data->qty:$propalline->qty,
397
            isset($request_data->remise_percent)?$request_data->remise_percent:$propalline->remise_percent,
398
            isset($request_data->tva_tx)?$request_data->tva_tx:$propalline->tva_tx,
399
            isset($request_data->localtax1_tx)?$request_data->localtax1_tx:$propalline->localtax1_tx,
400
            isset($request_data->localtax2_tx)?$request_data->localtax2_tx:$propalline->localtax2_tx,
401
            isset($request_data->desc)?$request_data->desc:$propalline->desc,
402
            'HT',
403
            isset($request_data->info_bits)?$request_data->info_bits:$propalline->info_bits,
404
            isset($request_data->special_code)?$request_data->special_code:$propalline->special_code,
405
            isset($request_data->fk_parent_line)?$request_data->fk_parent_line:$propalline->fk_parent_line,
406
            0,
407
            isset($request_data->fk_fournprice)?$request_data->fk_fournprice:$propalline->fk_fournprice,
408
            isset($request_data->pa_ht)?$request_data->pa_ht:$propalline->pa_ht,
409
            isset($request_data->label)?$request_data->label:$propalline->label,
410
            isset($request_data->product_type)?$request_data->product_type:$propalline->product_type,
411
            isset($request_data->date_start)?$request_data->date_start:$propalline->date_start,
412
            isset($request_data->date_end)?$request_data->date_end:$propalline->date_end,
413
            isset($request_data->array_options)?$request_data->array_options:$propalline->array_options,
414
            isset($request_data->fk_unit)?$request_data->fk_unit:$propalline->fk_unit,
415
            isset($request_data->multicurrency_subprice)?$request_data->multicurrency_subprice:$propalline->subprice
416
        );
417
418
	    if ($updateRes > 0) {
419
		    $result = $this->get($id);
420
		    unset($result->line);
421
		    return $this->_cleanObjectDatas($result);
422
	    }
423
	    return false;
424
	}
425
426
	/**
427
	 * Delete a line of given commercial proposal
428
	 *
429
	 *
430
	 * @param int   $id             Id of commercial proposal to update
431
	 * @param int   $lineid         Id of line to delete
432
	 *
433
	 * @url	DELETE {id}/lines/{lineid}
434
	 *
435
	 * @return int
436
	 *
437
     * @throws RestException 401
438
     * @throws RestException 404
439
	 */
440
    public function deleteLine($id, $lineid)
441
    {
442
		if(! DolibarrApiAccess::$user->rights->propal->creer) {
443
            throw new RestException(401);
444
		}
445
446
		$result = $this->propal->fetch($id);
447
		if( ! $result ) {
448
			throw new RestException(404, 'Proposal not found');
449
		}
450
451
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
452
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
453
		}
454
455
		// TODO Check the lineid $lineid is a line of ojbect
456
457
		$updateRes = $this->propal->deleteline($lineid);
458
		if ($updateRes > 0) {
459
			return $this->get($id);
460
		}
461
		else
462
		{
463
			throw new RestException(405, $this->propal->error);
464
		}
465
	}
466
467
    /**
468
	 * Add a contact type of given commercial proposal
469
	 *
470
	 * @param int    $id             Id of commercial proposal to update
471
	 * @param int    $contactid      Id of contact to add
472
	 * @param string $type           Type of the contact (BILLING, SHIPPING, CUSTOMER)
473
	 *
474
	 * @url	POST {id}/contact/{contactid}/{type}
475
	 *
476
	 * @return int
477
	 *
478
     * @throws RestException 401
479
     * @throws RestException 404
480
	 */
481
    public function postContact($id, $contactid, $type)
482
    {
483
        if(!DolibarrApiAccess::$user->rights->propal->creer) {
484
            throw new RestException(401);
485
        }
486
487
        $result = $this->propal->fetch($id);
488
489
		if(!$result) {
490
			throw new RestException(404, 'Proposal not found');
491
		}
492
493
        if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) {
494
            throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER');
495
        }
496
497
        if(!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
498
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
499
		}
500
501
        $result = $this->propal->add_contact($contactid, $type, 'external');
502
503
        if (!$result) {
504
            throw new RestException(500, 'Error when added the contact');
505
        }
506
507
        return $this->propal;
508
    }
509
510
     /**
511
	 * Delete a contact type of given commercial proposal
512
	 *
513
	 * @param int    $id             Id of commercial proposal to update
514
	 * @param int    $rowid          Row key of the contact in the array contact_ids.
515
	 *
516
	 * @url	DELETE {id}/contact/{rowid}
517
	 *
518
	 * @return int
519
	 *
520
     * @throws RestException 401
521
     * @throws RestException 404
522
     * @throws RestException 500
523
	 */
524
    public function deleteContact($id, $rowid)
525
    {
526
        if(!DolibarrApiAccess::$user->rights->propal->creer) {
527
            throw new RestException(401);
528
        }
529
530
        $result = $this->propal->fetch($id);
531
532
		if(!$result) {
533
			throw new RestException(404, 'Proposal not found');
534
		}
535
536
        if(!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
537
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
538
		}
539
540
        $result = $this->propal->delete_contact($rowid);
541
542
        if (!$result) {
543
            throw new RestException(500, 'Error when deleted the contact');
544
        }
545
546
        return $this->propal;
547
    }
548
549
	/**
550
	 * Update commercial proposal general fields (won't touch lines of commercial proposal)
551
	 *
552
	 * @param int   $id             Id of commercial proposal to update
553
	 * @param array $request_data   Datas
554
	 *
555
	 * @return int
556
     */
557
    public function put($id, $request_data = null)
558
    {
559
        if (! DolibarrApiAccess::$user->rights->propal->creer) {
560
            throw new RestException(401);
561
        }
562
563
		$result = $this->propal->fetch($id);
564
		if ( ! $result ) {
565
			throw new RestException(404, 'Proposal not found');
566
		}
567
568
		if ( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
569
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
570
		}
571
		foreach ($request_data as $field => $value) {
572
			if ($field == 'id') continue;
573
			$this->propal->$field = $value;
574
		}
575
576
		// update end of validity date
577
		if (empty($this->propal->fin_validite) && !empty($this->propal->duree_validite) && !empty($this->propal->date_creation))
578
		{
579
			$this->propal->fin_validite = $this->propal->date_creation + ($this->propal->duree_validite * 24 * 3600);
580
		}
581
		if (!empty($this->propal->fin_validite))
582
		{
583
			if($this->propal->set_echeance(DolibarrApiAccess::$user, $this->propal->fin_validite)<0)
584
			{
585
				throw new RestException(500, $this->propal->error);
586
			}
587
		}
588
589
		if ($this->propal->update(DolibarrApiAccess::$user) > 0)
590
		{
591
			return $this->get($id);
592
		}
593
		else
594
		{
595
			throw new RestException(500, $this->propal->error);
596
		}
597
	}
598
599
	/**
600
	 * Delete commercial proposal
601
	 *
602
	 * @param   int     $id         Commercial proposal ID
603
	 *
604
	 * @return  array
605
	 */
606
	public function delete($id)
607
	{
608
		if(! DolibarrApiAccess::$user->rights->propal->supprimer) {
609
			throw new RestException(401);
610
		}
611
		$result = $this->propal->fetch($id);
612
		if( ! $result ) {
613
			throw new RestException(404, 'Commercial Proposal not found');
614
		}
615
616
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
617
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
618
		}
619
620
		if( ! $this->propal->delete(DolibarrApiAccess::$user)) {
621
			throw new RestException(500, 'Error when delete Commercial Proposal : '.$this->propal->error);
622
		}
623
624
		return array(
625
			'success' => array(
626
				'code' => 200,
627
				'message' => 'Commercial Proposal deleted'
628
			)
629
		);
630
	}
631
632
	/**
633
	* Set a proposal to draft
634
	*
635
	* @param   int     $id             Order ID
636
	*
637
	* @url POST    {id}/settodraft
638
	*
639
	* @return  array
640
	*/
641
	public function settodraft($id)
642
	{
643
		if(! DolibarrApiAccess::$user->rights->propal->creer) {
644
			throw new RestException(401);
645
		}
646
		$result = $this->propal->fetch($id);
647
		if( ! $result ) {
648
			throw new RestException(404, 'Proposal not found');
649
		}
650
651
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
652
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
653
		}
654
655
		$result = $this->propal->setDraft(DolibarrApiAccess::$user);
656
		if ($result == 0) {
657
			throw new RestException(304, 'Nothing done. May be object is already draft');
658
		}
659
		if ($result < 0) {
660
			throw new RestException(500, 'Error : '.$this->propal->error);
661
		}
662
663
		$result = $this->propal->fetch($id);
664
		if( ! $result ) {
665
			throw new RestException(404, 'Proposal not found');
666
		}
667
668
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
669
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
670
		}
671
672
		$this->propal->fetchObjectLinked();
673
674
		return $this->_cleanObjectDatas($this->propal);
675
	}
676
677
678
	/**
679
	 * Validate a commercial proposal
680
	 *
681
	 * If you get a bad value for param notrigger check that ou provide this in body
682
	 * {
683
	 * "notrigger": 0
684
	 * }
685
	 *
686
	 * @param   int     $id             Commercial proposal ID
687
	 * @param   int     $notrigger      1=Does not execute triggers, 0= execute triggers
688
	 *
689
	 * @url POST    {id}/validate
690
	 *
691
	 * @throws RestException 304
692
     * @throws RestException 401
693
     * @throws RestException 404
694
     * @throws RestException 500
695
     *
696
     * @return array
697
     */
698
    public function validate($id, $notrigger = 0)
699
    {
700
		if(! DolibarrApiAccess::$user->rights->propal->creer) {
701
			throw new RestException(401);
702
		}
703
		$result = $this->propal->fetch($id);
704
		if( ! $result ) {
705
			throw new RestException(404, 'Commercial Proposal not found');
706
		}
707
708
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
709
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
710
		}
711
712
		$result = $this->propal->valid(DolibarrApiAccess::$user, $notrigger);
713
		if ($result == 0) {
714
			throw new RestException(304, 'Error nothing done. May be object is already validated');
715
		}
716
		if ($result < 0) {
717
			throw new RestException(500, 'Error when validating Commercial Proposal: '.$this->propal->error);
718
		}
719
720
        $result = $this->propal->fetch($id);
721
        if( ! $result ) {
722
            throw new RestException(404, 'Commercial Proposal not found');
723
        }
724
725
        if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
726
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
727
        }
728
729
        $this->propal->fetchObjectLinked();
730
731
        return $this->_cleanObjectDatas($this->propal);
732
    }
733
734
	/**
735
	 * Close (Accept or refuse) a quote / commercial proposal
736
	 *
737
	 * @param   int     $id             Commercial proposal ID
738
	 * @param   int	    $status			Must be 2 (accepted) or 3 (refused)				{@min 2}{@max 3}
739
	 * @param   string  $note_private   Add this mention at end of private note
740
	 * @param   int     $notrigger      Disabled triggers
741
	 *
742
	 * @url POST    {id}/close
743
	 *
744
	 * @return  array
745
	 */
746
	public function close($id, $status, $note_private = '', $notrigger = 0)
747
	{
748
		if(! DolibarrApiAccess::$user->rights->propal->creer) {
749
			throw new RestException(401);
750
		}
751
		$result = $this->propal->fetch($id);
752
		if( ! $result ) {
753
			throw new RestException(404, 'Commercial Proposal not found');
754
		}
755
756
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
757
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
758
		}
759
760
		$result = $this->propal->cloture(DolibarrApiAccess::$user, $status, $note_private, $notrigger);
761
		if ($result == 0) {
762
			throw new RestException(304, 'Error nothing done. May be object is already closed');
763
		}
764
		if ($result < 0) {
765
			throw new RestException(500, 'Error when closing Commercial Proposal: '.$this->propal->error);
766
		}
767
768
		$result = $this->propal->fetch($id);
769
		if( ! $result ) {
770
			throw new RestException(404, 'Proposal not found');
771
		}
772
773
		if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
774
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
775
		}
776
777
		$this->propal->fetchObjectLinked();
778
779
		return $this->_cleanObjectDatas($this->propal);
780
	}
781
782
    /**
783
     * Set a commercial proposal billed. Could be also called setbilled
784
     *
785
     * @param   int     $id             Commercial proposal ID
786
     *
787
     * @url POST    {id}/setinvoiced
788
     *
789
     * @return  array
790
     */
791
    public function setinvoiced($id)
792
    {
793
        if (! DolibarrApiAccess::$user->rights->propal->creer) {
794
            throw new RestException(401);
795
        }
796
        $result = $this->propal->fetch($id);
797
        if ( ! $result ) {
798
            throw new RestException(404, 'Commercial Proposal not found');
799
        }
800
801
        if ( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
802
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
803
        }
804
805
        $result = $this->propal->classifyBilled(DolibarrApiAccess::$user);
806
        if ($result < 0) {
807
            throw new RestException(500, 'Error : '.$this->propal->error);
808
        }
809
810
        $result = $this->propal->fetch($id);
811
        if ( ! $result ) {
812
            throw new RestException(404, 'Proposal not found');
813
        }
814
815
        if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
816
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
817
        }
818
819
        $this->propal->fetchObjectLinked();
820
821
        return $this->_cleanObjectDatas($this->propal);
822
    }
823
824
825
	/**
826
	 * Validate fields before create or update object
827
	 *
828
	 * @param   array           $data   Array with data to verify
829
	 * @return  array
830
	 * @throws  RestException
831
	 */
832
	private function _validate($data)
833
	{
834
		$propal = array();
835
		foreach (Proposals::$FIELDS as $field) {
836
			if (!isset($data[$field]))
837
				throw new RestException(400, "$field field missing");
838
			$propal[$field] = $data[$field];
839
		}
840
		return $propal;
841
	}
842
843
844
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
845
    /**
846
     * Clean sensible object datas
847
     *
848
     * @param   object  $object    Object to clean
849
     * @return    array    Array of cleaned object properties
850
     */
851
    protected function _cleanObjectDatas($object)
852
    {
853
        // phpcs:enable
854
        $object = parent::_cleanObjectDatas($object);
855
856
        unset($object->note);
857
        unset($object->name);
858
        unset($object->lastname);
859
        unset($object->firstname);
860
        unset($object->civility_id);
861
        unset($object->address);
862
863
        return $object;
864
    }
865
}
866