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