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

Thirdparties::_fetch()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 18
nc 5
nop 12
dl 0
loc 29
rs 9.3554
c 1
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* Copyright (C) 2015   Jean-François Ferry     <[email protected]>
3
 * Copyright (C) 2018   Pierre Chéné            <[email protected]>
4
 * Copyright (C) 2019   Cedric Ancelin          <[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
23
/**
24
 * API class for thirdparties
25
 *
26
 * @access protected
27
 * @class  DolibarrApiAccess {@requires user,external}
28
 *
29
 */
30
class Thirdparties extends DolibarrApi
31
{
32
	/**
33
	 *
34
	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
35
	 */
36
	static $FIELDS = array(
37
		'name'
38
	);
39
40
	/**
41
	 * @var Societe $company {@type Societe}
42
	 */
43
	public $company;
44
45
	/**
46
	 * Constructor
47
	 */
48
    public function __construct()
49
	{
50
		global $db, $conf;
51
		$this->db = $db;
52
53
		require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
54
		require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
55
		require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
56
		require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
57
58
		$this->company = new Societe($this->db);
59
60
		if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY)) {
61
			static::$FIELDS[] = 'email';
62
		}
63
	}
64
65
	/**
66
	 * Get properties of a thirdparty object
67
	 *
68
	 * Return an array with thirdparty informations
69
	 *
70
	 * @param 	int 	$id ID of thirdparty
71
	 * @return 	array|mixed data without useless information
72
	 *
73
	 * @throws 	RestException
74
	 */
75
  public function get($id)
76
	{
77
    return $this->_fetch($id);
78
  }
79
80
	/**
81
	 * Get properties of a thirdparty object by email.
82
	 *
83
	 * Return an array with thirdparty informations
84
	 *
85
	 * @param string    $email  Sort field
86
	 * @return array|mixed data without useless information
87
	 *
88
	 * @url     GET byEmail/{email}
89
	 *
90
	 * @throws RestException
91
	 */
92
	public function getByEmail($email)
93
	{
94
	    return $this->_fetch('', '', '', '', '', '', '', '', '', '', $email);
95
	}
96
97
	/**
98
	 * List thirdparties
99
	 *
100
	 * Get a list of thirdparties
101
	 *
102
	 * @param   string  $sortfield  Sort field
103
	 * @param   string  $sortorder  Sort order
104
	 * @param   int     $limit      Limit for list
105
	 * @param   int     $page       Page number
106
	 * @param   int     $mode       Set to 1 to show only customers
107
	 *                              Set to 2 to show only prospects
108
	 *                              Set to 3 to show only those are not customer neither prospect
109
	 *								Set to 4 to show only suppliers
110
	 * @param   string  $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.nom:like:'TheCompany%') and (t.date_creation:<:'20160101')"
111
	 * @return  array               Array of thirdparty objects
112
	 */
113
    public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $sqlfilters = '')
114
    {
115
		global $db, $conf;
116
117
		$obj_ret = array();
118
119
		// case of external user, we force socids
120
		$socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
121
122
		// If the internal user must only see his customers, force searching by him
123
		$search_sale = 0;
124
		if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
125
126
		$sql = "SELECT t.rowid";
127
		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)
128
		$sql.= " FROM ".MAIN_DB_PREFIX."societe as t";
129
130
		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
131
		$sql.= ", ".MAIN_DB_PREFIX."c_stcomm as st";
132
		$sql.= " WHERE t.fk_stcomm = st.id";
133
		if ($mode == 1) $sql.= " AND t.client IN (1, 3)";
134
		if ($mode == 2) $sql.= " AND t.client IN (2, 3)";
135
		if ($mode == 3) $sql.= " AND t.client IN (0)";
136
		if ($mode == 4) $sql.= " AND t.fournisseur IN (1)";
137
		$sql.= ' AND t.entity IN ('.getEntity('societe').')';
138
		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc";
139
		//if ($email != NULL) $sql.= " AND s.email = \"".$email."\"";
140
		if ($socid) $sql.= " AND t.rowid IN (".$socids.")";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $socid does not exist. Did you maybe mean $socids?
Loading history...
141
		if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc";		// Join for the needed table to filter by sale
142
		// Insert sale filter
143
		if ($search_sale > 0)
144
		{
145
			$sql .= " AND sc.fk_user = ".$search_sale;
146
		}
147
		// Add sql filters
148
		if ($sqlfilters)
149
		{
150
			if (! DolibarrApi::_checkFilters($sqlfilters))
151
			{
152
				throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
153
			}
154
			$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
155
			$sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
156
		}
157
158
		$sql.= $db->order($sortfield, $sortorder);
159
160
		if ($limit) {
161
			if ($page < 0)
162
			{
163
				$page = 0;
164
			}
165
			$offset = $limit * $page;
166
167
			$sql.= $db->plimit($limit + 1, $offset);
168
		}
169
170
		$result = $db->query($sql);
171
		if ($result)
172
		{
173
			$num = $db->num_rows($result);
174
			$min = min($num, ($limit <= 0 ? $num : $limit));
175
			while ($i < $min)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $i seems to be never defined.
Loading history...
176
			{
177
				$obj = $db->fetch_object($result);
178
				$soc_static = new Societe($db);
179
				if($soc_static->fetch($obj->rowid)) {
180
					$obj_ret[] = $this->_cleanObjectDatas($soc_static);
181
				}
182
				$i++;
183
			}
184
		}
185
		else {
186
			throw new RestException(503, 'Error when retrieve thirdparties : '.$db->lasterror());
187
		}
188
		if( ! count($obj_ret)) {
189
			throw new RestException(404, 'Thirdparties not found');
190
		}
191
		return $obj_ret;
192
	}
193
194
	/**
195
	 * Create thirdparty object
196
	 *
197
	 * @param array $request_data   Request datas
198
	 * @return int  ID of thirdparty
199
	 */
200
    public function post($request_data = null)
201
	{
202
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
203
			throw new RestException(401);
204
		}
205
		// Check mandatory fields
206
		$result = $this->_validate($request_data);
207
208
		foreach($request_data as $field => $value) {
209
			$this->company->$field = $value;
210
		}
211
		if ($this->company->create(DolibarrApiAccess::$user) < 0)
212
			throw new RestException(500, 'Error creating thirdparty', array_merge(array($this->company->error), $this->company->errors));
213
214
		return $this->company->id;
215
	}
216
217
	/**
218
	 * Update thirdparty
219
	 *
220
	 * @param int   $id             Id of thirdparty to update
221
	 * @param array $request_data   Datas
222
	 * @return int
223
	 */
224
    public function put($id, $request_data = null)
225
	{
226
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
227
			throw new RestException(401);
228
		}
229
230
		$result = $this->company->fetch($id);
231
		if( ! $result ) {
232
			throw new RestException(404, 'Thirdparty not found');
233
		}
234
235
		if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
236
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
237
		}
238
239
		foreach($request_data as $field => $value) {
240
			if ($field == 'id') continue;
241
			$this->company->$field = $value;
242
		}
243
244
		if($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update'))
245
			return $this->get($id);
246
247
		return false;
248
	}
249
250
	/**
251
	 * Merge a thirdparty into another one.
252
	 *
253
	 * Merge content (properties, notes) and objects (like invoices, events, orders, proposals, ...) of a thirdparty into a target thirdparty,
254
	 * then delete the merged thirdparty.
255
	 * If a property has a defined value both in thirdparty to delete and thirdparty to keep, the value into the thirdparty to
256
	 * delete will be ignored, the value of target thirdparty will remain, except for notes (content is concatenated).
257
	 *
258
	 * @param int   $id             ID of thirdparty to keep (the target thirdparty)
259
	 * @param int   $idtodelete     ID of thirdparty to remove (the thirdparty to delete), once data has been merged into the target thirdparty.
260
	 * @return int
261
	 *
262
	 * @url PUT {id}/merge/{idtodelete}
263
	 */
264
    public function merge($id, $idtodelete)
265
	{
266
		global $db, $hookmanager;
267
268
		$error = 0;
269
270
		if ($id == $idtodelete)
271
		{
272
			throw new RestException(400, 'Try to merge a thirdparty into itself');
273
		}
274
275
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
276
			throw new RestException(401);
277
		}
278
279
		$result = $this->company->fetch($id);	// include the fetch of extra fields
280
		if( ! $result ) {
281
			throw new RestException(404, 'Thirdparty not found');
282
		}
283
284
		if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
285
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
286
		}
287
288
		$this->companytoremove = new Societe($db);
289
290
		$result = $this->companytoremove->fetch($idtodelete);	// include the fetch of extra fields
291
		if( ! $result ) {
292
			throw new RestException(404, 'Thirdparty not found');
293
		}
294
295
		if( ! DolibarrApi::_checkAccessToResource('societe', $this->companytoremove->id)) {
296
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
297
		}
298
299
		$soc_origin = $this->companytoremove;
300
		$object = $this->company;
301
		$user = DolibarrApiAccess::$user;
302
303
304
		// Call same code than into action 'confirm_merge'
305
306
307
		$db->begin();
308
309
		// Recopy some data
310
		$object->client = $object->client | $soc_origin->client;
311
		$object->fournisseur = $object->fournisseur | $soc_origin->fournisseur;
312
		$listofproperties=array(
313
			'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode',
314
			'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
315
			'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
316
			'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency',
317
			'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
318
			'model_pdf', 'fk_projet'
319
		);
320
		foreach ($listofproperties as $property)
321
		{
322
			if (empty($object->$property)) $object->$property = $soc_origin->$property;
323
		}
324
325
		// Concat some data
326
		$listofproperties=array(
327
			'note_public', 'note_private'
328
		);
329
		foreach ($listofproperties as $property)
330
		{
331
			$object->$property = dol_concatdesc($object->$property, $soc_origin->$property);
332
		}
333
334
		// Merge extrafields
335
		if (is_array($soc_origin->array_options))
336
		{
337
			foreach ($soc_origin->array_options as $key => $val)
338
			{
339
				if (empty($object->array_options[$key])) $object->array_options[$key] = $val;
340
			}
341
		}
342
343
		// Merge categories
344
		$static_cat = new Categorie($db);
345
		$custcats = $static_cat->containing($soc_origin->id, 'customer', 'id');
346
		$object->setCategories($custcats, 'customer');
347
		$suppcats = $static_cat->containing($soc_origin->id, 'supplier', 'id');
348
		$object->setCategories($suppcats, 'supplier');
349
350
		// If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
351
		if ($soc_origin->code_client == $object->code_client
352
			|| $soc_origin->code_fournisseur == $object->code_fournisseur
353
			|| $soc_origin->barcode == $object->barcode)
354
		{
355
			dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
356
			$soc_origin->code_client = '';
357
			$soc_origin->code_fournisseur = '';
358
			$soc_origin->barcode = '';
359
			$soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
360
		}
361
362
		// Update
363
		$result = $object->update($object->id, $user, 0, 1, 1, 'merge');
364
		if ($result < 0)
365
		{
366
			$error++;
367
		}
368
369
		// Move links
370
		if (! $error)
371
		{
372
			$objects = array(
373
				'Adherent' => '/adherents/class/adherent.class.php',
374
				'Societe' => '/societe/class/societe.class.php',
375
				'Categorie' => '/categories/class/categorie.class.php',
376
				'ActionComm' => '/comm/action/class/actioncomm.class.php',
377
				'Propal' => '/comm/propal/class/propal.class.php',
378
				'Commande' => '/commande/class/commande.class.php',
379
				'Facture' => '/compta/facture/class/facture.class.php',
380
				'FactureRec' => '/compta/facture/class/facture-rec.class.php',
381
				'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
382
				'Contact' => '/contact/class/contact.class.php',
383
				'Contrat' => '/contrat/class/contrat.class.php',
384
				'Expedition' => '/expedition/class/expedition.class.php',
385
				'Fichinter' => '/fichinter/class/fichinter.class.php',
386
				'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
387
				'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
388
				'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
389
				'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
390
				'Livraison' => '/livraison/class/livraison.class.php',
391
				'Product' => '/product/class/product.class.php',
392
				'Project' => '/projet/class/project.class.php',
393
				'User' => '/user/class/user.class.php',
394
			);
395
396
			//First, all core objects must update their tables
397
			foreach ($objects as $object_name => $object_file)
398
			{
399
				require_once DOL_DOCUMENT_ROOT.$object_file;
400
401
				if (!$errors && !$object_name::replaceThirdparty($db, $soc_origin->id, $object->id))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $errors does not exist. Did you maybe mean $error?
Loading history...
402
				{
403
					$errors++;
404
					//setEventMessages($db->lasterror(), null, 'errors');
405
				}
406
			}
407
		}
408
409
		// External modules should update their ones too
410
		if (!$errors)
411
		{
412
            $reshook = $hookmanager->executeHooks('replaceThirdparty', array(
413
				'soc_origin' => $soc_origin->id,
414
				'soc_dest' => $object->id
415
			), $soc_dest, $action);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $soc_dest seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $action seems to be never defined.
Loading history...
416
417
			if ($reshook < 0)
418
			{
419
				//setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
420
				$errors++;
421
			}
422
		}
423
424
425
		if (! $error)
426
		{
427
			$object->context=array('merge'=>1, 'mergefromid'=>$soc_origin->id);
428
429
			// Call trigger
430
			$result=$object->call_trigger('COMPANY_MODIFY', $user);
431
			if ($result < 0)
432
			{
433
				//setEventMessages($object->error, $object->errors, 'errors');
434
				$error++;
435
			}
436
			// End call triggers
437
		}
438
439
		if (! $error)
440
		{
441
			//We finally remove the old thirdparty
442
			if ($soc_origin->delete($soc_origin->id, $user) < 1)
443
			{
444
				$errors++;
445
			}
446
		}
447
448
		// End of merge
449
450
		if ($error)
451
		{
452
			$db->rollback();
453
454
			throw new RestException(500, 'Error failed to merged thirdparty '.$this->companytoremove->id.' into '.$id.'. Enable and read log file for more information.');
455
		}
456
		else
457
		{
458
			$db->commit();
459
		}
460
461
		return $this->get($id);
462
	}
463
464
	/**
465
	 * Delete thirdparty
466
	 *
467
	 * @param int $id   Thirparty ID
468
	 * @return integer
469
	 */
470
    public function delete($id)
471
	{
472
		if(! DolibarrApiAccess::$user->rights->societe->supprimer) {
473
			throw new RestException(401);
474
		}
475
		$result = $this->company->fetch($id);
476
		if( ! $result ) {
477
			throw new RestException(404, 'Thirdparty not found');
478
		}
479
		if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
480
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
481
		}
482
        $this->company->oldcopy = clone $this->company;
483
		return $this->company->delete($id);
484
	}
485
486
	/**
487
	 * Get customer categories for a thirdparty
488
	 *
489
	 * @param int		$id         ID of thirdparty
490
	 * @param string	$sortfield	Sort field
491
	 * @param string	$sortorder	Sort order
492
	 * @param int		$limit		Limit for list
493
	 * @param int		$page		Page number
494
	 *
495
	 * @return mixed
496
	 *
497
	 * @url GET {id}/categories
498
	 */
499
    public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
500
	{
501
		if (! DolibarrApiAccess::$user->rights->categorie->lire) {
502
			throw new RestException(401);
503
		}
504
505
		$result = $this->company->fetch($id);
506
		if( ! $result )
507
		{
508
			throw new RestException(404, 'Thirdparty not found');
509
		}
510
511
		$categories = new Categorie($this->db);
512
513
		$result = $categories->getListForItem($id, 'customer', $sortfield, $sortorder, $limit, $page);
514
515
		if (is_numeric($result) && $result < 0)
516
		{
517
			throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
518
		}
519
520
		if (is_numeric($result) && $result == 0)	// To fix a return of 0 instead of empty array of method getListForItem
521
		{
522
			return array();
523
		}
524
525
		return $result;
526
	}
527
528
	/**
529
	 * Add a customer category to a thirdparty
530
	 *
531
	 * @param int		$id				Id of thirdparty
532
	 * @param int       $category_id	Id of category
533
	 *
534
	 * @return mixed
535
	 *
536
	 * @url POST {id}/categories/{category_id}
537
	 */
538
    public function addCategory($id, $category_id)
539
	{
540
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
541
			throw new RestException(401);
542
		}
543
544
		$result = $this->company->fetch($id);
545
		if( ! $result ) {
546
			throw new RestException(404, 'Thirdparty not found');
547
		}
548
		$category = new Categorie($this->db);
549
		$result = $category->fetch($category_id);
550
		if( ! $result ) {
551
			throw new RestException(404, 'category not found');
552
		}
553
554
		if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
555
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
556
		}
557
		if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) {
558
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
559
		}
560
561
		$category->add_type($this->company, 'customer');
562
563
		return $this->_cleanObjectDatas($this->company);
564
	}
565
566
	/**
567
	 * Remove the link between a customer category and the thirdparty
568
	 *
569
	 * @param int		$id				Id of thirdparty
570
	 * @param int		$category_id	Id of category
571
	 *
572
	 * @return mixed
573
	 *
574
	 * @url DELETE {id}/categories/{category_id}
575
	 */
576
    public function deleteCategory($id, $category_id)
577
	{
578
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
579
			throw new RestException(401);
580
		}
581
582
		$result = $this->company->fetch($id);
583
		if( ! $result ) {
584
			throw new RestException(404, 'Thirdparty not found');
585
		}
586
		$category = new Categorie($this->db);
587
		$result = $category->fetch($category_id);
588
		if( ! $result ) {
589
			throw new RestException(404, 'category not found');
590
		}
591
592
		if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
593
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
594
		}
595
		if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) {
596
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
597
		}
598
599
		$category->del_type($this->company, 'customer');
600
601
		return $this->_cleanObjectDatas($this->company);
602
	}
603
604
	/**
605
	 * Get supplier categories for a thirdparty
606
	 *
607
	 * @param int		$id         ID of thirdparty
608
	 * @param string	$sortfield	Sort field
609
	 * @param string	$sortorder	Sort order
610
	 * @param int		$limit		Limit for list
611
	 * @param int		$page		Page number
612
	 *
613
	 * @return mixed
614
	 *
615
	 * @url GET {id}/supplier_categories
616
	 */
617
    public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
618
	{
619
		if (! DolibarrApiAccess::$user->rights->categorie->lire) {
620
			throw new RestException(401);
621
		}
622
623
		$result = $this->company->fetch($id);
624
		if( ! $result )
625
		{
626
			throw new RestException(404, 'Thirdparty not found');
627
		}
628
629
		$categories = new Categorie($this->db);
630
631
		$result = $categories->getListForItem($id, 'supplier', $sortfield, $sortorder, $limit, $page);
632
633
		if (is_numeric($result) && $result < 0)
634
		{
635
			throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
636
		}
637
638
		if (is_numeric($result) && $result == 0)	// To fix a return of 0 instead of empty array of method getListForItem
639
		{
640
			return array();
641
		}
642
643
		return $result;
644
	}
645
646
	/**
647
	 * Add a supplier category to a thirdparty
648
	 *
649
	 * @param int		$id				Id of thirdparty
650
	 * @param int       $category_id	Id of category
651
	 *
652
	 * @return mixed
653
	 *
654
	 * @url POST {id}/supplier_categories/{category_id}
655
	 */
656
    public function addSupplierCategory($id, $category_id)
657
	{
658
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
659
			throw new RestException(401);
660
		}
661
662
		$result = $this->company->fetch($id);
663
		if( ! $result ) {
664
			throw new RestException(404, 'Thirdparty not found');
665
		}
666
		$category = new Categorie($this->db);
667
		$result = $category->fetch($category_id);
668
		if( ! $result ) {
669
			throw new RestException(404, 'category not found');
670
		}
671
672
		if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
673
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
674
		}
675
		if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) {
676
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
677
		}
678
679
		$category->add_type($this->company, 'supplier');
680
681
		return $this->_cleanObjectDatas($this->company);
682
	}
683
684
	/**
685
	 * Remove the link between a category and the thirdparty
686
	 *
687
	 * @param int		$id				Id of thirdparty
688
	 * @param int		$category_id	Id of category
689
	 *
690
	 * @return mixed
691
	 *
692
	 * @url DELETE {id}/supplier_categories/{category_id}
693
	 */
694
    public function deleteSupplierCategory($id, $category_id)
695
	{
696
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
697
			throw new RestException(401);
698
		}
699
700
		$result = $this->company->fetch($id);
701
		if( ! $result ) {
702
			throw new RestException(404, 'Thirdparty not found');
703
		}
704
		$category = new Categorie($this->db);
705
		$result = $category->fetch($category_id);
706
		if( ! $result ) {
707
			throw new RestException(404, 'category not found');
708
		}
709
710
		if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
711
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
712
		}
713
		if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) {
714
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
715
		}
716
717
		$category->del_type($this->company, 'supplier');
718
719
		return $this->_cleanObjectDatas($this->company);
720
	}
721
722
723
	/**
724
	 * Get outstanding proposals of thirdparty
725
	 *
726
	 * @param 	int 	$id			ID of the thirdparty
727
	 * @param 	string 	$mode		'customer' or 'supplier'
728
	 *
729
	 * @url     GET {id}/outstandingproposals
730
	 *
731
	 * @return array  				List of outstandings proposals of thirdparty
732
	 *
733
	 * @throws 400
734
	 * @throws 401
735
	 * @throws 404
736
	 */
737
    public function getOutStandingProposals($id, $mode = 'customer')
738
	{
739
		$obj_ret = array();
740
741
		if(! DolibarrApiAccess::$user->rights->societe->lire) {
742
			throw new RestException(401);
743
		}
744
745
		if(empty($id)) {
746
			throw new RestException(400, 'Thirdparty ID is mandatory');
747
		}
748
749
		if( ! DolibarrApi::_checkAccessToResource('societe', $id)) {
750
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
751
		}
752
753
		$result = $this->company->fetch($id);
754
		if( ! $result ) {
755
			throw new RestException(404, 'Thirdparty not found');
756
		}
757
758
		$result = $this->company->getOutstandingProposals($mode);
759
760
		unset($result['total_ht']);
761
		unset($result['total_ttc']);
762
763
		return $result;
764
	}
765
766
767
	/**
768
	 * Get outstanding orders of thirdparty
769
	 *
770
	 * @param 	int 	$id			ID of the thirdparty
771
	 * @param 	string 	$mode		'customer' or 'supplier'
772
	 *
773
	 * @url     GET {id}/outstandingorders
774
	 *
775
	 * @return array  				List of outstandings orders of thirdparty
776
	 *
777
	 * @throws 400
778
	 * @throws 401
779
	 * @throws 404
780
	 */
781
    public function getOutStandingOrder($id, $mode = 'customer')
782
	{
783
		$obj_ret = array();
784
785
		if(! DolibarrApiAccess::$user->rights->societe->lire) {
786
			throw new RestException(401);
787
		}
788
789
		if(empty($id)) {
790
			throw new RestException(400, 'Thirdparty ID is mandatory');
791
		}
792
793
		if( ! DolibarrApi::_checkAccessToResource('societe', $id)) {
794
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
795
		}
796
797
		$result = $this->company->fetch($id);
798
		if( ! $result ) {
799
			throw new RestException(404, 'Thirdparty not found');
800
		}
801
802
		$result = $this->company->getOutstandingOrders($mode);
803
804
		unset($result['total_ht']);
805
		unset($result['total_ttc']);
806
807
		return $result;
808
	}
809
810
	/**
811
	 * Get outstanding invoices of thirdparty
812
	 *
813
	 * @param 	int 	$id			ID of the thirdparty
814
	 * @param 	string 	$mode		'customer' or 'supplier'
815
	 *
816
	 * @url     GET {id}/outstandinginvoices
817
	 *
818
	 * @return array  				List of outstandings invoices of thirdparty
819
	 *
820
	 * @throws 400
821
	 * @throws 401
822
	 * @throws 404
823
	 */
824
    public function getOutStandingInvoices($id, $mode = 'customer')
825
	{
826
		$obj_ret = array();
827
828
		if(! DolibarrApiAccess::$user->rights->societe->lire) {
829
			throw new RestException(401);
830
		}
831
832
		if(empty($id)) {
833
			throw new RestException(400, 'Thirdparty ID is mandatory');
834
		}
835
836
		if( ! DolibarrApi::_checkAccessToResource('societe', $id)) {
837
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
838
		}
839
840
		$result = $this->company->fetch($id);
841
		if( ! $result ) {
842
			throw new RestException(404, 'Thirdparty not found');
843
		}
844
845
		$result = $this->company->getOutstandingBills($mode);
846
847
		unset($result['total_ht']);
848
		unset($result['total_ttc']);
849
850
		return $result;
851
	}
852
853
	/**
854
	 * Get fixed amount discount of a thirdparty (all sources: deposit, credit note, commercial offers...)
855
	 *
856
	 * @param 	int 	$id             ID of the thirdparty
857
	 * @param 	string 	$filter    	Filter exceptional discount. "none" will return every discount, "available" returns unapplied discounts, "used" returns applied discounts   {@choice none,available,used}
858
	 * @param   string  $sortfield  	Sort field
859
	 * @param   string  $sortorder  	Sort order
860
	 *
861
	 * @url     GET {id}/fixedamountdiscounts
862
	 *
863
	 * @return array  List of fixed discount of thirdparty
864
	 *
865
	 * @throws 400
866
	 * @throws 401
867
	 * @throws 404
868
	 * @throws 503
869
	 */
870
    public function getFixedAmountDiscounts($id, $filter = "none", $sortfield = "f.type", $sortorder = 'ASC')
871
	{
872
		$obj_ret = array();
873
874
		if(! DolibarrApiAccess::$user->rights->societe->lire) {
875
			throw new RestException(401);
876
		}
877
878
		if(empty($id)) {
879
			throw new RestException(400, 'Thirdparty ID is mandatory');
880
		}
881
882
		if( ! DolibarrApi::_checkAccessToResource('societe', $id)) {
883
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
884
		}
885
886
		$result = $this->company->fetch($id);
887
		if( ! $result ) {
888
			throw new RestException(404, 'Thirdparty not found');
889
		}
890
891
892
		$sql = "SELECT f.ref, f.type as factype, re.fk_facture_source, re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc, re.description, re.fk_facture, re.fk_facture_line";
893
		$sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re, ".MAIN_DB_PREFIX."facture as f";
894
		$sql .= " WHERE f.rowid = re.fk_facture_source AND re.fk_soc = ".$id;
895
		if ($filter == "available")  $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL";
896
		if ($filter == "used")  $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)";
897
898
		$sql.= $this->db->order($sortfield, $sortorder);
899
900
		$result = $this->db->query($sql);
901
		if( ! $result ) {
902
			throw new RestException(503, $this->db->lasterror());
903
		} else {
904
			$num = $this->db->num_rows($result);
905
			while ( $obj = $this->db->fetch_object($result) ) {
906
				$obj_ret[] = $obj;
907
			}
908
		}
909
910
		return $obj_ret;
911
	}
912
913
914
915
	/**
916
	 * Return list of invoices qualified to be replaced by another invoice.
917
	 *
918
	 * @param int   $id             Id of thirdparty
919
	 *
920
	 * @url     GET {id}/getinvoicesqualifiedforreplacement
921
	 *
922
	 * @return array
923
	 * @throws 400
924
	 * @throws 401
925
	 * @throws 404
926
	 * @throws 405
927
	 */
928
    public function getInvoicesQualifiedForReplacement($id)
929
    {
930
		if(! DolibarrApiAccess::$user->rights->facture->lire) {
931
			throw new RestException(401);
932
		}
933
		if(empty($id)) {
934
			throw new RestException(400, 'Thirdparty ID is mandatory');
935
		}
936
937
		if( ! DolibarrApi::_checkAccessToResource('societe', $id)) {
938
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
939
		}
940
941
		/*$result = $this->thirdparty->fetch($id);
942
		 if( ! $result ) {
943
		 throw new RestException(404, 'Thirdparty not found');
944
		 }*/
945
946
		$invoice = new Facture($this->db);
947
		$result = $invoice->list_replacable_invoices($id);
948
		if( $result < 0) {
949
			throw new RestException(405, $this->thirdparty->error);
0 ignored issues
show
Bug Best Practice introduced by
The property thirdparty does not exist on Thirdparties. Did you maybe forget to declare it?
Loading history...
950
		}
951
952
		return $result;
953
	}
954
955
	/**
956
	 * Return list of invoices qualified to be corrected by a credit note.
957
	 * Invoices matching the following rules are returned
958
	 * (validated + payment on process) or classified (payed completely or payed partialy) + not already replaced + not already a credit note
959
	 *
960
	 * @param int   $id             Id of thirdparty
961
	 *
962
	 * @url     GET {id}/getinvoicesqualifiedforcreditnote
963
	 *
964
	 * @return array
965
	 * @throws 400
966
	 * @throws 401
967
	 * @throws 404
968
	 * @throws 405
969
	 */
970
    public function getInvoicesQualifiedForCreditNote($id)
971
    {
972
		if(! DolibarrApiAccess::$user->rights->facture->lire) {
973
			throw new RestException(401);
974
		}
975
		if(empty($id)) {
976
			throw new RestException(400, 'Thirdparty ID is mandatory');
977
		}
978
979
		if( ! DolibarrApi::_checkAccessToResource('societe', $id)) {
980
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
981
		}
982
983
		/*$result = $this->thirdparty->fetch($id);
984
		 if( ! $result ) {
985
		 throw new RestException(404, 'Thirdparty not found');
986
		 }*/
987
988
		$invoice = new Facture($this->db);
989
		$result = $invoice->list_qualified_avoir_invoices($id);
990
		if( $result < 0) {
991
			throw new RestException(405, $this->thirdparty->error);
0 ignored issues
show
Bug Best Practice introduced by
The property thirdparty does not exist on Thirdparties. Did you maybe forget to declare it?
Loading history...
992
		}
993
994
		return $result;
995
	}
996
997
	/**
998
	 * Get CompanyBankAccount objects for thirdparty
999
	 *
1000
	 * @param int $id ID of thirdparty
1001
	 *
1002
	 * @return array
1003
	 *
1004
	 * @url GET {id}/bankaccounts
1005
	 */
1006
    public function getCompanyBankAccount($id)
1007
    {
1008
		global $db, $conf;
1009
1010
		if(! DolibarrApiAccess::$user->rights->facture->lire) {
1011
			throw new RestException(401);
1012
		}
1013
		if(empty($id)) {
1014
			throw new RestException(400, 'Thirdparty ID is mandatory');
1015
		}
1016
1017
		if( ! DolibarrApi::_checkAccessToResource('societe', $id)) {
1018
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1019
		}
1020
1021
		/**
1022
		 * We select all the records that match the socid
1023
		 */
1024
1025
		$sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,";
1026
		$sql.= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur";
1027
		$sql.= " FROM ".MAIN_DB_PREFIX."societe_rib";
1028
		if ($id) $sql.= " WHERE fk_soc  = ".$id." ";
1029
1030
1031
		$result = $db->query($sql);
1032
1033
		if($result->num_rows == 0 ){
1034
			throw new RestException(404, 'Account not found');
1035
		}
1036
1037
		$i=0;
1038
1039
		$accounts = array();
1040
1041
		if ($result)
1042
		{
1043
			$num = $db->num_rows($result);
1044
			while ($i < $num)
1045
			{
1046
				$obj = $db->fetch_object($result);
1047
				$account = new CompanyBankAccount($db);
1048
				if($account->fetch($obj->rowid)) {
1049
					$accounts[] = $account;
1050
				}
1051
				$i++;
1052
			}
1053
		}
1054
		else{
1055
			throw new RestException(404, 'Account not found');
1056
		}
1057
1058
1059
		$fields = array('socid', 'default_rib', 'frstrecur', '1000110000001', 'datec', 'datem', 'label', 'bank', 'bic', 'iban', 'id', 'rum');
1060
1061
		$returnAccounts = array();
1062
1063
		foreach($accounts as $account){
1064
			$object= array();
1065
			foreach($account as $key => $value)
1066
				if(in_array($key, $fields)){
1067
					$object[$key] = $value;
1068
				}
1069
			$returnAccounts[] = $object;
1070
		}
1071
1072
		return $returnAccounts;
1073
	}
1074
1075
	/**
1076
	 * Create CompanyBankAccount object for thirdparty
1077
	 * @param int  $id ID of thirdparty
1078
	 * @param array $request_data Request data
1079
	 *
1080
	 * @return object  ID of thirdparty
1081
	 *
1082
	 * @url POST {id}/bankaccounts
1083
	 */
1084
    public function createCompanyBankAccount($id, $request_data = null)
1085
	{
1086
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
1087
			throw new RestException(401);
1088
		}
1089
1090
		$account = new CompanyBankAccount($this->db);
1091
1092
		$account->socid = $id;
1093
1094
		foreach($request_data as $field => $value) {
1095
			$account->$field = $value;
1096
		}
1097
1098
		if ($account->create(DolibarrApiAccess::$user) < 0)
1099
			throw new RestException(500, 'Error creating Company Bank account');
1100
1101
1102
		if ($account->update(DolibarrApiAccess::$user) < 0)
1103
			throw new RestException(500, 'Error updating values');
1104
1105
		return $account;
1106
	}
1107
1108
	/**
1109
	 * Update CompanyBankAccount object for thirdparty
1110
	 *
1111
	 * @param int $id ID of thirdparty
1112
	 * @param int  $bankaccount_id ID of CompanyBankAccount
1113
	 * @param array $request_data Request data
1114
	 *
1115
	 * @return object  ID of thirdparty
1116
	 *
1117
	 * @url PUT {id}/bankaccounts/{bankaccount_id}
1118
	 */
1119
    public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null)
1120
	{
1121
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
1122
			throw new RestException(401);
1123
		}
1124
1125
		$account = new CompanyBankAccount($this->db);
1126
1127
		$account->fetch($bankaccount_id, $id, -1, '');
1128
1129
		if($account->socid != $id){
1130
			throw new RestException(401);
1131
		}
1132
1133
1134
		foreach($request_data as $field => $value) {
1135
			$account->$field = $value;
1136
		}
1137
1138
		if ($account->update(DolibarrApiAccess::$user) < 0)
1139
			throw new RestException(500, 'Error updating values');
1140
1141
		return $account;
1142
	}
1143
1144
	/**
1145
	 * Delete a bank account attached to a thirdparty
1146
	 *
1147
	 * @param int $id ID of thirdparty
1148
	 * @param int $bankaccount_id ID of CompanyBankAccount
1149
	 *
1150
	 * @return int -1 if error 1 if correct deletion
1151
	 *
1152
	 * @url DELETE {id}/bankaccounts/{bankaccount_id}
1153
	 */
1154
    public function deleteCompanyBankAccount($id, $bankaccount_id)
1155
    {
1156
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
1157
			throw new RestException(401);
1158
		}
1159
1160
		$account = new CompanyBankAccount($this->db);
1161
1162
		$account->fetch($bankaccount_id);
1163
1164
		if(!$account->socid == $id)
1165
			throw new RestException(401);
1166
1167
		return $account->delete(DolibarrApiAccess::$user);
1168
	}
1169
1170
	/**
1171
	 * Generate a Document from a bank account record (like SEPA mandate)
1172
	 *
1173
	 * @param int 		$id 			Thirdparty id
1174
	 * @param int 		$companybankid 	Companybank id
1175
	 * @param string 	$model 			Model of document to generate
1176
	 * @return void
1177
	 *
1178
	 * @url GET {id}/generateBankAccountDocument/{companybankid}/{model}
1179
	 */
1180
	public function generateBankAccountDocument($id, $companybankid = null, $model = 'sepamandate')
1181
	{
1182
		global $conf;
1183
1184
		$this->langs->loadLangs(array("main","dict","commercial","products","companies","banks","bills","withdrawals"));
0 ignored issues
show
Bug Best Practice introduced by
The property langs does not exist on Thirdparties. Did you maybe forget to declare it?
Loading history...
1185
1186
		$this->company->fetch($id);
1187
1188
		$action = 'builddoc';
1189
		if(! DolibarrApiAccess::$user->rights->societe->creer)
1190
			throw new RestException(401);
1191
1192
		$this->company->setDocModel(DolibarrApiAccess::$user, $model);
1193
1194
		$this->company->fk_bank = $this->company->fk_account;
0 ignored issues
show
Bug introduced by
The property fk_bank does not seem to exist on Societe.
Loading history...
1195
1196
		$outputlangs = $this->langs;
1197
		$newlang='';
1198
1199
		if ($this->conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang=GETPOST('lang_id', 'aZ09');
0 ignored issues
show
Bug Best Practice introduced by
The property conf does not exist on Thirdparties. Did you maybe forget to declare it?
Loading history...
1200
		if ($this->conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->company->thirdparty->default_lang)) $newlang=$this->company->thirdparty->default_lang;  // for proposal, order, invoice, ...
1201
		if ($this->conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->company->default_lang)) $newlang=$this->company->default_lang;                  // for thirdparty
1202
		if (! empty($newlang)) {
1203
			$outputlangs = new Translate("", $conf);
1204
			$outputlangs->setDefaultLang($newlang);
1205
		}
1206
1207
		// To be sure vars is defined
1208
		$hidedetails = $hidedesc = $hideref = 0;
1209
		$moreparams=null;
1210
		if (empty($hidedetails)) $hidedetails=0;
1 ignored issue
show
introduced by
The condition empty($hidedetails) is always true.
Loading history...
1211
		if (empty($hidedesc)) $hidedesc=0;
1 ignored issue
show
introduced by
The condition empty($hidedesc) is always true.
Loading history...
1212
		if (empty($hideref)) $hideref=0;
1 ignored issue
show
introduced by
The condition empty($hideref) is always true.
Loading history...
1213
		if (empty($moreparams)) $moreparams=null;
0 ignored issues
show
introduced by
The condition empty($moreparams) is always false.
Loading history...
1214
1215
1216
		$sql = "SELECT rowid";
1217
		$sql.= " FROM ".MAIN_DB_PREFIX."societe_rib";
1218
		if ($id) $sql.= " WHERE fk_soc  = ".$id." ";
1219
		if ($companybankid) $sql.= " AND id = ".$companybankid."";
1220
1221
		$i=0;
1222
		$accounts=array();
1223
1224
		$result = $this->db->query($sql);
1225
		if ($result)
1226
		{
1227
			if ($result->num_rows == 0) {
1228
				throw new RestException(404, 'Bank account not found');
1229
			}
1230
1231
			$num = $this->db->num_rows($result);
1232
			while ($i < $num)
1233
			{
1234
				$obj = $this->db->fetch_object($result);
1235
1236
				$account = new CompanyBankAccount($this->db);
1237
				if ($account->fetch($obj->rowid)) {
1238
					$accounts[] = $account;
1239
				}
1240
				$i++;
1241
			}
1242
		}
1243
		else
1244
		{
1245
			throw new RestException(404, 'Bank account not found');
1246
		}
1247
1248
		$moreparams = array(
1249
			'use_companybankid'=>$accounts[0]->id,
1250
			'force_dir_output'=>$this->conf->societe->multidir_output[$this->company->entity].'/'.dol_sanitizeFileName($this->company->id)
1251
		);
1252
1253
		$result = 0;
1254
1255
		$result = $this->company->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1256
1257
		if ($result > 0)
1258
		{
1259
			return array("success" => $result);
1260
		}
1261
		else
1262
		{
1263
			throw new RestException(500);
1264
		}
1265
    }
1266
1267
  /**
1268
	 * Get a specific gateway attached to a thirdparty (by specifying the site key)
1269
	 *
1270
	 * @param int $id ID of thirdparty
1271
	 * @param string $site Site key
1272
	 *
1273
	 * @return SocieteAccount[]
1274
	 * @throws 401 Unauthorized: User does not have permission to read thirdparties
1275
	 * @throws 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
1276
	 *
1277
	 * @url GET {id}/gateways/
1278
	 */
1279
    public function getSocieteAccounts($id, $site = null)
1280
    {
1281
		global $db, $conf;
1282
1283
		if(!DolibarrApiAccess::$user->rights->societe->lire) {
1284
			throw new RestException(401);
1285
		}
1286
1287
		if(!DolibarrApi::_checkAccessToResource('societe', $id)) {
1288
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1289
		}
1290
1291
		/**
1292
		 * We select all the records that match the socid
1293
		 */
1294
		$sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
1295
		$sql.= " WHERE fk_soc = $id";
1296
		if($site) $sql .= " AND site ='$site'";
1297
1298
		$result = $db->query($sql);
1299
1300
		if($result->num_rows == 0){
1301
			throw new RestException(404, 'This thirdparty does not have any gateway attached or does not exist.');
1302
		}
1303
1304
		$i=0;
1305
1306
		$accounts = array();
1307
1308
		$num = $db->num_rows($result);
1309
		while ($i < $num)
1310
		{
1311
			$obj = $db->fetch_object($result);
1312
			$account = new SocieteAccount($db);
1313
1314
			if($account->fetch($obj->rowid)) {
1315
				$accounts[] = $account;
1316
			}
1317
			$i++;
1318
		}
1319
1320
		$fields = array('id', 'fk_soc', 'key_account', 'site', 'date_creation', 'tms');
1321
1322
		$returnAccounts = array();
1323
1324
		foreach($accounts as $account){
1325
			$object= array();
1326
			foreach($account as $key => $value)
1327
				if(in_array($key, $fields)){
1328
					$object[$key] = $value;
1329
				}
1330
			$returnAccounts[] = $object;
1331
		}
1332
1333
		return $returnAccounts;
1334
	}
1335
1336
	/**
1337
	 * Create and attach a new gateway to an existing thirdparty
1338
	 *
1339
	 * Possible fields for request_data (request body) are specified in <code>llx_societe_account</code> table.<br>
1340
	 * See <a href="https://wiki.dolibarr.org/index.php/Table_llx_societe_account">Table llx_societe_account</a> wiki page for more information<br><br>
1341
	 * <u>Example body payload :</u> <pre>{"key_account": "cus_DAVkLSs1LYyYI", "site": "stripe"}</pre>
1342
	 *
1343
	 * @param int $id ID of thirdparty
1344
	 * @param array $request_data Request data
1345
	 *
1346
	 * @return SocieteAccount
1347
	 * @throws 401 Unauthorized: User does not have permission to read thirdparties
1348
	 * @throws 409 Conflict: A SocieteAccount entity (gateway) already exists for this company and site.
1349
	 * @throws 422 Unprocessable Entity: You must pass the site attribute in your request data !
1350
	 * @throws 500 Internal Server Error: Error creating SocieteAccount account
1351
	 * @status 201
1352
	 *
1353
	 * @url POST {id}/gateways
1354
	 */
1355
    public function createSocieteAccount($id, $request_data = null)
1356
	{
1357
		global $db;
1358
1359
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
1360
			throw new RestException(401);
1361
		}
1362
1363
		if(!isset($request_data['site'])) {
1364
			throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !');
1365
		}
1366
1367
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc  = ".$id." AND site = '". $request_data['site']."' ";
1368
		$result = $db->query($sql);
1369
1370
		if($result->num_rows == 0 ){
1371
			$account = new SocieteAccount($this->db);
1372
			if(!isset($request_data['login'])) {
1373
				$account->login = "";
1374
			}
1375
			$account->fk_soc = $id;
1376
1377
			foreach($request_data as $field => $value) {
1378
				$account->$field = $value;
1379
			}
1380
1381
			if ($account->create(DolibarrApiAccess::$user) < 0)
1382
				throw new RestException(500, 'Error creating SocieteAccount entity. Ensure that the ID of thirdparty provided does exist!');
1383
1384
			$this->_cleanObjectDatas($account);
1385
1386
			return $account;
1387
		} else {
1388
			throw new RestException(409, 'A SocieteAccount entity already exists for this company and site.');
1389
		}
1390
	}
1391
1392
	/**
1393
	 * Create and attach a new (or replace an existing) specific site gateway to a thirdparty
1394
	 *
1395
	 * You <strong>MUST</strong> pass all values to keep (otherwise, they will be deleted) !<br>
1396
	 * If you just need to update specific fields prefer <code>PATCH /thirdparties/{id}/gateways/{site}</code> endpoint.<br><br>
1397
	 * When a <strong>SocieteAccount</strong> entity does not exist for the <code>id</code> and <code>site</code>
1398
	 * supplied, a new one will be created. In that case <code>fk_soc</code> and <code>site</code> members form
1399
	 * request body payload will be ignored and <code>id</code> and <code>site</code> query strings parameters
1400
	 * will be used instead.
1401
	 *
1402
	 * @param int $id ID of thirdparty
1403
	 * @param string $site Site key
1404
	 * @param array $request_data Request data
1405
	 *
1406
	 * @return SocieteAccount
1407
	 * @throws 401 Unauthorized: User does not have permission to read thirdparties
1408
	 * @throws 422 Unprocessable Entity: You must pass the site attribute in your request data !
1409
	 * @throws 500 Internal Server Error: Error updating SocieteAccount entity
1410
	 *
1411
	 * @throws RestException
1412
	 * @url PUT {id}/gateways/{site}
1413
	 */
1414
    public function putSocieteAccount($id, $site, $request_data = null)
1415
	{
1416
		global $db;
1417
1418
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
1419
			throw new RestException(401);
1420
		}
1421
1422
		$sql = "SELECT rowid, fk_user_creat, date_creation FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '$site' ";
1423
		$result = $db->query($sql);
1424
1425
		// We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one.
1426
		if($result->num_rows == 0 ){
1427
			if(!isset($request_data['key_account'])) {
1428
				throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !');
1429
			}
1430
			$account = new SocieteAccount($this->db);
1431
			if(!isset($request_data['login'])) {
1432
				$account->login = "";
1433
			}
1434
1435
			foreach($request_data as $field => $value) {
1436
				$account->$field = $value;
1437
			}
1438
1439
			$account->fk_soc = $id;
1440
			$account->site = $site;
1441
1442
			if ($account->create(DolibarrApiAccess::$user) < 0)
1443
				throw new RestException(500, 'Error creating SocieteAccount entity.');
1444
		// We found an existing SocieteAccount entity, we are replacing it
1445
		} else {
1446
			if(isset($request_data['site']) && $request_data['site'] !== $site) {
1447
				$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc  = ".$id." AND site = '". $request_data['site']."' ";
1448
				$result = $db->query($sql);
1449
1450
				if($result->num_rows !== 0)
1451
					throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) from $site to ".$request_data['site'] . " but another SocieteAccount entity already exists with this site key.");
1452
			}
1453
1454
			$obj = $db->fetch_object($result);
1455
1456
			$account = new SocieteAccount($this->db);
1457
			$account->id = $obj->rowid;
1458
			$account->fk_soc = $id;
1459
			$account->site = $site;
1460
			if(!isset($request_data['login'])) {
1461
				$account->login = "";
1462
			}
1463
			$account->fk_user_creat = $obj->fk_user_creat;
1464
			$account->date_creation = $obj->date_creation;
1465
1466
			foreach($request_data as $field => $value) {
1467
				$account->$field = $value;
1468
			}
1469
1470
			if ($account->update(DolibarrApiAccess::$user) < 0)
1471
				throw new RestException(500, 'Error updating SocieteAccount entity.');
1472
		}
1473
1474
		$this->_cleanObjectDatas($account);
1475
1476
		return $account;
1477
	}
1478
1479
	/**
1480
	 * Update specified values of a specific site gateway attached to a thirdparty
1481
	 *
1482
	 * @param int $id Id of thirdparty
1483
	 * @param string  $site Site key
1484
	 * @param array $request_data Request data
1485
	 *
1486
	 * @return SocieteAccount
1487
	 * @throws 401 Unauthorized: User does not have permission to read thirdparties
1488
	 * @throws 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
1489
	 * @throws 409 Conflict: Another SocieteAccount entity already exists for this thirdparty with this site key.
1490
	 * @throws 500 Internal Server Error: Error updating SocieteAccount entity
1491
	 *
1492
	 * @url PATCH {id}/gateways/{site}
1493
	 */
1494
    public function patchSocieteAccount($id, $site, $request_data = null)
1495
	{
1496
		global $db;
1497
1498
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
1499
			throw new RestException(401);
1500
		}
1501
1502
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc  = $id AND site = '$site' ";
1503
		$result = $db->query($sql);
1504
1505
		if($result->num_rows == 0 ){
1506
			throw new RestException(404, "This thirdparty does not have $site gateway attached or does not exist.");
1507
		} else {
1508
			// If the user tries to edit the site member, we check first if
1509
			if(isset($request_data['site']) && $request_data['site'] !== $site) {
1510
				$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc  = ".$id." AND site = '". $request_data['site']."' ";
1511
				$result = $db->query($sql);
1512
1513
				if($result->num_rows !== 0)
1514
					throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) site member from $site to ".$request_data['site'] . " but another SocieteAccount entity already exists for this thirdparty with this site key.");
1515
			}
1516
1517
			$obj = $db->fetch_object($result);
1518
			$account = new SocieteAccount($this->db);
1519
			$account->fetch($obj->rowid);
1520
1521
			foreach($request_data as $field => $value) {
1522
				$account->$field = $value;
1523
			}
1524
1525
			if ($account->update(DolibarrApiAccess::$user) < 0)
1526
				throw new RestException(500, 'Error updating SocieteAccount account');
1527
1528
			$this->_cleanObjectDatas($account);
1529
1530
			return $account;
1531
		}
1532
	}
1533
1534
	/**
1535
	 * Delete a specific site gateway attached to a thirdparty (by gateway id)
1536
	 *
1537
	 * @param int $id ID of thirdparty
1538
	 * @param int $site Site key
1539
	 *
1540
	 * @return void
1541
	 * @throws 401 Unauthorized: User does not have permission to delete thirdparties gateways
1542
	 * @throws 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
1543
	 * @throws 500 Internal Server Error: Error deleting SocieteAccount entity
1544
	 *
1545
	 * @url DELETE {id}/gateways/{site}
1546
	 */
1547
    public function deleteSocieteAccount($id, $site)
1548
    {
1549
		global /** @var Database $db */
1550
		$db;
1551
1552
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
1553
			throw new RestException(401);
1554
		}
1555
1556
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc  = $id AND site = '$site' ";
1557
		$result = $db->query($sql);
1558
1559
		if($result->num_rows == 0 ){
1560
			throw new RestException(404);
1561
		} else {
1562
			$obj = $db->fetch_object($result);
1563
			$account = new SocieteAccount($this->db);
1564
			$account->fetch($obj->rowid);
1565
1566
			if($account->delete(DolibarrApiAccess::$user) < 0) {
1567
				throw new RestException(500, "Error while deleting $site gateway attached to this third party");
1568
			}
1569
		}
1570
	}
1571
1572
	/**
1573
	 * Delete all gateways attached to a thirdparty
1574
	 *
1575
	 * @param int $id ID of thirdparty
1576
	 *
1577
	 * @return void
1578
	 * @throws RestException(401) Unauthorized: User does not have permission to delete thirdparties gateways
1579
	 * @throws RestException(404) Not Found: Specified thirdparty ID does not belongs to an existing thirdparty
1580
	 * @throws RestException(500) Internal Server Error: Error deleting SocieteAccount entity
1581
	 *
1582
	 * @url DELETE {id}/gateways
1583
	 */
1584
    public function deleteSocieteAccounts($id)
1585
    {
1586
		global /** @var Database $db */
1587
		$db;
1588
1589
		if(! DolibarrApiAccess::$user->rights->societe->creer) {
1590
			throw new RestException(401);
1591
		}
1592
1593
		/**
1594
		 * We select all the records that match the socid
1595
		 */
1596
1597
		$sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms";
1598
		$sql.= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc  = $id ";
1599
1600
		$result = $db->query($sql);
1601
1602
		if($result->num_rows == 0 ){
1603
			throw new RestException(404, 'This third party does not have any gateway attached or does not exist.');
1604
		} else {
1605
			$i=0;
1606
1607
			$num = $db->num_rows($result);
1608
			while ($i < $num)
1609
			{
1610
				$obj = $db->fetch_object($result);
1611
				$account = new SocieteAccount($db);
1612
				$account->fetch($obj->rowid);
1613
1614
				if($account->delete(DolibarrApiAccess::$user) < 0) {
1615
					throw new RestException(500, 'Error while deleting gateways attached to this third party');
1616
				}
1617
				$i++;
1618
			}
1619
		}
1620
	}
1621
1622
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1623
	/**
1624
	 * Clean sensible object datas
1625
	 *
1626
	 * @param   object  $object    Object to clean
1627
	 * @return    array    Array of cleaned object properties
1628
	 */
1629
	protected function _cleanObjectDatas($object)
1630
    {
1631
        // phpcs:enable
1632
		$object = parent::_cleanObjectDatas($object);
1633
1634
		unset($object->nom);	// ->name already defined and nom deprecated
1635
1636
		unset($object->total_ht);
1637
		unset($object->total_tva);
1638
		unset($object->total_localtax1);
1639
		unset($object->total_localtax2);
1640
		unset($object->total_ttc);
1641
1642
		unset($object->lines);
1643
		unset($object->thirdparty);
1644
1645
		return $object;
1646
	}
1647
1648
	/**
1649
	 * Validate fields before create or update object
1650
	 *
1651
	 * @param array $data   Datas to validate
1652
	 * @return array
1653
	 *
1654
	 * @throws RestException
1655
	 */
1656
    private function _validate($data)
1657
    {
1658
        $thirdparty = array();
1659
        foreach (Thirdparties::$FIELDS as $field) {
1660
            if (!isset($data[$field]))
1661
                throw new RestException(400, "$field field missing");
1662
            $thirdparty[$field] = $data[$field];
1663
        }
1664
        return $thirdparty;
1665
    }
1666
1667
  /**
1668
   * Fetch properties of a thirdparty object.
1669
   *
1670
   * Return an array with thirdparty informations
1671
   *
1672
   * @param	   int		$rowid      Id of third party to load
1673
	 * @param    string	$ref        Reference of third party, name (Warning, this can return several records)
1674
	 * @param    string	$ref_ext    External reference of third party (Warning, this information is a free field not provided by Dolibarr)
1675
	 * @param    string	$ref_int    Internal reference of third party (not used by dolibarr)
1676
	 * @param    string	$idprof1		Prof id 1 of third party (Warning, this can return several records)
1677
	 * @param    string	$idprof2		Prof id 2 of third party (Warning, this can return several records)
1678
	 * @param    string	$idprof3		Prof id 3 of third party (Warning, this can return several records)
1679
	 * @param    string	$idprof4		Prof id 4 of third party (Warning, this can return several records)
1680
	 * @param    string	$idprof5		Prof id 5 of third party (Warning, this can return several records)
1681
	 * @param    string	$idprof6		Prof id 6 of third party (Warning, this can return several records)
1682
	 * @param    string	$email   		Email of third party (Warning, this can return several records)
1683
	 * @param    string	$ref_alias  Name_alias of third party (Warning, this can return several records)
1684
   * @return array|mixed data without useless information
1685
   *
1686
   * @throws RestException
1687
   */
1688
  private function _fetch($rowid, $ref = '', $ref_ext = '', $ref_int = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
1689
  {
1690
      if(! DolibarrApiAccess::$user->rights->societe->lire) {
1691
          throw new RestException(401);
1692
      }
1693
1694
      $result = $this->company->fetch($rowid, $ref, $ref_ext, $ref_int, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias);
1695
      if( ! $result ) {
1696
          throw new RestException(404, 'Thirdparty not found');
1697
      }
1698
1699
      if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) {
1700
          throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1701
      }
1702
1703
      if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
1704
          $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1705
          $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1706
      } else {
1707
          $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
1708
          $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
1709
      }
1710
1711
      $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount);
1712
      $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote);
1713
      $this->company->absolute_discount = price2num($absolute_discount, 'MT');
0 ignored issues
show
Bug introduced by
The property absolute_discount does not seem to exist on Societe.
Loading history...
1714
      $this->company->absolute_creditnote = price2num($absolute_creditnote, 'MT');
0 ignored issues
show
Bug introduced by
The property absolute_creditnote does not seem to exist on Societe.
Loading history...
1715
1716
      return $this->_cleanObjectDatas($this->company);
1717
  }
1718
}
1719