Passed
Branch develop (a7390e)
by
unknown
25:38
created

Expedition::create_line()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
c 0
b 0
f 0
nc 2
nop 4
dl 0
loc 17
rs 9.9332
1
<?php
2
/* Copyright (C) 2003-2008	Rodolphe Quiedeville	<[email protected]>
3
 * Copyright (C) 2005-2012	Regis Houssin			<[email protected]>
4
 * Copyright (C) 2007		Franky Van Liedekerke	<[email protected]>
5
 * Copyright (C) 2006-2012	Laurent Destailleur		<[email protected]>
6
 * Copyright (C) 2011-2017	Juanjo Menent			<[email protected]>
7
 * Copyright (C) 2013       Florian Henry		  	<[email protected]>
8
 * Copyright (C) 2014		Cedric GROSS			<[email protected]>
9
 * Copyright (C) 2014-2015  Marcos García           <[email protected]>
10
 * Copyright (C) 2014-2017  Francis Appels          <[email protected]>
11
 * Copyright (C) 2015       Claudio Aschieri        <[email protected]>
12
 * Copyright (C) 2016		Ferran Marcet			<[email protected]>
13
 * Copyright (C) 2018       Nicolas ZABOURI			<[email protected]>
14
 * Copyright (C) 2018       Frédéric France         <[email protected]>
15
 *
16
 * This program is free software; you can redistribute it and/or modify
17
 * it under the terms of the GNU General Public License as published by
18
 * the Free Software Foundation; either version 3 of the License, or
19
 * (at your option) any later version.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 * GNU General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU General Public License
27
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
28
 */
29
30
/**
31
 *  \file       htdocs/expedition/class/expedition.class.php
32
 *  \ingroup    expedition
33
 *  \brief      Fichier de la classe de gestion des expeditions
34
 */
35
36
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
37
require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
38
if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
39
if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
40
if (! empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
41
42
43
/**
44
 *	Class to manage shipments
45
 */
46
class Expedition extends CommonObject
47
{
48
	/**
49
	 * @var string ID to identify managed object
50
	 */
51
	public $element="shipping";
52
53
	/**
54
	 * @var int Field with ID of parent key if this field has a parent
55
	 */
56
	public $fk_element="fk_expedition";
57
58
	/**
59
	 * @var string Name of table without prefix where object is stored
60
	 */
61
	public $table_element="expedition";
62
63
	/**
64
	 * @var int    Name of subtable line
65
	 */
66
	public $table_element_line="expeditiondet";
67
68
	/**
69
	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
70
	 * @var int
71
	 */
72
	public $ismultientitymanaged = 1;
73
74
	/**
75
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
76
	 */
77
	public $picto = 'sending';
78
79
	public $socid;
80
81
	/**
82
	 * @var string Customer ref
83
	 */
84
	public $ref_customer;
85
86
	/**
87
	 * @var string internal ref
88
	 */
89
	public $ref_int;
90
91
	public $brouillon;
92
93
	/**
94
	 * @var int warehouse id
95
	 */
96
	public $entrepot_id;
97
	public $lines=array();
98
99
	/**
100
	 * @var string Tracking number
101
	 */
102
	public $tracking_number;
103
104
	/**
105
	 * @var string Tracking url
106
	 */
107
	public $tracking_url;
108
	public $billed;
109
110
	/**
111
	 * @var string name of pdf model
112
	 */
113
	public $model_pdf;
114
115
	public $trueWeight;
116
	public $weight_units;
117
	public $trueWidth;
118
	public $width_units;
119
	public $trueHeight;
120
	public $height_units;
121
	public $trueDepth;
122
	public $depth_units;
123
	// A denormalized value
124
	public $trueSize;
125
126
	public $date_delivery;		// Date delivery planed
127
128
	/**
129
	 * @deprecated
130
	 * @see $date_shipping
131
	 */
132
	public $date;
133
134
	/**
135
	 * @deprecated
136
	 * @see $date_shipping
137
	 */
138
	public $date_expedition;
139
140
	/**
141
	 * Effective delivery date
142
	 * @var int
143
	 */
144
	public $date_shipping;
145
146
	public $date_creation;
147
	public $date_valid;
148
149
	public $meths;
150
	public $listmeths;			// List of carriers
151
152
    /**
153
	 * Draft status
154
	 */
155
	const STATUS_DRAFT = 0;
156
157
	/**
158
	 * Validated status
159
	 */
160
	const STATUS_VALIDATED = 1;
161
162
	/**
163
	 * Closed status
164
	 */
165
	const STATUS_CLOSED = 2;
166
167
168
169
	/**
170
	 *	Constructor
171
	 *
172
	 *  @param		DoliDB		$db      Database handler
173
	 */
174
	public function __construct($db)
175
	{
176
		global $conf;
177
178
		$this->db = $db;
179
		$this->lines = array();
180
		$this->products = array();
181
182
		// List of long language codes for status
183
		$this->statuts = array();
184
		$this->statuts[-1] = 'StatusSendingCanceled';
185
		$this->statuts[0]  = 'StatusSendingDraft';
186
		$this->statuts[1]  = 'StatusSendingValidated';
187
		$this->statuts[2]  = 'StatusSendingProcessed';
188
189
		// List of short language codes for status
190
		$this->statutshorts = array();
191
		$this->statutshorts[-1] = 'StatusSendingCanceledShort';
192
		$this->statutshorts[0]  = 'StatusSendingDraftShort';
193
		$this->statutshorts[1]  = 'StatusSendingValidatedShort';
194
		$this->statutshorts[2]  = 'StatusSendingProcessedShort';
195
196
		/* Status "billed" or not is managed by another field than status
197
		if (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))
198
		{
199
			$this->statuts[2]  = 'StatusSendingBilled';
200
			$this->statutshorts[2]  = 'StatusSendingBilledShort';
201
		}*/
202
	}
203
204
	/**
205
	 *	Return next contract ref
206
	 *
207
	 *	@param	Societe		$soc	Thirdparty object
208
	 *	@return string				Free reference for contract
209
	 */
210
	public function getNextNumRef($soc)
211
	{
212
		global $langs, $conf;
213
		$langs->load("sendings");
214
215
		if (!empty($conf->global->EXPEDITION_ADDON_NUMBER))
216
		{
217
			$mybool = false;
218
219
			$file = $conf->global->EXPEDITION_ADDON_NUMBER.".php";
220
			$classname = $conf->global->EXPEDITION_ADDON_NUMBER;
221
222
			// Include file with class
223
			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
224
225
			foreach ($dirmodels as $reldir) {
226
227
				$dir = dol_buildpath($reldir."core/modules/expedition/");
228
229
				// Load file with numbering class (if found)
230
				$mybool|=@include_once $dir.$file;
231
			}
232
233
			if (! $mybool)
1 ignored issue
show
Bug Best Practice introduced by
The expression $mybool of type false|integer is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
234
			{
235
				dol_print_error('', "Failed to include file ".$file);
236
				return '';
237
			}
238
239
			$obj = new $classname();
240
			$numref = "";
241
			$numref = $obj->getNextValue($soc, $this);
242
243
			if ( $numref != "")
244
			{
245
				return $numref;
246
			}
247
			else
248
			{
249
				dol_print_error($this->db, get_class($this)."::getNextNumRef ".$obj->error);
250
				return "";
251
			}
252
		}
253
		else
254
		{
255
			print $langs->trans("Error")." ".$langs->trans("Error_EXPEDITION_ADDON_NUMBER_NotDefined");
256
			return "";
257
		}
258
	}
259
260
	/**
261
	 *  Create expedition en base
262
	 *
263
	 *  @param	User	$user       Objet du user qui cree
264
	 * 	@param		int		$notrigger	1=Does not execute triggers, 0= execute triggers
265
	 *  @return int 				<0 si erreur, id expedition creee si ok
266
	 */
267
	public function create($user, $notrigger = 0)
268
	{
269
		global $conf, $hookmanager;
270
271
		$now=dol_now();
272
273
		require_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php';
274
		$error = 0;
275
276
		// Clean parameters
277
		$this->brouillon = 1;
278
		$this->tracking_number = dol_sanitizeFileName($this->tracking_number);
279
		if (empty($this->fk_project)) $this->fk_project = 0;
280
281
		$this->user = $user;
282
283
284
		$this->db->begin();
285
286
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."expedition (";
287
		$sql.= "ref";
288
		$sql.= ", entity";
289
		$sql.= ", ref_customer";
290
		$sql.= ", ref_int";
291
		$sql.= ", date_creation";
292
		$sql.= ", fk_user_author";
293
		$sql.= ", date_expedition";
294
		$sql.= ", date_delivery";
295
		$sql.= ", fk_soc";
296
		$sql.= ", fk_projet";
297
		$sql.= ", fk_address";
298
		$sql.= ", fk_shipping_method";
299
		$sql.= ", tracking_number";
300
		$sql.= ", weight";
301
		$sql.= ", size";
302
		$sql.= ", width";
303
		$sql.= ", height";
304
		$sql.= ", weight_units";
305
		$sql.= ", size_units";
306
		$sql.= ", note_private";
307
		$sql.= ", note_public";
308
		$sql.= ", model_pdf";
309
		$sql.= ", fk_incoterms, location_incoterms";
310
		$sql.= ") VALUES (";
311
		$sql.= "'(PROV)'";
312
		$sql.= ", ".$conf->entity;
313
		$sql.= ", ".($this->ref_customer?"'".$this->db->escape($this->ref_customer)."'":"null");
314
		$sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
315
		$sql.= ", '".$this->db->idate($now)."'";
316
		$sql.= ", ".$user->id;
317
		$sql.= ", ".($this->date_expedition>0?"'".$this->db->idate($this->date_expedition)."'":"null");
1 ignored issue
show
Deprecated Code introduced by
The property Expedition::$date_expedition has been deprecated. ( Ignorable by Annotation )

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

317
		$sql.= ", ".(/** @scrutinizer ignore-deprecated */ $this->date_expedition>0?"'".$this->db->idate($this->date_expedition)."'":"null");
Loading history...
318
		$sql.= ", ".($this->date_delivery>0?"'".$this->db->idate($this->date_delivery)."'":"null");
319
		$sql.= ", ".$this->socid;
320
		$sql.= ", ".$this->fk_project;
321
		$sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:"null");
1 ignored issue
show
Deprecated Code introduced by
The property CommonObject::$fk_delivery_address has been deprecated. ( Ignorable by Annotation )

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

321
		$sql.= ", ".(/** @scrutinizer ignore-deprecated */ $this->fk_delivery_address>0?$this->fk_delivery_address:"null");
Loading history...
322
		$sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:"null");
323
		$sql.= ", '".$this->db->escape($this->tracking_number)."'";
324
		$sql.= ", ".$this->weight;
325
		$sql.= ", ".$this->sizeS;	// TODO Should use this->trueDepth
0 ignored issues
show
Bug Best Practice introduced by
The property sizeS does not exist on Expedition. Did you maybe forget to declare it?
Loading history...
326
		$sql.= ", ".$this->sizeW;	// TODO Should use this->trueWidth
0 ignored issues
show
Bug Best Practice introduced by
The property sizeW does not exist on Expedition. Did you maybe forget to declare it?
Loading history...
327
		$sql.= ", ".$this->sizeH;	// TODO Should use this->trueHeight
0 ignored issues
show
Bug Best Practice introduced by
The property sizeH does not exist on Expedition. Did you maybe forget to declare it?
Loading history...
328
		$sql.= ", ".$this->weight_units;
329
		$sql.= ", ".$this->size_units;
330
		$sql.= ", ".(!empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null");
331
		$sql.= ", ".(!empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null");
332
		$sql.= ", ".(!empty($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null");
333
		$sql.= ", ".(int) $this->fk_incoterms;
334
		$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
335
		$sql.= ")";
336
337
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
338
		$resql=$this->db->query($sql);
339
		if ($resql)
340
		{
341
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expedition");
342
343
			$sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
344
			$sql.= " SET ref = '(PROV".$this->id.")'";
345
			$sql.= " WHERE rowid = ".$this->id;
346
347
			dol_syslog(get_class($this)."::create", LOG_DEBUG);
348
			if ($this->db->query($sql))
349
			{
350
				// Insert of lines
351
				$num=count($this->lines);
352
				for ($i = 0; $i < $num; $i++)
353
				{
354
					if (! isset($this->lines[$i]->detail_batch))
355
					{	// no batch management
356
						if (! $this->create_line($this->lines[$i]->entrepot_id, $this->lines[$i]->origin_line_id, $this->lines[$i]->qty, $this->lines[$i]->array_options) > 0)
357
						{
358
							$error++;
359
						}
360
					}
361
					else
362
					{	// with batch management
363
						if (! $this->create_line_batch($this->lines[$i], $this->lines[$i]->array_options) > 0)
364
						{
365
							$error++;
366
						}
367
					}
368
				}
369
370
				if (! $error && $this->id && $this->origin_id)
371
				{
372
					$ret = $this->add_object_linked();
373
					if (!$ret)
374
					{
375
						$error++;
376
					}
377
				}
378
379
				// Actions on extra fields
380
				if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))
381
				{
382
					$result=$this->insertExtraFields();
383
					if ($result < 0)
384
					{
385
						$error++;
386
					}
387
				}
388
389
				if (! $error && ! $notrigger)
390
				{
391
					// Call trigger
392
					$result=$this->call_trigger('SHIPPING_CREATE', $user);
393
					if ($result < 0) { $error++; }
394
					// End call triggers
395
396
					if (! $error)
397
					{
398
						$this->db->commit();
399
						return $this->id;
400
					}
401
					else
402
					{
403
						foreach($this->errors as $errmsg)
404
						{
405
							dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
406
							$this->error.=($this->error?', '.$errmsg:$errmsg);
407
						}
408
						$this->db->rollback();
409
						return -1*$error;
410
					}
411
				}
412
				else
413
				{
414
					$error++;
415
					$this->error=$this->db->lasterror()." - sql=$sql";
416
					$this->db->rollback();
417
					return -3;
418
				}
419
			}
420
			else
421
			{
422
				$error++;
423
				$this->error=$this->db->lasterror()." - sql=$sql";
424
				$this->db->rollback();
425
				return -2;
426
			}
427
		}
428
		else
429
		{
430
			$error++;
431
			$this->error=$this->db->error()." - sql=$sql";
432
			$this->db->rollback();
433
			return -1;
434
		}
435
	}
436
437
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
438
	/**
439
	 * Create a expedition line
440
	 *
441
	 * @param 	int		$entrepot_id		Id of warehouse
442
	 * @param 	int		$origin_line_id		Id of source line
443
	 * @param 	int		$qty				Quantity
444
	 * @param	array	$array_options		extrafields array
445
	 * @return	int							<0 if KO, line_id if OK
446
	 */
447
	public function create_line($entrepot_id, $origin_line_id, $qty, $array_options = 0)
448
	{
449
		//phpcs:enable
450
		global $user;
451
452
		$expeditionline = new ExpeditionLigne($this->db);
453
		$expeditionline->fk_expedition = $this->id;
454
		$expeditionline->entrepot_id = $entrepot_id;
455
		$expeditionline->fk_origin_line = $origin_line_id;
456
		$expeditionline->qty = $qty;
457
		$expeditionline->array_options = $array_options;
458
459
		if (($lineId = $expeditionline->insert($user)) < 0)
460
		{
461
			$this->errors[]=$expeditionline->error;
462
		}
463
		return $lineId;
464
	}
465
466
467
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
468
	/**
469
	 * Create the detail (eat-by date) of the expedition line
470
	 *
471
	 * @param 	object		$line_ext		full line informations
472
	 * @param	array		$array_options		extrafields array
473
	 * @return	int							<0 if KO, >0 if OK
474
	 */
475
	public function create_line_batch($line_ext, $array_options = 0)
476
	{
477
        // phpcs:enable
478
		$error = 0;
479
		$stockLocationQty = array(); // associated array with batch qty in stock location
480
481
		$tab=$line_ext->detail_batch;
482
		// create stockLocation Qty array
483
		foreach ($tab as $detbatch)
484
		{
485
			if ($detbatch->entrepot_id)
486
			{
487
				$stockLocationQty[$detbatch->entrepot_id] += $detbatch->qty;
488
			}
489
		}
490
		// create shipment lines
491
		foreach ($stockLocationQty as $stockLocation => $qty)
492
		{
493
			if (($line_id = $this->create_line($stockLocation, $line_ext->origin_line_id, $qty, $array_options)) < 0)
494
			{
495
				$error++;
496
			}
497
			else
498
			{
499
				// create shipment batch lines for stockLocation
500
				foreach ($tab as $detbatch)
501
				{
502
					if ($detbatch->entrepot_id == $stockLocation){
503
						if (! ($detbatch->create($line_id) >0))		// Create an expeditionlinebatch
504
						{
505
							$error++;
506
						}
507
					}
508
				}
509
			}
510
		}
511
512
		if (! $error) return 1;
513
		else return -1;
514
	}
515
516
	/**
517
	 *	Get object and lines from database
518
	 *
519
	 *	@param	int		$id       	Id of object to load
520
	 * 	@param	string	$ref		Ref of object
521
	 * 	@param	string	$ref_ext	External reference of object
522
	 * 	@param	string	$ref_int	Internal reference of other object
523
	 *	@return int			        >0 if OK, 0 if not found, <0 if KO
524
	 */
525
	public function fetch($id, $ref = '', $ref_ext = '', $ref_int = '')
526
	{
527
		global $conf;
528
529
		// Check parameters
530
		if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
531
532
		$sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_customer, e.ref_ext, e.ref_int, e.fk_user_author, e.fk_statut, e.fk_projet as fk_project, e.billed";
533
        $sql.= ", e.date_valid";
534
		$sql.= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
535
		$sql.= ", e.date_expedition as date_expedition, e.model_pdf, e.fk_address, e.date_delivery";
536
		$sql.= ", e.fk_shipping_method, e.tracking_number";
537
		$sql.= ", e.note_private, e.note_public";
538
		$sql.= ', e.fk_incoterms, e.location_incoterms';
539
		$sql.= ', i.libelle as label_incoterms';
540
		$sql.= ', s.libelle as shipping_method';
541
		$sql.= ", el.fk_source as origin_id, el.sourcetype as origin";
542
		$sql.= " FROM ".MAIN_DB_PREFIX."expedition as e";
543
		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
544
		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid';
545
		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_shipment_mode as s ON e.fk_shipping_method = s.rowid';
546
		$sql.= " WHERE e.entity IN (".getEntity('expedition').")";
547
		if ($id)   	  $sql.= " AND e.rowid=".$id;
548
		if ($ref)     $sql.= " AND e.ref='".$this->db->escape($ref)."'";
549
		if ($ref_ext) $sql.= " AND e.ref_ext='".$this->db->escape($ref_ext)."'";
550
		if ($ref_int) $sql.= " AND e.ref_int='".$this->db->escape($ref_int)."'";
551
552
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
553
		$result = $this->db->query($sql);
554
		if ($result)
555
		{
556
			if ($this->db->num_rows($result))
557
			{
558
				$obj = $this->db->fetch_object($result);
559
560
				$this->id                   = $obj->rowid;
561
				$this->ref                  = $obj->ref;
562
				$this->socid                = $obj->socid;
563
				$this->ref_customer	    = $obj->ref_customer;
564
				$this->ref_ext		    = $obj->ref_ext;
565
				$this->ref_int		    = $obj->ref_int;
566
				$this->statut               = $obj->fk_statut;
567
				$this->user_author_id       = $obj->fk_user_author;
568
				$this->date_creation        = $this->db->jdate($obj->date_creation);
569
                $this->date_valid           = $this->db->jdate($obj->date_valid);
570
				$this->date                 = $this->db->jdate($obj->date_expedition);	// TODO deprecated
571
				$this->date_expedition      = $this->db->jdate($obj->date_expedition);	// TODO deprecated
572
				$this->date_shipping        = $this->db->jdate($obj->date_expedition);	// Date real
573
				$this->date_delivery        = $this->db->jdate($obj->date_delivery);	// Date planed
574
				$this->fk_delivery_address  = $obj->fk_address;
575
				$this->modelpdf             = $obj->model_pdf;
576
				$this->shipping_method_id   = $obj->fk_shipping_method;
577
				$this->shipping_method	    = $obj->shipping_method;
578
				$this->tracking_number      = $obj->tracking_number;
579
				$this->origin               = ($obj->origin?$obj->origin:'commande'); // For compatibility
580
				$this->origin_id            = $obj->origin_id;
581
				$this->billed               = $obj->billed;
582
				$this->fk_project	        = $obj->fk_project;
583
584
				$this->trueWeight           = $obj->weight;
585
				$this->weight_units         = $obj->weight_units;
586
587
				$this->trueWidth            = $obj->width;
588
				$this->width_units          = $obj->size_units;
589
				$this->trueHeight           = $obj->height;
590
				$this->height_units         = $obj->size_units;
591
				$this->trueDepth            = $obj->size;
592
				$this->depth_units          = $obj->size_units;
593
594
				$this->note_public          = $obj->note_public;
595
				$this->note_private         = $obj->note_private;
596
597
				// A denormalized value
598
				$this->trueSize             = $obj->size."x".$obj->width."x".$obj->height;
599
				$this->size_units           = $obj->size_units;
600
601
				//Incoterms
602
				$this->fk_incoterms         = $obj->fk_incoterms;
603
				$this->location_incoterms   = $obj->location_incoterms;
604
				$this->label_incoterms    = $obj->label_incoterms;
605
606
				$this->db->free($result);
607
608
				if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
609
610
				// Tracking url
611
				$this->getUrlTrackingStatus($obj->tracking_number);
612
613
				/*
614
				 * Thirdparty
615
				 */
616
				$result=$this->fetch_thirdparty();
617
618
				// Retreive extrafields
619
				$this->fetch_optionals();
620
621
				/*
622
				 * Lines
623
				 */
624
				$result=$this->fetch_lines();
625
				if ($result < 0)
626
				{
627
					return -3;
628
				}
629
630
				return 1;
631
			}
632
			else
633
			{
634
				dol_syslog(get_class($this).'::Fetch no expedition found', LOG_ERR);
635
				$this->error='Delivery with id '.$id.' not found';
636
				return 0;
637
			}
638
		}
639
		else
640
		{
641
			$this->error=$this->db->error();
642
			return -1;
643
		}
644
	}
645
646
	/**
647
	 *  Validate object and update stock if option enabled
648
	 *
649
	 *  @param      User		$user       Object user that validate
650
	 *  @param		int			$notrigger	1=Does not execute triggers, 0= execute triggers
651
	 *  @return     int						<0 if OK, >0 if KO
652
	 */
653
	public function valid($user, $notrigger = 0)
654
	{
655
		global $conf, $langs;
656
657
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
658
659
		dol_syslog(get_class($this)."::valid");
660
661
		// Protection
662
		if ($this->statut)
663
		{
664
			dol_syslog(get_class($this)."::valid no draft status", LOG_WARNING);
665
			return 0;
666
		}
667
668
		if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->creer))
669
	   	|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->shipping_advance->validate))))
670
		{
671
			$this->error='Permission denied';
672
			dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
673
			return -1;
674
		}
675
676
		$this->db->begin();
677
678
		$error = 0;
679
680
		// Define new ref
681
		$soc = new Societe($this->db);
682
		$soc->fetch($this->socid);
683
684
		// Class of company linked to order
685
		$result=$soc->set_as_client();
686
687
		// Define new ref
688
		if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
689
		{
690
			$numref = $this->getNextNumRef($soc);
691
		}
692
		else
693
		{
694
			$numref = "EXP".$this->id;
695
		}
696
		$this->newref = $numref;
697
698
		$now=dol_now();
699
700
		// Validate
701
		$sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
702
		$sql.= " ref='".$numref."'";
703
		$sql.= ", fk_statut = 1";
704
		$sql.= ", date_valid = '".$this->db->idate($now)."'";
705
		$sql.= ", fk_user_valid = ".$user->id;
706
		$sql.= " WHERE rowid = ".$this->id;
707
708
		dol_syslog(get_class($this)."::valid update expedition", LOG_DEBUG);
709
		$resql=$this->db->query($sql);
710
		if (! $resql)
711
		{
712
			$this->error=$this->db->lasterror();
713
			$error++;
714
		}
715
716
		// If stock increment is done on sending (recommanded choice)
717
		if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT))
718
		{
719
			require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
720
721
			$langs->load("agenda");
722
723
			// Loop on each product line to add a stock movement
724
			$sql = "SELECT cd.fk_product, cd.subprice,";
725
			$sql.= " ed.rowid, ed.qty, ed.fk_entrepot,";
726
			$sql.= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
727
			$sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
728
			$sql.= " ".MAIN_DB_PREFIX."expeditiondet as ed";
729
			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
730
			$sql.= " WHERE ed.fk_expedition = ".$this->id;
731
			$sql.= " AND cd.rowid = ed.fk_origin_line";
732
733
			dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
734
			$resql=$this->db->query($sql);
735
			if ($resql)
736
			{
737
				$cpt = $this->db->num_rows($resql);
738
				for ($i = 0; $i < $cpt; $i++)
739
				{
740
					$obj = $this->db->fetch_object($resql);
741
					if (empty($obj->edbrowid))
742
					{
743
						$qty = $obj->qty;
744
					}
745
					else
746
					{
747
						$qty = $obj->edbqty;
748
					}
749
					if ($qty <= 0) continue;
750
					dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
751
752
					//var_dump($this->lines[$i]);
753
					$mouvS = new MouvementStock($this->db);
754
					$mouvS->origin = &$this;
755
756
					if (empty($obj->edbrowid))
757
					{
758
						// line without batch detail
759
760
						// We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record.
761
						$result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentValidatedInDolibarr", $numref));
762
						if ($result < 0) {
763
							$error++;
764
							$this->error = $mouvS->error;
765
							$this->errors = array_merge($this->errors, $mouvS->errors);
766
							break;
767
						}
768
					}
769
					else
770
					{
771
						// line with batch detail
772
773
						// We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record.
774
						// Note: ->fk_origin_stock = id into table llx_product_batch (may be rename into llx_product_stock_batch in another version)
775
						$result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentValidatedInDolibarr", $numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock);
776
						if ($result < 0) {
777
							$error++;
778
							$this->error = $mouvS->error;
779
							$this->errors = array_merge($this->errors, $mouvS->errors);
780
							break;
781
						}
782
					}
783
				}
784
			}
785
			else
786
			{
787
				$this->db->rollback();
788
				$this->error=$this->db->error();
789
				return -2;
790
			}
791
		}
792
793
		// Change status of order to "shipment in process"
794
		$ret = $this->setStatut(Commande::STATUS_SHIPMENTONPROCESS, $this->origin_id, $this->origin);
795
796
		if (! $ret)
797
		{
798
			$error++;
799
		}
800
801
		if (! $error && ! $notrigger)
802
		{
803
			// Call trigger
804
			$result=$this->call_trigger('SHIPPING_VALIDATE', $user);
805
			if ($result < 0) { $error++; }
806
			// End call triggers
807
		}
808
809
		if (! $error)
810
		{
811
			$this->oldref = $this->ref;
812
813
			// Rename directory if dir was a temporary ref
814
			if (preg_match('/^[\(]?PROV/i', $this->ref))
815
			{
816
				// Now we rename also files into index
817
				$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref)+1).")), filepath = 'expedition/sending/".$this->db->escape($this->newref)."'";
818
				$sql.= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/sending/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
819
				$resql = $this->db->query($sql);
820
				if (! $resql) { $error++; $this->error = $this->db->lasterror(); }
821
822
				// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
823
				$oldref = dol_sanitizeFileName($this->ref);
824
				$newref = dol_sanitizeFileName($numref);
825
				$dirsource = $conf->expedition->dir_output.'/sending/'.$oldref;
826
				$dirdest = $conf->expedition->dir_output.'/sending/'.$newref;
827
				if (! $error && file_exists($dirsource))
828
				{
829
					dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
830
831
					if (@rename($dirsource, $dirdest))
832
					{
833
						dol_syslog("Rename ok");
834
						// Rename docs starting with $oldref with $newref
835
						$listoffiles=dol_dir_list($conf->expedition->dir_output.'/sending/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
836
						foreach($listoffiles as $fileentry)
837
						{
838
							$dirsource=$fileentry['name'];
839
							$dirdest=preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
840
							$dirsource=$fileentry['path'].'/'.$dirsource;
841
							$dirdest=$fileentry['path'].'/'.$dirdest;
842
							@rename($dirsource, $dirdest);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rename(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

842
							/** @scrutinizer ignore-unhandled */ @rename($dirsource, $dirdest);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
843
						}
844
					}
845
				}
846
			}
847
		}
848
849
		// Set new ref and current status
850
		if (! $error)
851
		{
852
			$this->ref = $numref;
853
			$this->statut = self::STATUS_VALIDATED;
854
		}
855
856
		if (! $error)
857
		{
858
			$this->db->commit();
859
			return 1;
860
		}
861
		else
862
		{
863
			$this->db->rollback();
864
			return -1*$error;
865
		}
866
	}
867
868
869
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
870
	/**
871
	 *	Create a delivery receipt from a shipment
872
	 *
873
	 *	@param	User	$user       User
874
	 *  @return int  				<0 if KO, >=0 if OK
875
	 */
876
	public function create_delivery($user)
877
	{
878
        // phpcs:enable
879
		global $conf;
880
881
		if ($conf->livraison_bon->enabled)
882
		{
883
			if ($this->statut == self::STATUS_VALIDATED || $this->statut == self::STATUS_CLOSED)
884
			{
885
				// Expedition validee
886
				include_once DOL_DOCUMENT_ROOT.'/livraison/class/livraison.class.php';
887
				$delivery = new Livraison($this->db);
888
				$result=$delivery->create_from_sending($user, $this->id);
889
				if ($result > 0)
890
				{
891
					return $result;
892
				}
893
				else
894
				{
895
					$this->error=$delivery->error;
896
					return $result;
897
				}
898
			}
899
			else return 0;
900
		}
901
		else return 0;
902
	}
903
904
	/**
905
	 * Add an expedition line.
906
	 * If STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS is set, you can add a shipment line, with no stock source defined
907
	 * If STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT is not set, you can add a shipment line, even if not enough into stock
908
	 *
909
	 * @param 	int		$entrepot_id		Id of warehouse
910
	 * @param 	int		$id					Id of source line (order line)
911
	 * @param 	int		$qty				Quantity
912
	 * @param	array	$array_options		extrafields array
913
	 * @return	int							<0 if KO, >0 if OK
914
	 */
915
	public function addline($entrepot_id, $id, $qty, $array_options = 0)
916
	{
917
		global $conf, $langs;
918
919
		$num = count($this->lines);
920
		$line = new ExpeditionLigne($this->db);
921
922
		$line->entrepot_id = $entrepot_id;
923
		$line->origin_line_id = $id;
1 ignored issue
show
Deprecated Code introduced by
The property ExpeditionLigne::$origin_line_id has been deprecated. ( Ignorable by Annotation )

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

923
		/** @scrutinizer ignore-deprecated */ $line->origin_line_id = $id;
Loading history...
924
		$line->qty = $qty;
925
926
		$orderline = new OrderLine($this->db);
927
		$orderline->fetch($id);
928
929
		if (! empty($conf->stock->enabled) && ! empty($orderline->fk_product))
930
		{
931
			$fk_product = $orderline->fk_product;
932
933
			if (! ($entrepot_id > 0) && empty($conf->global->STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS))
934
			{
935
				$langs->load("errors");
936
				$this->error=$langs->trans("ErrorWarehouseRequiredIntoShipmentLine");
937
				return -1;
938
			}
939
940
			if ($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT)
941
			{
942
				// Check must be done for stock of product into warehouse if $entrepot_id defined
943
				$product=new Product($this->db);
944
				$result=$product->fetch($fk_product);
945
946
				if ($entrepot_id > 0) {
947
					$product->load_stock('warehouseopen');
948
					$product_stock = $product->stock_warehouse[$entrepot_id]->real;
949
				}
950
				else
951
					$product_stock = $product->stock_reel;
952
953
				$product_type=$product->type;
954
				if ($product_type == 0 && $product_stock < $qty)
955
				{
956
					$langs->load("errors");
957
					$this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $product->ref);
958
					$this->db->rollback();
959
					return -3;
960
				}
961
			}
962
		}
963
964
		// If product need a batch number, we should not have called this function but addline_batch instead.
965
		if (! empty($conf->productbatch->enabled) && ! empty($orderline->fk_product) && ! empty($orderline->product_tobatch))
966
		{
967
			$this->error='ADDLINE_WAS_CALLED_INSTEAD_OF_ADDLINEBATCH';
968
			return -4;
969
		}
970
971
		// extrafields
972
		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
973
			$line->array_options = $array_options;
974
975
		$this->lines[$num] = $line;
976
	}
977
978
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
979
	/**
980
	 * Add a shipment line with batch record
981
	 *
982
	 * @param 	array		$dbatch		Array of value (key 'detail' -> Array, key 'qty' total quantity for line, key ix_l : original line index)
983
	 * @param	array		$array_options		extrafields array
984
	 * @return	int						<0 if KO, >0 if OK
985
	 */
986
	public function addline_batch($dbatch, $array_options = 0)
987
	{
988
        // phpcs:enable
989
		global $conf,$langs;
990
991
		$num = count($this->lines);
992
		if ($dbatch['qty']>0)
993
		{
994
			$line = new ExpeditionLigne($this->db);
995
			$tab=array();
996
			foreach ($dbatch['detail'] as $key=>$value)
997
			{
998
				if ($value['q']>0)
999
				{
1000
					// $value['q']=qty to move
1001
					// $value['id_batch']=id into llx_product_batch of record to move
1002
					//var_dump($value);
1003
1004
					$linebatch = new ExpeditionLineBatch($this->db);
1005
					$ret=$linebatch->fetchFromStock($value['id_batch']);	// load serial, sellby, eatby
1006
					if ($ret<0)
1007
					{
1008
						$this->error=$linebatch->error;
1009
						return -1;
1010
					}
1011
					$linebatch->qty=$value['q'];
1012
					$tab[]=$linebatch;
1013
1014
					if ($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT)
1015
					{
1016
						require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
1017
						$prod_batch = new Productbatch($this->db);
1018
						$prod_batch->fetch($value['id_batch']);
1019
1020
						if ($prod_batch->qty < $linebatch->qty)
1021
						{
1022
							$langs->load("errors");
1023
							$this->errors[]=$langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $prod_batch->fk_product);
1024
							dol_syslog(get_class($this)."::addline_batch error=Product ".$prod_batch->batch.": ".$this->errorsToString(), LOG_ERR);
1025
							$this->db->rollback();
1026
							return -1;
1027
						}
1028
					}
1029
1030
					//var_dump($linebatch);
1031
				}
1032
			}
1033
			$line->entrepot_id = $linebatch->entrepot_id;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $linebatch does not seem to be defined for all execution paths leading up to this point.
Loading history...
1034
			$line->origin_line_id = $dbatch['ix_l'];
1 ignored issue
show
Deprecated Code introduced by
The property ExpeditionLigne::$origin_line_id has been deprecated. ( Ignorable by Annotation )

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

1034
			/** @scrutinizer ignore-deprecated */ $line->origin_line_id = $dbatch['ix_l'];
Loading history...
1035
			$line->qty = $dbatch['qty'];
1036
			$line->detail_batch=$tab;
1037
1038
			// extrafields
1039
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
1040
				$line->array_options = $array_options;
1041
1042
			//var_dump($line);
1043
			$this->lines[$num] = $line;
1044
			return 1;
1045
		}
1046
	}
1047
1048
	/**
1049
	 *  Update database
1050
	 *
1051
	 *  @param	User	$user        	User that modify
1052
	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
1053
	 *  @return int 			       	<0 if KO, >0 if OK
1054
	 */
1055
	public function update($user = null, $notrigger = 0)
1056
	{
1057
		global $conf;
1058
		$error=0;
1059
1060
		// Clean parameters
1061
1062
		if (isset($this->ref)) $this->ref=trim($this->ref);
1063
		if (isset($this->entity)) $this->entity=trim($this->entity);
1064
		if (isset($this->ref_customer)) $this->ref_customer=trim($this->ref_customer);
1065
		if (isset($this->socid)) $this->socid=trim($this->socid);
1066
		if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author);
1067
		if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid);
1068
		if (isset($this->fk_delivery_address)) $this->fk_delivery_address=trim($this->fk_delivery_address);
1 ignored issue
show
Documentation Bug introduced by
The property $fk_delivery_address was declared of type integer, but trim($this->fk_delivery_address) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1069
		if (isset($this->shipping_method_id)) $this->shipping_method_id=trim($this->shipping_method_id);
1070
		if (isset($this->tracking_number)) $this->tracking_number=trim($this->tracking_number);
1071
		if (isset($this->statut)) $this->statut=(int) $this->statut;
1072
		if (isset($this->trueDepth)) $this->trueDepth=trim($this->trueDepth);
1073
		if (isset($this->trueWidth)) $this->trueWidth=trim($this->trueWidth);
1074
		if (isset($this->trueHeight)) $this->trueHeight=trim($this->trueHeight);
1075
		if (isset($this->size_units)) $this->size_units=trim($this->size_units);
1076
		if (isset($this->weight_units)) $this->weight_units=trim($this->weight_units);
1077
		if (isset($this->trueWeight)) $this->weight=trim($this->trueWeight);
1078
		if (isset($this->note_private)) $this->note=trim($this->note_private);
1079
		if (isset($this->note_public)) $this->note=trim($this->note_public);
1080
		if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
1081
1082
1083
1084
		// Check parameters
1085
		// Put here code to add control on parameters values
1086
1087
		// Update request
1088
		$sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
1089
1090
		$sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
1091
		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
1092
		$sql.= " ref_customer=".(isset($this->ref_customer)?"'".$this->db->escape($this->ref_customer)."'":"null").",";
1093
		$sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").",";
1094
		$sql.= " date_creation=".(dol_strlen($this->date_creation)!=0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
1095
		$sql.= " fk_user_author=".(isset($this->fk_user_author)?$this->fk_user_author:"null").",";
1096
		$sql.= " date_valid=".(dol_strlen($this->date_valid)!=0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
1097
		$sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
1098
		$sql.= " date_expedition=".(dol_strlen($this->date_expedition)!=0 ? "'".$this->db->idate($this->date_expedition)."'" : 'null').",";
1099
		$sql.= " date_delivery=".(dol_strlen($this->date_delivery)!=0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
1100
		$sql.= " fk_address=".(isset($this->fk_delivery_address)?$this->fk_delivery_address:"null").",";
1101
		$sql.= " fk_shipping_method=".((isset($this->shipping_method_id) && $this->shipping_method_id > 0)?$this->shipping_method_id:"null").",";
1102
		$sql.= " tracking_number=".(isset($this->tracking_number)?"'".$this->db->escape($this->tracking_number)."'":"null").",";
1103
		$sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
1104
		$sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
1105
		$sql.= " height=".(($this->trueHeight != '')?$this->trueHeight:"null").",";
1106
		$sql.= " width=".(($this->trueWidth != '')?$this->trueWidth:"null").",";
1107
		$sql.= " size_units=".(isset($this->size_units)?$this->size_units:"null").",";
1108
		$sql.= " size=".(($this->trueDepth != '')?$this->trueDepth:"null").",";
1109
		$sql.= " weight_units=".(isset($this->weight_units)?$this->weight_units:"null").",";
1110
		$sql.= " weight=".(($this->trueWeight != '')?$this->trueWeight:"null").",";
1111
		$sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
1112
		$sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
1113
		$sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").",";
1114
		$sql.= " entity=".$conf->entity;
1115
1116
		$sql.= " WHERE rowid=".$this->id;
1117
1118
		$this->db->begin();
1119
1120
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
1121
		$resql = $this->db->query($sql);
1122
		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
1123
1124
		if (! $error)
1125
		{
1126
			if (! $notrigger)
1127
			{
1128
				// Call trigger
1129
				$result=$this->call_trigger('SHIPPING_MODIFY', $user);
1130
				if ($result < 0) { $error++; }
1131
				// End call triggers
1132
			}
1133
		}
1134
1135
		// Commit or rollback
1136
		if ($error)
1137
		{
1138
			foreach($this->errors as $errmsg)
1139
			{
1140
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1141
				$this->error.=($this->error?', '.$errmsg:$errmsg);
1142
			}
1143
			$this->db->rollback();
1144
			return -1*$error;
1145
		}
1146
		else
1147
		{
1148
			$this->db->commit();
1149
			return 1;
1150
		}
1151
	}
1152
1153
	/**
1154
	 * 	Delete shipment.
1155
	 * 	Warning, do not delete a shipment if a delivery is linked to (with table llx_element_element)
1156
	 *
1157
	 *  @param  int  $notrigger 			Disable triggers
1158
     *  @param  bool $also_update_stock  	true if the stock should be increased back (false by default)
1159
	 * 	@return	int							>0 if OK, 0 if deletion done but failed to delete files, <0 if KO
1160
	 */
1161
	public function delete($notrigger = 0, $also_update_stock = false)
1162
	{
1163
		global $conf, $langs, $user;
1164
1165
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1166
		require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
1167
1168
		$error=0;
1169
		$this->error='';
1170
1171
		$this->db->begin();
1172
1173
		// Add a protection to refuse deleting if shipment has at least one delivery
1174
		$this->fetchObjectLinked($this->id, 'shipping', 0, 'delivery');	// Get deliveries linked to this shipment
1175
		if (count($this->linkedObjectsIds) > 0)
1176
		{
1177
			$this->error='ErrorThereIsSomeDeliveries';
1178
			$error++;
1179
		}
1180
1181
		if (! $error)
1182
		{
1183
			if (! $notrigger)
1184
			{
1185
				// Call trigger
1186
				$result=$this->call_trigger('SHIPPING_DELETE', $user);
1187
				if ($result < 0) { $error++; }
1188
				// End call triggers
1189
			}
1190
		}
1191
1192
		// Stock control
1193
		if (! $error && $conf->stock->enabled &&
1194
			(($conf->global->STOCK_CALCULATE_ON_SHIPMENT && $this->statut > self::STATUS_DRAFT) ||
1195
			 ($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE && $this->statut == self::STATUS_CLOSED && $also_update_stock)))
1196
		{
1197
			require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
1198
1199
			$langs->load("agenda");
1200
1201
			// Loop on each product line to add a stock movement
1202
			$sql = "SELECT cd.fk_product, cd.subprice, ed.qty, ed.fk_entrepot, ed.rowid as expeditiondet_id";
1203
			$sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
1204
			$sql.= " ".MAIN_DB_PREFIX."expeditiondet as ed";
1205
			$sql.= " WHERE ed.fk_expedition = ".$this->id;
1206
			$sql.= " AND cd.rowid = ed.fk_origin_line";
1207
1208
			dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
1209
			$resql=$this->db->query($sql);
1210
			if ($resql)
1211
			{
1212
				$cpt = $this->db->num_rows($resql);
1213
				for ($i = 0; $i < $cpt; $i++)
1214
				{
1215
					dol_syslog(get_class($this)."::delete movement index ".$i);
1216
					$obj = $this->db->fetch_object($resql);
1217
1218
					$mouvS = new MouvementStock($this->db);
1219
					// we do not log origin because it will be deleted
1220
					$mouvS->origin = null;
1221
					// get lot/serial
1222
					$lotArray = null;
1223
					if ($conf->productbatch->enabled)
1224
					{
1225
						$lotArray = ExpeditionLineBatch::fetchAll($this->db, $obj->expeditiondet_id);
1226
						if (! is_array($lotArray))
1227
						{
1228
							$error++;$this->errors[]="Error ".$this->db->lasterror();
1229
						}
1230
					}
1231
					if (empty($lotArray)) {
1232
						// no lot/serial
1233
						// We increment stock of product (and sub-products)
1234
						// We use warehouse selected for each line
1235
						$result=$mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->trans("ShipmentDeletedInDolibarr", $this->ref));  // Price is set to 0, because we don't want to see WAP changed
1236
						if ($result < 0)
1237
						{
1238
							$error++;$this->errors=$this->errors + $mouvS->errors;
1239
							break;
1240
						}
1241
					}
1242
					else
1243
					{
1244
						// We increment stock of batches
1245
						// We use warehouse selected for each line
1246
						foreach($lotArray as $lot)
1247
						{
1248
							$result=$mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->qty, 0, $langs->trans("ShipmentDeletedInDolibarr", $this->ref), $lot->eatby, $lot->sellby, $lot->batch);  // Price is set to 0, because we don't want to see WAP changed
1249
							if ($result < 0)
1250
							{
1251
								$error++;$this->errors=$this->errors + $mouvS->errors;
1252
								break;
1253
							}
1254
						}
1255
						if ($error) break; // break for loop incase of error
1256
					}
1257
				}
1258
			}
1259
			else
1260
			{
1261
				$error++;$this->errors[]="Error ".$this->db->lasterror();
1262
			}
1263
		}
1264
1265
		// delete batch expedition line
1266
		if (! $error && $conf->productbatch->enabled)
1267
		{
1268
			if (ExpeditionLineBatch::deletefromexp($this->db, $this->id) < 0)
1269
			{
1270
				$error++;$this->errors[]="Error ".$this->db->lasterror();
1271
			}
1272
		}
1273
1274
		if (! $error)
1275
		{
1276
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet";
1277
			$sql.= " WHERE fk_expedition = ".$this->id;
1278
1279
			if ( $this->db->query($sql) )
1280
			{
1281
				// Delete linked object
1282
				$res = $this->deleteObjectLinked();
1283
				if ($res < 0) $error++;
1284
1285
				if (! $error)
1286
				{
1287
					$sql = "DELETE FROM ".MAIN_DB_PREFIX."expedition";
1288
					$sql.= " WHERE rowid = ".$this->id;
1289
1290
					if ($this->db->query($sql))
1291
					{
1292
						if (! empty($this->origin) && $this->origin_id > 0)
1293
						{
1294
							$this->fetch_origin();
1295
							$origin=$this->origin;
1296
							if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS)     // If order source of shipment is "shipment in progress"
1297
							{
1298
								// Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress"
1299
								$this->$origin->loadExpeditions();
1300
								//var_dump($this->$origin->expeditions);exit;
1301
								if (count($this->$origin->expeditions) <= 0)
1302
								{
1303
									$this->$origin->setStatut(Commande::STATUS_VALIDATED);
1304
								}
1305
							}
1306
						}
1307
1308
						if (! $error)
1309
						{
1310
							$this->db->commit();
1311
1312
							// We delete PDFs
1313
							$ref = dol_sanitizeFileName($this->ref);
1314
							if (! empty($conf->expedition->dir_output))
1315
							{
1316
								$dir = $conf->expedition->dir_output . '/sending/' . $ref ;
1317
								$file = $dir . '/' . $ref . '.pdf';
1318
								if (file_exists($file))
1319
								{
1320
									if (! dol_delete_file($file))
1321
									{
1322
										return 0;
1323
									}
1324
								}
1325
								if (file_exists($dir))
1326
								{
1327
									if (!dol_delete_dir_recursive($dir))
1328
									{
1329
										$this->error=$langs->trans("ErrorCanNotDeleteDir", $dir);
1330
										return 0;
1331
									}
1332
								}
1333
							}
1334
1335
							return 1;
1336
						}
1337
						else
1338
						{
1339
							$this->db->rollback();
1340
							return -1;
1341
						}
1342
					}
1343
					else
1344
					{
1345
						$this->error=$this->db->lasterror()." - sql=$sql";
1346
						$this->db->rollback();
1347
						return -3;
1348
					}
1349
				}
1350
				else
1351
				{
1352
					$this->error=$this->db->lasterror()." - sql=$sql";
1353
					$this->db->rollback();
1354
					return -2;
1355
				}
1356
			}
1357
			else
1358
			{
1359
				$this->error=$this->db->lasterror()." - sql=$sql";
1360
				$this->db->rollback();
1361
				return -1;
1362
			}
1363
		}
1364
		else
1365
		{
1366
			$this->db->rollback();
1367
			return -1;
1368
		}
1369
	}
1370
1371
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1372
	/**
1373
	 *	Load lines
1374
	 *
1375
	 *	@return	int		>0 if OK, Otherwise if KO
1376
	 */
1377
	public function fetch_lines()
1378
	{
1379
        // phpcs:enable
1380
		global $conf, $mysoc;
1381
		// TODO: recuperer les champs du document associe a part
1382
1383
		$sql = "SELECT cd.rowid, cd.fk_product, cd.label as custom_label, cd.description, cd.qty as qty_asked, cd.product_type";
1384
		$sql.= ", cd.total_ht, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.total_tva";
1385
		$sql.= ", cd.vat_src_code, cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.info_bits, cd.price, cd.subprice, cd.remise_percent,cd.buy_price_ht as pa_ht";
1386
		$sql.= ", cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc";
1387
		$sql.= ", ed.rowid as line_id, ed.qty as qty_shipped, ed.fk_origin_line, ed.fk_entrepot";
1388
		$sql.= ", p.ref as product_ref, p.label as product_label, p.fk_product_type";
1389
		$sql.= ", p.weight, p.weight_units, p.length, p.length_units, p.surface, p.surface_units, p.volume, p.volume_units, p.tobatch as product_tobatch";
1390
		$sql.= " FROM ".MAIN_DB_PREFIX."expeditiondet as ed, ".MAIN_DB_PREFIX."commandedet as cd";
1391
		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = cd.fk_product";
1392
		$sql.= " WHERE ed.fk_expedition = ".$this->id;
1393
		$sql.= " AND ed.fk_origin_line = cd.rowid";
1394
		$sql.= " ORDER BY cd.rang, ed.fk_origin_line";
1395
1396
		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1397
		$resql = $this->db->query($sql);
1398
		if ($resql)
1399
		{
1400
			include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1401
1402
			$num = $this->db->num_rows($resql);
1403
			$i = 0;
1404
			$lineindex = 0;
1405
			$originline = 0;
1406
1407
			$this->total_ht = 0;
1408
			$this->total_tva = 0;
1409
			$this->total_ttc = 0;
1410
			$this->total_localtax1 = 0;
1411
			$this->total_localtax2 = 0;
1412
1413
			$line = new ExpeditionLigne($this->db);
1414
1415
			while ($i < $num)
1416
			{
1417
				$obj = $this->db->fetch_object($resql);
1418
1419
				if ($originline == $obj->fk_origin_line) {
1420
					$line->entrepot_id       = 0; // entrepod_id in details_entrepot
1421
					$line->qty_shipped    	+= $obj->qty_shipped;
1422
				} else {
1423
					$line = new ExpeditionLigne($this->db);
1424
					$line->entrepot_id    	= $obj->fk_entrepot;
1425
					$line->qty_shipped    	= $obj->qty_shipped;
1426
				}
1427
1428
				$detail_entrepot              = new stdClass;
1429
				$detail_entrepot->entrepot_id = $obj->fk_entrepot;
1430
				$detail_entrepot->qty_shipped = $obj->qty_shipped;
1431
				$detail_entrepot->line_id     = $obj->line_id;
1432
				$line->details_entrepot[]     = $detail_entrepot;
1433
1434
				$line->line_id          = $obj->line_id;
1435
				$line->rowid            = $obj->line_id;    // TODO deprecated
1436
				$line->id               = $obj->line_id;
1437
1438
				$line->fk_origin     	= 'orderline';
1439
				$line->fk_origin_line 	= $obj->fk_origin_line;
1440
				$line->origin_line_id 	= $obj->fk_origin_line;	    // TODO deprecated
1441
1442
				$line->fk_expedition    = $this->id;                // id of parent
1443
1444
				$line->product_type     = $obj->product_type;
1445
				$line->fk_product     	= $obj->fk_product;
1446
				$line->fk_product_type	= $obj->fk_product_type;
1447
				$line->ref				= $obj->product_ref;		// TODO deprecated
1448
				$line->product_ref		= $obj->product_ref;
1449
				$line->product_label	= $obj->product_label;
1450
				$line->libelle        	= $obj->product_label;		// TODO deprecated
1451
				$line->product_tobatch  = $obj->product_tobatch;
1452
				$line->label			= $obj->custom_label;
1453
				$line->description    	= $obj->description;
1454
				$line->qty_asked      	= $obj->qty_asked;
1455
				$line->weight         	= $obj->weight;
1456
				$line->weight_units   	= $obj->weight_units;
1457
				$line->length         	= $obj->length;
1458
				$line->length_units   	= $obj->length_units;
1459
				$line->surface        	= $obj->surface;
1460
				$line->surface_units   	= $obj->surface_units;
1461
				$line->volume         	= $obj->volume;
1462
				$line->volume_units   	= $obj->volume_units;
1463
1464
				$line->pa_ht 			= $obj->pa_ht;
1465
1466
				// Local taxes
1467
				$localtax_array=array(0=>$obj->localtax1_type, 1=>$obj->localtax1_tx, 2=>$obj->localtax2_type, 3=>$obj->localtax2_tx);
1468
				$localtax1_tx = get_localtax($obj->tva_tx, 1, $this->thirdparty);
1469
				$localtax2_tx = get_localtax($obj->tva_tx, 2, $this->thirdparty);
1470
1471
				// For invoicing
1472
				$tabprice = calcul_price_total($obj->qty_shipped, $obj->subprice, $obj->remise_percent, $obj->tva_tx, $localtax1_tx, $localtax2_tx, 0, 'HT', $obj->info_bits, $obj->fk_product_type, $mysoc, $localtax_array);	// We force type to 0
1473
				$line->desc	         	= $obj->description;		// We need ->desc because some code into CommonObject use desc (property defined for other elements)
1474
				$line->qty 				= $line->qty_shipped;
1475
				$line->total_ht			= $tabprice[0];
1476
				$line->total_localtax1 	= $tabprice[9];
1477
				$line->total_localtax2 	= $tabprice[10];
1478
				$line->total_ttc	 	= $tabprice[2];
1479
				$line->total_tva	 	= $tabprice[1];
1480
				$line->vat_src_code	 	= $obj->vat_src_code;
1481
				$line->tva_tx 		 	= $obj->tva_tx;
1482
				$line->localtax1_tx 	= $obj->localtax1_tx;
1483
				$line->localtax2_tx 	= $obj->localtax2_tx;
1484
				$line->info_bits        = $obj->info_bits;
1485
				$line->price			= $obj->price;
1486
				$line->subprice			= $obj->subprice;
1487
				$line->remise_percent	= $obj->remise_percent;
1488
1489
				$this->total_ht+= $tabprice[0];
1490
				$this->total_tva+= $tabprice[1];
1491
				$this->total_ttc+= $tabprice[2];
1492
				$this->total_localtax1+= $tabprice[9];
1493
				$this->total_localtax2+= $tabprice[10];
1494
1495
				// Multicurrency
1496
				$this->fk_multicurrency 		= $obj->fk_multicurrency;
1497
				$this->multicurrency_code 		= $obj->multicurrency_code;
1498
				$this->multicurrency_subprice 	= $obj->multicurrency_subprice;
1499
				$this->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
1500
				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
1501
				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
1502
1503
				if ($originline != $obj->fk_origin_line)
1504
				{
1505
					$line->detail_batch = array();
1506
				}
1507
1508
				// Detail of batch
1509
				if (! empty($conf->productbatch->enabled) && $obj->line_id > 0 && $obj->product_tobatch > 0)
1510
				{
1511
					require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
1512
1513
					$newdetailbatch = ExpeditionLineBatch::fetchAll($this->db, $obj->line_id, $obj->fk_product);
1514
					if (is_array($newdetailbatch))
1515
					{
1516
						if ($originline != $obj->fk_origin_line)
1517
						{
1518
							$line->detail_batch = $newdetailbatch;
1519
						}
1520
						else
1521
						{
1522
							$line->detail_batch = array_merge($line->detail_batch, $newdetailbatch);
1523
						}
1524
					}
1525
				}
1526
1527
				if ($originline != $obj->fk_origin_line)
1528
				{
1529
					$this->lines[$lineindex] = $line;
1530
					$lineindex++;
1531
				}
1532
				else
1533
				{
1534
					$line->total_ht			+= $tabprice[0];
1535
					$line->total_localtax1 	+= $tabprice[9];
1536
					$line->total_localtax2 	+= $tabprice[10];
1537
					$line->total_ttc	 	+= $tabprice[2];
1538
					$line->total_tva	 	+= $tabprice[1];
1539
				}
1540
1541
				$i++;
1542
				$originline = $obj->fk_origin_line;
1543
			}
1544
			$this->db->free($resql);
1545
			return 1;
1546
		}
1547
		else
1548
		{
1549
			$this->error=$this->db->error();
1550
			return -3;
1551
		}
1552
	}
1553
1554
	/**
1555
	 *  Delete detail line
1556
	 *
1557
	 *  @param		User	$user			User making deletion
1558
	 *  @param		int		$lineid			Id of line to delete
1559
	 *  @return     int         			>0 if OK, <0 if KO
1560
	 */
1561
	public function deleteline($user, $lineid)
1562
	{
1563
		global $user;
1564
1565
		if ($this->statut == self::STATUS_DRAFT)
1566
		{
1567
			$this->db->begin();
1568
1569
			$line=new ExpeditionLigne($this->db);
1570
1571
			// For triggers
1572
			$line->fetch($lineid);
1573
1574
			if ($line->delete($user) > 0)
1575
			{
1576
				//$this->update_price(1);
1577
1578
				$this->db->commit();
1579
				return 1;
1580
			}
1581
			else
1582
			{
1583
				$this->db->rollback();
1584
				return -1;
1585
			}
1586
		}
1587
		else
1588
		{
1589
			$this->error='ErrorDeleteLineNotAllowedByObjectStatus';
1590
			return -2;
1591
		}
1592
	}
1593
1594
1595
	/**
1596
	 *	Return clicable link of object (with eventually picto)
1597
	 *
1598
	 *	@param      int			$withpicto      			Add picto into link
1599
	 *	@param      string		$option         			Where the link point to
1600
	 *	@param      int			$max          				Max length to show
1601
	 *	@param      int			$short						Use short labels
1602
	 *  @param      int         $notooltip      			1=No tooltip
1603
	 *  @param      int     	$save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1604
	 *	@return     string          						String with URL
1605
	 */
1606
	public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1)
1607
	{
1608
		global $langs;
1609
1610
		$result='';
1611
		$label = '<u>' . $langs->trans("ShowSending") . '</u>';
1612
		$label .= '<br><b>' . $langs->trans('Ref') . ':</b> '.$this->ref;
1613
		$label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.($this->ref_customer ? $this->ref_customer : $this->ref_client);
0 ignored issues
show
Bug introduced by
The property ref_client does not exist on Expedition. Did you mean ref_int?
Loading history...
1614
1615
		$url = DOL_URL_ROOT.'/expedition/card.php?id='.$this->id;
1616
1617
		if ($short) return $url;
1618
1619
		if ($option !== 'nolink')
1620
		{
1621
			// Add param to save lastsearch_values or not
1622
			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1623
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1624
			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1625
		}
1626
1627
		$linkclose='';
1628
		if (empty($notooltip))
1629
		{
1630
			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conf seems to be never defined.
Loading history...
1631
			{
1632
				$label=$langs->trans("ShowSending");
1633
				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1634
			}
1635
			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1636
			$linkclose.=' class="classfortooltip"';
1637
		}
1638
1639
		$linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1640
		$linkend='</a>';
1641
1642
		$result .= $linkstart;
1643
		if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
1644
		if ($withpicto != 2) $result.= $this->ref;
1645
		$result .= $linkend;
1646
1647
		return $result;
1648
	}
1649
1650
	/**
1651
	 *	Return status label
1652
	 *
1653
	 *	@param      int		$mode      	0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
1654
	 *	@return     string      		Libelle
1655
	 */
1656
	public function getLibStatut($mode = 0)
1657
	{
1658
		return $this->LibStatut($this->statut, $mode);
1659
	}
1660
1661
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1662
	/**
1663
	 * Return label of a status
1664
	 *
1665
	 * @param      int		$statut		Id statut
1666
	 * @param      int		$mode       0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
1667
	 * @return     string				Label of status
1668
	 */
1669
	public function LibStatut($statut, $mode)
1670
	{
1671
        // phpcs:enable
1672
		global $langs;
1673
1674
		if ($mode==0)
1675
		{
1676
			if ($statut==0) return $langs->trans($this->statuts[$statut]);
1677
			elseif ($statut==1) return $langs->trans($this->statuts[$statut]);
1678
			elseif ($statut==2) return $langs->trans($this->statuts[$statut]);
1679
		}
1680
		elseif ($mode==1)
1681
		{
1682
			if ($statut==0) return $langs->trans($this->statutshorts[$statut]);
1683
			elseif ($statut==1) return $langs->trans($this->statutshorts[$statut]);
1684
			elseif ($statut==2) return $langs->trans($this->statutshorts[$statut]);
1685
		}
1686
		elseif ($mode == 3)
1687
		{
1688
			if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]), 'statut0');
1689
			elseif ($statut==1) return img_picto($langs->trans($this->statuts[$statut]), 'statut4');
1690
			elseif ($statut==2) return img_picto($langs->trans($this->statuts[$statut]), 'statut6');
1691
		}
1692
		elseif ($mode == 4)
1693
		{
1694
			if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]), 'statut0').' '.$langs->trans($this->statuts[$statut]);
1695
			elseif ($statut==1) return img_picto($langs->trans($this->statuts[$statut]), 'statut4').' '.$langs->trans($this->statuts[$statut]);
1696
			elseif ($statut==2) return img_picto($langs->trans($this->statuts[$statut]), 'statut6').' '.$langs->trans($this->statuts[$statut]);
1697
		}
1698
		elseif ($mode == 5)
1699
		{
1700
			if ($statut==0) return $langs->trans($this->statutshorts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]), 'statut0');
1701
			elseif ($statut==1) return $langs->trans($this->statutshorts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]), 'statut4');
1702
			elseif ($statut==2) return $langs->trans($this->statutshorts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]), 'statut6');
1703
		}
1704
	}
1705
1706
	/**
1707
	 *  Initialise an instance with random values.
1708
	 *  Used to build previews or test instances.
1709
	 *	id must be 0 if object instance is a specimen.
1710
	 *
1711
	 *  @return	void
1712
	 */
1713
	public function initAsSpecimen()
1714
	{
1715
		global $langs;
1716
1717
		$now=dol_now();
1718
1719
		dol_syslog(get_class($this)."::initAsSpecimen");
1720
1721
		// Load array of products prodids
1722
		$num_prods = 0;
1723
		$prodids = array();
1724
		$sql = "SELECT rowid";
1725
		$sql.= " FROM ".MAIN_DB_PREFIX."product";
1726
		$sql.= " WHERE entity IN (".getEntity('product').")";
1727
		$resql = $this->db->query($sql);
1728
		if ($resql)
1729
		{
1730
			$num_prods = $this->db->num_rows($resql);
1731
			$i = 0;
1732
			while ($i < $num_prods)
1733
			{
1734
				$i++;
1735
				$row = $this->db->fetch_row($resql);
1736
				$prodids[$i] = $row[0];
1737
			}
1738
		}
1739
1740
		$order=new Commande($this->db);
1741
		$order->initAsSpecimen();
1742
1743
		// Initialise parametres
1744
		$this->id=0;
1745
		$this->ref = 'SPECIMEN';
1746
		$this->specimen=1;
1747
		$this->statut               = self::STATUS_VALIDATED;
1748
		$this->livraison_id         = 0;
1749
		$this->date                 = $now;
1 ignored issue
show
Deprecated Code introduced by
The property Expedition::$date has been deprecated. ( Ignorable by Annotation )

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

1749
		/** @scrutinizer ignore-deprecated */ $this->date                 = $now;
Loading history...
1750
		$this->date_creation        = $now;
1751
		$this->date_valid           = $now;
1752
		$this->date_delivery        = $now;
1753
		$this->date_expedition      = $now + 24*3600;
1 ignored issue
show
Deprecated Code introduced by
The property Expedition::$date_expedition has been deprecated. ( Ignorable by Annotation )

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

1753
		/** @scrutinizer ignore-deprecated */ $this->date_expedition      = $now + 24*3600;
Loading history...
1754
1755
		$this->entrepot_id          = 0;
1756
		$this->fk_delivery_address  = 0;
1 ignored issue
show
Deprecated Code introduced by
The property CommonObject::$fk_delivery_address has been deprecated. ( Ignorable by Annotation )

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

1756
		/** @scrutinizer ignore-deprecated */ $this->fk_delivery_address  = 0;
Loading history...
1757
		$this->socid                = 1;
1758
1759
		$this->commande_id          = 0;
1760
		$this->commande             = $order;
1761
1762
		$this->origin_id            = 1;
1763
		$this->origin               = 'commande';
1764
1765
		$this->note_private			= 'Private note';
1766
		$this->note_public			= 'Public note';
1767
1768
		$nbp = 5;
1769
		$xnbp = 0;
1770
		while ($xnbp < $nbp)
1771
		{
1772
			$line=new ExpeditionLigne($this->db);
1773
			$line->desc=$langs->trans("Description")." ".$xnbp;
1 ignored issue
show
Deprecated Code introduced by
The property ExpeditionLigne::$desc has been deprecated. ( Ignorable by Annotation )

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

1773
			/** @scrutinizer ignore-deprecated */ $line->desc=$langs->trans("Description")." ".$xnbp;
Loading history...
1774
			$line->libelle=$langs->trans("Description")." ".$xnbp;
1 ignored issue
show
Deprecated Code introduced by
The property ExpeditionLigne::$libelle has been deprecated. ( Ignorable by Annotation )

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

1774
			/** @scrutinizer ignore-deprecated */ $line->libelle=$langs->trans("Description")." ".$xnbp;
Loading history...
1775
			$line->qty=10;
1776
			$line->qty_asked=5;
1777
			$line->qty_shipped=4;
1778
			$line->fk_product=$this->commande->lines[$xnbp]->fk_product;
1779
1780
			$this->lines[]=$line;
1781
			$xnbp++;
1782
		}
1783
	}
1784
1785
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1786
	/**
1787
	 *	Set the planned delivery date
1788
	 *
1789
	 *	@param      User			$user        		Objet user that modify
1790
	 *	@param      integer 		$date_livraison     Date of delivery
1791
	 *	@return     int         						<0 if KO, >0 if OK
1792
	 */
1793
	public function set_date_livraison($user, $date_livraison)
1794
	{
1795
        // phpcs:enable
1796
		if ($user->rights->expedition->creer)
1797
		{
1798
			$sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
1799
			$sql.= " SET date_delivery = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
1800
			$sql.= " WHERE rowid = ".$this->id;
1801
1802
			dol_syslog(get_class($this)."::set_date_livraison", LOG_DEBUG);
1803
			$resql=$this->db->query($sql);
1804
			if ($resql)
1805
			{
1806
				$this->date_delivery = $date_livraison;
1807
				return 1;
1808
			}
1809
			else
1810
			{
1811
				$this->error=$this->db->error();
1812
				return -1;
1813
			}
1814
		}
1815
		else
1816
		{
1817
			return -2;
1818
		}
1819
	}
1820
1821
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1822
	/**
1823
	 *	Fetch deliveries method and return an array. Load array this->meths(rowid=>label).
1824
	 *
1825
	 * 	@return	void
1826
	 */
1827
	public function fetch_delivery_methods()
1828
	{
1829
        // phpcs:enable
1830
		global $langs;
1831
		$this->meths = array();
1832
1833
		$sql = "SELECT em.rowid, em.code, em.libelle";
1834
		$sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
1835
		$sql.= " WHERE em.active = 1";
1836
		$sql.= " ORDER BY em.libelle ASC";
1837
1838
		$resql = $this->db->query($sql);
1839
		if ($resql)
1840
		{
1841
			while ($obj = $this->db->fetch_object($resql))
1842
			{
1843
				$label=$langs->trans('SendingMethod'.$obj->code);
1844
				$this->meths[$obj->rowid] = ($label != 'SendingMethod'.$obj->code?$label:$obj->libelle);
1845
			}
1846
		}
1847
	}
1848
1849
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1850
	/**
1851
	 *  Fetch all deliveries method and return an array. Load array this->listmeths.
1852
	 *
1853
	 *  @param  int      $id     only this carrier, all if none
1854
	 *  @return void
1855
	 */
1856
	public function list_delivery_methods($id = '')
1857
	{
1858
        // phpcs:enable
1859
		global $langs;
1860
1861
		$this->listmeths = array();
1862
		$i=0;
1863
1864
		$sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active";
1865
		$sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
1866
		if ($id!='') $sql.= " WHERE em.rowid=".$id;
1867
1868
		$resql = $this->db->query($sql);
1869
		if ($resql)
1870
		{
1871
			while ($obj = $this->db->fetch_object($resql))
1872
			{
1873
				$this->listmeths[$i]['rowid'] = $obj->rowid;
1874
				$this->listmeths[$i]['code'] = $obj->code;
1875
				$label=$langs->trans('SendingMethod'.$obj->code);
1876
				$this->listmeths[$i]['libelle'] = ($label != 'SendingMethod'.$obj->code?$label:$obj->libelle);
1877
				$this->listmeths[$i]['description'] = $obj->description;
1878
				$this->listmeths[$i]['tracking'] = $obj->tracking;
1879
				$this->listmeths[$i]['active'] = $obj->active;
1880
				$i++;
1881
			}
1882
		}
1883
	}
1884
1885
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1886
	/**
1887
	 *  Update/create delivery method.
1888
	 *
1889
	 *  @param	string      $id     id method to activate
1890
	 *
1891
	 *  @return void
1892
	 */
1893
	public function update_delivery_method($id = '')
1894
	{
1895
        // phpcs:enable
1896
		if ($id=='')
1897
		{
1898
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_shipment_mode (code, libelle, description, tracking)";
1899
			$sql.=" VALUES ('".$this->db->escape($this->update['code'])."','".$this->db->escape($this->update['libelle'])."','".$this->db->escape($this->update['description'])."','".$this->db->escape($this->update['tracking'])."')";
0 ignored issues
show
Bug Best Practice introduced by
The property update does not exist on Expedition. Did you maybe forget to declare it?
Loading history...
1900
			$resql = $this->db->query($sql);
1901
		}
1902
		else
1903
		{
1904
			$sql = "UPDATE ".MAIN_DB_PREFIX."c_shipment_mode SET";
1905
			$sql.= " code='".$this->db->escape($this->update['code'])."'";
1906
			$sql.= ",libelle='".$this->db->escape($this->update['libelle'])."'";
1907
			$sql.= ",description='".$this->db->escape($this->update['description'])."'";
1908
			$sql.= ",tracking='".$this->db->escape($this->update['tracking'])."'";
1909
			$sql.= " WHERE rowid=".$id;
1910
			$resql = $this->db->query($sql);
1911
		}
1912
		if ($resql < 0) dol_print_error($this->db, '');
1913
	}
1914
1915
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1916
	/**
1917
	 *  Activate delivery method.
1918
	 *
1919
	 *  @param      int      $id     id method to activate
1920
	 *  @return void
1921
	 */
1922
	public function activ_delivery_method($id)
1923
	{
1924
        // phpcs:enable
1925
		$sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=1';
1926
		$sql.= ' WHERE rowid='.$id;
1927
1928
		$resql = $this->db->query($sql);
1929
	}
1930
1931
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1932
	/**
1933
	 *  DesActivate delivery method.
1934
	 *
1935
	 *  @param      int      $id     id method to desactivate
1936
	 *
1937
	 *  @return void
1938
	 */
1939
	public function disable_delivery_method($id)
1940
	{
1941
        // phpcs:enable
1942
		$sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=0';
1943
		$sql.= ' WHERE rowid='.$id;
1944
1945
		$resql = $this->db->query($sql);
1946
	}
1947
1948
1949
	/**
1950
	 * Forge an set tracking url
1951
	 *
1952
	 * @param	string	$value		Value
1953
	 * @return	void
1954
	 */
1955
	public function getUrlTrackingStatus($value = '')
1956
	{
1957
		if (! empty($this->shipping_method_id))
1958
		{
1959
			$sql = "SELECT em.code, em.tracking";
1960
			$sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
1961
			$sql.= " WHERE em.rowid = ".$this->shipping_method_id;
1962
1963
			$resql = $this->db->query($sql);
1964
			if ($resql)
1965
			{
1966
				if ($obj = $this->db->fetch_object($resql))
1967
				{
1968
					$tracking = $obj->tracking;
1969
				}
1970
			}
1971
		}
1972
1973
		if (!empty($tracking) && !empty($value))
1974
		{
1975
			$url = str_replace('{TRACKID}', $value, $tracking);
1976
			$this->tracking_url = sprintf('<a target="_blank" href="%s">'.($value?$value:'url').'</a>', $url, $url);
1977
		}
1978
		else
1979
		{
1980
			$this->tracking_url = $value;
1981
		}
1982
	}
1983
1984
	/**
1985
	 *	Classify the shipping as closed.
1986
	 *
1987
	 *	@return     int     <0 if KO, >0 if OK
1988
	 */
1989
	public function setClosed()
1990
	{
1991
		global $conf,$langs,$user;
1992
1993
		$error=0;
1994
1995
		$this->db->begin();
1996
1997
		$sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut='.self::STATUS_CLOSED;
1998
		$sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0';
1999
2000
		$resql=$this->db->query($sql);
2001
		if ($resql)
2002
		{
2003
			// Set order billed if 100% of order is shipped (qty in shipment lines match qty in order lines)
2004
			if ($this->origin == 'commande' && $this->origin_id > 0)
2005
			{
2006
				$order = new Commande($this->db);
2007
				$order->fetch($this->origin_id);
2008
2009
				$order->loadExpeditions(self::STATUS_CLOSED);		// Fill $order->expeditions = array(orderlineid => qty)
2010
2011
				$shipments_match_order = 1;
2012
				foreach($order->lines as $line)
2013
				{
2014
					$lineid = $line->id;
2015
					$qty = $line->qty;
2016
					if (($line->product_type == 0 || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) && $order->expeditions[$lineid] != $qty)
2017
					{
2018
						$shipments_match_order = 0;
2019
						$text='Qty for order line id '.$lineid.' is '.$qty.'. However in the shipments with status Expedition::STATUS_CLOSED='.self::STATUS_CLOSED.' we have qty = '.$order->expeditions[$lineid].', so we can t close order';
2020
						dol_syslog($text);
2021
						break;
2022
					}
2023
				}
2024
				if ($shipments_match_order)
2025
				{
2026
					dol_syslog("Qty for the ".count($order->lines)." lines of order have same value for shipments with status Expedition::STATUS_CLOSED=".self::STATUS_CLOSED.', so we close order');
2027
					$order->cloture($user);
2028
				}
2029
			}
2030
2031
			$this->statut=self::STATUS_CLOSED;
2032
2033
2034
			// If stock increment is done on closing
2035
			if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE))
2036
			{
2037
				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2038
2039
				$langs->load("agenda");
2040
2041
				// Loop on each product line to add a stock movement
2042
				// TODO possibilite d'expedier a partir d'une propale ou autre origine ?
2043
				$sql = "SELECT cd.fk_product, cd.subprice,";
2044
				$sql.= " ed.rowid, ed.qty, ed.fk_entrepot,";
2045
				$sql.= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
2046
				$sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
2047
				$sql.= " ".MAIN_DB_PREFIX."expeditiondet as ed";
2048
				$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
2049
				$sql.= " WHERE ed.fk_expedition = ".$this->id;
2050
				$sql.= " AND cd.rowid = ed.fk_origin_line";
2051
2052
				dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
2053
				$resql=$this->db->query($sql);
2054
				if ($resql)
2055
				{
2056
					$cpt = $this->db->num_rows($resql);
2057
					for ($i = 0; $i < $cpt; $i++)
2058
					{
2059
						$obj = $this->db->fetch_object($resql);
2060
						if (empty($obj->edbrowid))
2061
						{
2062
							$qty = $obj->qty;
2063
						}
2064
						else
2065
						{
2066
							$qty = $obj->edbqty;
2067
						}
2068
						if ($qty <= 0) continue;
2069
						dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
2070
2071
						$mouvS = new MouvementStock($this->db);
2072
						$mouvS->origin = &$this;
2073
2074
						if (empty($obj->edbrowid))
2075
						{
2076
							// line without batch detail
2077
2078
							// We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2079
							$result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentClassifyClosedInDolibarr", $numref));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $numref seems to be never defined.
Loading history...
2080
							if ($result < 0) {
2081
								$this->error = $mouvS->error;
2082
								$this->errors = $mouvS->errors;
2083
								$error++; break;
2084
							}
2085
						}
2086
						else
2087
						{
2088
							// line with batch detail
2089
2090
							// We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2091
							$result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentClassifyClosedInDolibarr", $numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock);
2092
							if ($result < 0) {
2093
								$this->error = $mouvS->error;
2094
								$this->errors = $mouvS->errors;
2095
								$error++; break;
2096
							}
2097
						}
2098
					}
2099
				}
2100
				else
2101
				{
2102
					$this->error=$this->db->lasterror();
2103
					$error++;
2104
				}
2105
			}
2106
2107
			// Call trigger
2108
			if (! $error)
2109
			{
2110
				$result=$this->call_trigger('SHIPPING_CLOSED', $user);
2111
				if ($result < 0) {
2112
					$error++;
2113
				}
2114
			}
2115
		}
2116
		else
2117
		{
2118
			dol_print_error($this->db);
2119
			$error++;
2120
		}
2121
2122
		if (! $error)
2123
		{
2124
			$this->db->commit();
2125
			return 1;
2126
		}
2127
		else
2128
		{
2129
			$this->statut = self::STATUS_VALIDATED;
2130
			$this->db->rollback();
2131
			return -1;
2132
		}
2133
	}
2134
2135
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2136
	/**
2137
	 *	Classify the shipping as invoiced (used when WORKFLOW_BILL_ON_SHIPMENT is on)
2138
	 *
2139
	 *	@return     int     <0 if ko, >0 if ok
2140
	 */
2141
	public function set_billed()
2142
	{
2143
        // phpcs:enable
2144
		global $user;
2145
		$error=0;
2146
2147
		$this->db->begin();
2148
2149
		$sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut=2, billed=1';    // TODO Update only billed
2150
		$sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0';
2151
2152
		$resql=$this->db->query($sql);
2153
		if ($resql)
2154
		{
2155
			$this->statut=self::STATUS_CLOSED;
2156
			$this->billed=1;
2157
2158
			// Call trigger
2159
			$result=$this->call_trigger('SHIPPING_BILLED', $user);
2160
			if ($result < 0) {
2161
				$error++;
2162
			}
2163
		} else {
2164
			$error++;
2165
			$this->errors[]=$this->db->lasterror;
2166
		}
2167
2168
		if (empty($error)) {
2169
			$this->db->commit();
2170
			return 1;
2171
		}
2172
		else
2173
		{
2174
			$this->statut=self::STATUS_VALIDATED;
2175
			$this->billed=0;
2176
			$this->db->rollback();
2177
			return -1;
2178
		}
2179
	}
2180
2181
	/**
2182
	 *	Classify the shipping as validated/opened
2183
	 *
2184
	 *	@return     int     <0 if KO, 0 if already open, >0 if OK
2185
	 */
2186
	public function reOpen()
2187
	{
2188
		global $conf,$langs,$user;
2189
2190
		$error=0;
2191
2192
		// Protection. This avoid to move stock later when we should not
2193
		if ($this->statut == self::STATUS_VALIDATED)
2194
		{
2195
			return 0;
2196
		}
2197
2198
		$this->db->begin();
2199
2200
		$oldbilled=$this->billed;
2201
2202
		$sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut=1';
2203
		$sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0';
2204
2205
		$resql=$this->db->query($sql);
2206
		if ($resql)
2207
		{
2208
			$this->statut=self::STATUS_VALIDATED;
2209
			$this->billed=0;
2210
2211
			// If stock increment is done on closing
2212
			if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE))
2213
			{
2214
				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2215
2216
				$langs->load("agenda");
2217
2218
				// Loop on each product line to add a stock movement
2219
				// TODO possibilite d'expedier a partir d'une propale ou autre origine
2220
				$sql = "SELECT cd.fk_product, cd.subprice,";
2221
				$sql.= " ed.rowid, ed.qty, ed.fk_entrepot,";
2222
				$sql.= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
2223
				$sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
2224
				$sql.= " ".MAIN_DB_PREFIX."expeditiondet as ed";
2225
				$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
2226
				$sql.= " WHERE ed.fk_expedition = ".$this->id;
2227
				$sql.= " AND cd.rowid = ed.fk_origin_line";
2228
2229
				dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
2230
				$resql=$this->db->query($sql);
2231
				if ($resql)
2232
				{
2233
					$cpt = $this->db->num_rows($resql);
2234
					for ($i = 0; $i < $cpt; $i++)
2235
					{
2236
						$obj = $this->db->fetch_object($resql);
2237
						if (empty($obj->edbrowid))
2238
						{
2239
							$qty = $obj->qty;
2240
						}
2241
						else
2242
						{
2243
							$qty = $obj->edbqty;
2244
						}
2245
						if ($qty <= 0) continue;
2246
						dol_syslog(get_class($this)."::reopen expedition movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
2247
2248
						//var_dump($this->lines[$i]);
2249
						$mouvS = new MouvementStock($this->db);
2250
						$mouvS->origin = &$this;
2251
2252
						if (empty($obj->edbrowid))
2253
						{
2254
							// line without batch detail
2255
2256
							// We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2257
							$result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr", $numref));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $numref seems to be never defined.
Loading history...
2258
							if ($result < 0) {
2259
								$this->error = $mouvS->error;
2260
								$this->errors = $mouvS->errors;
2261
								$error++; break;
2262
							}
2263
						}
2264
						else
2265
						{
2266
							// line with batch detail
2267
2268
							// We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
2269
							$result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr", $numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock);
2270
							if ($result < 0) {
2271
								$this->error = $mouvS->error;
2272
								$this->errors = $mouvS->errors;
2273
								$error++; break;
2274
							}
2275
						}
2276
					}
2277
				}
2278
				else
2279
				{
2280
					$this->error=$this->db->lasterror();
2281
					$error++;
2282
				}
2283
			}
2284
2285
            if (! $error) {
2286
				// Call trigger
2287
				$result=$this->call_trigger('SHIPPING_REOPEN', $user);
2288
				if ($result < 0) {
2289
					$error++;
2290
				}
2291
            }
2292
		} else {
2293
			$error++;
2294
			$this->errors[]=$this->db->lasterror();
2295
		}
2296
2297
		if (! $error)
2298
		{
2299
			$this->db->commit();
2300
			return 1;
2301
		}
2302
		else
2303
		{
2304
			$this->statut=self::STATUS_CLOSED;
2305
			$this->billed=$oldbilled;
2306
			$this->db->rollback();
2307
			return -1;
2308
		}
2309
	}
2310
2311
	/**
2312
	 *  Create a document onto disk according to template module.
2313
	 *
2314
	 *  @param	    string		$modele			Force the model to using ('' to not force)
2315
	 *  @param		Translate	$outputlangs	object lang to use for translations
2316
	 *  @param      int			$hidedetails    Hide details of lines
2317
	 *  @param      int			$hidedesc       Hide description
2318
	 *  @param      int			$hideref        Hide ref
2319
     *  @param      null|array  $moreparams     Array to provide more information
2320
	 *  @return     int         				0 if KO, 1 if OK
2321
	 */
2322
	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2323
	{
2324
		global $conf,$langs;
2325
2326
		$langs->load("sendings");
2327
2328
		if (! dol_strlen($modele)) {
2329
2330
			$modele = 'rouget';
2331
2332
			if ($this->modelpdf) {
2333
				$modele = $this->modelpdf;
2334
			} elseif (! empty($conf->global->EXPEDITION_ADDON_PDF)) {
2335
				$modele = $conf->global->EXPEDITION_ADDON_PDF;
2336
			}
2337
		}
2338
2339
		$modelpath = "core/modules/expedition/doc/";
2340
2341
		$this->fetch_origin();
2342
2343
		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2344
	}
2345
2346
	/**
2347
	 * Function used to replace a thirdparty id with another one.
2348
	 *
2349
	 * @param DoliDB $db Database handler
2350
	 * @param int $origin_id Old thirdparty id
2351
	 * @param int $dest_id New thirdparty id
2352
	 * @return bool
2353
	 */
2354
	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
2355
	{
2356
		$tables = array(
2357
			'expedition'
2358
		);
2359
2360
		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2361
	}
2362
}
2363
2364
2365
/**
2366
 * Classe to manage lines of shipment
2367
 */
2368
class ExpeditionLigne extends CommonObjectLine
2369
{
2370
	/**
2371
	 * @var string ID to identify managed object
2372
	 */
2373
	public $element='expeditiondet';
2374
2375
	/**
2376
	 * @var string Name of table without prefix where object is stored
2377
	 */
2378
	public $table_element='expeditiondet';
2379
2380
	/**
2381
	 * @deprecated
2382
	 * @see $fk_origin_line
2383
	 */
2384
	public $origin_line_id;
2385
2386
	/**
2387
     * @var int ID
2388
     */
2389
	public $fk_origin_line;
2390
2391
	/**
2392
	 * @var int Id of shipment
2393
	 */
2394
	public $fk_expedition;
2395
2396
	/**
2397
     * @var DoliDB Database handler.
2398
     */
2399
    public $db;
2400
2401
    /**
2402
     * @var float qty asked From llx_expeditiondet
2403
     */
2404
    public $qty;
2405
2406
    /**
2407
     * @var float qty shipped
2408
     */
2409
    public $qty_shipped;
2410
2411
    /**
2412
     * @var int Id of product
2413
     */
2414
    public $fk_product;
2415
    public $detail_batch;
2416
2417
    /**
2418
     * @var int Id of warehouse
2419
     */
2420
	public $entrepot_id;
2421
2422
2423
    /**
2424
     * @var float qty asked From llx_commandedet or llx_propaldet
2425
     */
2426
	public $qty_asked;
2427
2428
    /**
2429
     * @deprecated
2430
     * @see $product_ref
2431
     */
2432
    public $ref;
2433
2434
	/**
2435
	 * @var string product ref
2436
	 */
2437
	public $product_ref;
2438
2439
	/**
2440
	 * @deprecated
2441
	 * @see $product_label
2442
	 */
2443
	public $libelle;
2444
2445
    /**
2446
     * @var string product label
2447
     */
2448
	public $product_label;
2449
2450
    /**
2451
     * @var string product description
2452
     * @deprecated
2453
     * @see $product_desc
2454
     */
2455
    public $desc;
2456
2457
    /**
2458
     * @var string product description
2459
     */
2460
	public $product_desc;
2461
2462
    /**
2463
     * @var float weight
2464
     */
2465
    public $weight;
2466
    public $weight_units;
2467
2468
    /**
2469
     * @var float weight
2470
     */
2471
    public $length;
2472
    public $length_units;
2473
2474
    /**
2475
     * @var float weight
2476
     */
2477
    public $surface;
2478
    public $surface_units;
2479
2480
    /**
2481
     * @var float weight
2482
     */
2483
    public $volume;
2484
    public $volume_units;
2485
2486
	// Invoicing
2487
	public $remise_percent;
2488
    public $tva_tx;
2489
2490
    /**
2491
     * @var float total without tax
2492
     */
2493
    public $total_ht;
2494
2495
    /**
2496
     * @var float total with tax
2497
     */
2498
    public $total_ttc;
2499
2500
    /**
2501
     * @var float total vat
2502
     */
2503
    public $total_tva;
2504
2505
    /**
2506
     * @var float total localtax 1
2507
     */
2508
    public $total_localtax1;
2509
2510
    /**
2511
     * @var float total localtax 2
2512
     */
2513
    public $total_localtax2;
2514
2515
2516
    /**
2517
     *	Constructor
2518
     *
2519
     *  @param		DoliDB		$db      Database handler
2520
     */
2521
	public function __construct($db)
2522
	{
2523
		$this->db=$db;
2524
	}
2525
2526
	/**
2527
	 *  Load line expedition
2528
	 *
2529
	 *  @param  int		$rowid          Id line order
2530
	 *  @return	int						<0 if KO, >0 if OK
2531
	 */
2532
	public function fetch($rowid)
2533
	{
2534
		$sql = 'SELECT ed.rowid, ed.fk_expedition, ed.fk_entrepot, ed.fk_origin_line, ed.qty, ed.rang';
2535
		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as ed';
2536
		$sql.= ' WHERE ed.rowid = '.$rowid;
2537
		$result = $this->db->query($sql);
2538
		if ($result)
2539
		{
2540
			$objp = $this->db->fetch_object($result);
2541
			$this->id				= $objp->rowid;
2542
			$this->fk_expedition	= $objp->fk_expedition;
2543
			$this->entrepot_id		= $objp->fk_entrepot;
2544
			$this->fk_origin_line	= $objp->fk_origin_line;
2545
			$this->qty				= $objp->qty;
2546
			$this->rang				= $objp->rang;
2547
2548
			$this->db->free($result);
2549
2550
			return 1;
2551
		}
2552
		else
2553
		{
2554
			$this->errors[] = $this->db->lasterror();
2555
			$this->error = $this->db->lasterror();
2556
			return -1;
2557
		}
2558
	}
2559
2560
	/**
2561
	 *	Insert line into database
2562
	 *
2563
	 *	@param      User	$user			User that modify
2564
	 *	@param      int		$notrigger		1 = disable triggers
2565
	 *	@return     int						<0 if KO, line id >0 if OK
2566
	 */
2567
	public function insert($user, $notrigger = 0)
2568
	{
2569
		global $langs, $conf;
2570
2571
		$error=0;
2572
2573
		// Check parameters
2574
		if (empty($this->fk_expedition) || empty($this->fk_origin_line) || ! is_numeric($this->qty))
2575
		{
2576
			$this->error = 'ErrorMandatoryParametersNotProvided';
2577
			return -1;
2578
		}
2579
2580
		$this->db->begin();
2581
2582
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."expeditiondet (";
2583
		$sql.= "fk_expedition";
2584
		$sql.= ", fk_entrepot";
2585
		$sql.= ", fk_origin_line";
2586
		$sql.= ", qty";
2587
		$sql.= ") VALUES (";
2588
		$sql.= $this->fk_expedition;
2589
		$sql.= ", ".(empty($this->entrepot_id) ? 'NULL' : $this->entrepot_id);
2590
		$sql.= ", ".$this->fk_origin_line;
2591
		$sql.= ", ".$this->qty;
2592
		$sql.= ")";
2593
2594
		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
2595
		$resql = $this->db->query($sql);
2596
		if ($resql)
2597
		{
2598
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expeditiondet");
2599
2600
			if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))
2601
			{
2602
				$result=$this->insertExtraFields();
2603
				if ($result < 0)
2604
				{
2605
					$error++;
2606
				}
2607
			}
2608
2609
			if (! $error && ! $notrigger)
2610
			{
2611
				// Call trigger
2612
				$result=$this->call_trigger('LINESHIPPING_INSERT', $user);
2613
				if ($result < 0)
2614
				{
2615
					$error++;
2616
				}
2617
				// End call triggers
2618
			}
2619
2620
			if (! $error) {
2621
				$this->db->commit();
2622
				return $this->id;
2623
			}
2624
2625
			foreach($this->errors as $errmsg)
2626
			{
2627
				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
2628
				$this->error.=($this->error?', '.$errmsg:$errmsg);
2629
			}
2630
2631
			$this->db->rollback();
2632
			return -1*$error;
2633
		}
2634
		else
2635
		{
2636
			$error++;
2637
		}
2638
	}
2639
2640
	/**
2641
	 * 	Delete shipment line.
2642
	 *
2643
	 *	@param		User	$user			User that modify
2644
	 *	@param		int		$notrigger		0=launch triggers after, 1=disable triggers
2645
	 * 	@return		int		>0 if OK, <0 if KO
2646
	 */
2647
	public function delete($user = null, $notrigger = 0)
2648
	{
2649
		global $conf;
2650
2651
		$error=0;
2652
2653
		$this->db->begin();
2654
2655
		// delete batch expedition line
2656
		if ($conf->productbatch->enabled)
2657
		{
2658
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch";
2659
			$sql.= " WHERE fk_expeditiondet = ".$this->id;
2660
2661
			if (!$this->db->query($sql))
2662
			{
2663
				$this->errors[]=$this->db->lasterror()." - sql=$sql";
2664
				$error++;
2665
			}
2666
		}
2667
2668
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet";
2669
		$sql.= " WHERE rowid = ".$this->id;
2670
2671
		if (! $error && $this->db->query($sql))
2672
		{
2673
			// Remove extrafields
2674
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2675
			{
2676
				$result=$this->deleteExtraFields();
2677
				if ($result < 0)
2678
				{
2679
					$this->errors[]=$this->error;
2680
					$error++;
2681
				}
2682
			}
2683
			if (! $error && ! $notrigger)
2684
			{
2685
				// Call trigger
2686
				$result=$this->call_trigger('LINESHIPPING_DELETE', $user);
2687
				if ($result < 0)
2688
				{
2689
					$this->errors[]=$this->error;
2690
					$error++;
2691
				}
2692
				// End call triggers
2693
			}
2694
		}
2695
		else
2696
		{
2697
			$this->errors[]=$this->db->lasterror()." - sql=$sql";
2698
			$error++;
2699
		}
2700
2701
		if (! $error) {
2702
			$this->db->commit();
2703
			return 1;
2704
		}
2705
		else
2706
		{
2707
			foreach($this->errors as $errmsg)
2708
			{
2709
				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
2710
				$this->error.=($this->error?', '.$errmsg:$errmsg);
2711
			}
2712
			$this->db->rollback();
2713
			return -1*$error;
2714
		}
2715
	}
2716
2717
	/**
2718
	 *  Update a line in database
2719
	 *
2720
	 *	@param		User	$user			User that modify
2721
	 *	@param		int		$notrigger		1 = disable triggers
2722
	 *  @return		int					< 0 if KO, > 0 if OK
2723
	 */
2724
	public function update($user = null, $notrigger = 0)
2725
	{
2726
		global $conf;
2727
2728
		$error=0;
2729
2730
		dol_syslog(get_class($this)."::update id=$this->id, entrepot_id=$this->entrepot_id, product_id=$this->fk_product, qty=$this->qty");
2731
2732
		$this->db->begin();
2733
2734
		// Clean parameters
2735
		if (empty($this->qty)) $this->qty=0;
2736
		$qty=price2num($this->qty);
2737
		$remainingQty = 0;
2738
		$batch = null;
2739
		$batch_id = null;
2740
		$expedition_batch_id = null;
2741
		if (is_array($this->detail_batch)) 	// array of ExpeditionLineBatch
2742
		{
2743
			if (count($this->detail_batch) > 1)
2744
			{
2745
				dol_syslog(get_class($this).'::update only possible for one batch', LOG_ERR);
2746
				$this->errors[]='ErrorBadParameters';
2747
				$error++;
2748
			}
2749
			else
2750
			{
2751
				$batch = $this->detail_batch[0]->batch;
2752
				$batch_id = $this->detail_batch[0]->fk_origin_stock;
2753
				$expedition_batch_id = $this->detail_batch[0]->id;
2754
				if ($this->entrepot_id != $this->detail_batch[0]->entrepot_id)
2755
				{
2756
					dol_syslog(get_class($this).'::update only possible for batch of same warehouse', LOG_ERR);
2757
					$this->errors[]='ErrorBadParameters';
2758
					$error++;
2759
				}
2760
				$qty = price2num($this->detail_batch[0]->qty);
2761
			}
2762
		}
2763
		elseif (! empty($this->detail_batch))
2764
		{
2765
			$batch = $this->detail_batch->batch;
2766
			$batch_id = $this->detail_batch->fk_origin_stock;
2767
			$expedition_batch_id = $this->detail_batch->id;
2768
			if ($this->entrepot_id != $this->detail_batch->entrepot_id)
2769
			{
2770
				dol_syslog(get_class($this).'::update only possible for batch of same warehouse', LOG_ERR);
2771
				$this->errors[]='ErrorBadParameters';
2772
				$error++;
2773
			}
2774
			$qty = price2num($this->detail_batch->qty);
2775
		}
2776
2777
		// check parameters
2778
		if (! isset($this->id) || ! isset($this->entrepot_id))
2779
		{
2780
			dol_syslog(get_class($this).'::update missing line id and/or warehouse id', LOG_ERR);
2781
			$this->errors[]='ErrorMandatoryParametersNotProvided';
2782
			$error++;
2783
			return -1;
2784
		}
2785
2786
		// update lot
2787
2788
		if (! empty($batch) && $conf->productbatch->enabled)
2789
		{
2790
			dol_syslog(get_class($this)."::update expedition batch id=$expedition_batch_id, batch_id=$batch_id, batch=$batch");
2791
2792
			if (empty($batch_id) || empty($this->fk_product)) {
2793
				dol_syslog(get_class($this).'::update missing fk_origin_stock (batch_id) and/or fk_product', LOG_ERR);
2794
				$this->errors[]='ErrorMandatoryParametersNotProvided';
2795
				$error++;
2796
			}
2797
2798
			// fetch remaining lot qty
2799
			require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
2800
			if (! $error && ($lotArray = ExpeditionLineBatch::fetchAll($this->db, $this->id)) < 0)
2801
			{
2802
				$this->errors[]=$this->db->lasterror()." - ExpeditionLineBatch::fetchAll";
2803
				$error++;
2804
			}
2805
			else
2806
			{
2807
				// caculate new total line qty
2808
				foreach ($lotArray as $lot)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $lotArray does not seem to be defined for all execution paths leading up to this point.
Loading history...
2809
				{
2810
					if ($expedition_batch_id != $lot->id)
2811
					{
2812
						$remainingQty += $lot->qty;
2813
					}
2814
				}
2815
				$qty += $remainingQty;
2816
2817
				//fetch lot details
2818
2819
				// fetch from product_lot
2820
				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
2821
				$lot = new Productlot($this->db);
2822
				if ($lot->fetch(0, $this->fk_product, $batch) < 0)
2823
				{
2824
					$this->errors[] = $lot->errors;
2825
					$error++;
2826
				}
2827
				if (! $error && ! empty($expedition_batch_id))
2828
				{
2829
					// delete lot expedition line
2830
					$sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch";
2831
					$sql.= " WHERE fk_expeditiondet = ".$this->id;
2832
					$sql.= " AND rowid = ".$expedition_batch_id;
2833
2834
					if (!$this->db->query($sql))
2835
					{
2836
						$this->errors[]=$this->db->lasterror()." - sql=$sql";
2837
						$error++;
2838
					}
2839
				}
2840
				if (! $error && $this->detail_batch->qty > 0)
2841
				{
2842
					// create lot expedition line
2843
					if (isset($lot->id))
2844
					{
2845
						$shipmentLot = new ExpeditionLineBatch($this->db);
2846
						$shipmentLot->batch = $lot->batch;
2847
						$shipmentLot->eatby = $lot->eatby;
2848
						$shipmentLot->sellby = $lot->sellby;
2849
						$shipmentLot->entrepot_id = $this->detail_batch->entrepot_id;
2850
						$shipmentLot->qty = $this->detail_batch->qty;
2851
						$shipmentLot->fk_origin_stock = $batch_id;
2852
						if ($shipmentLot->create($this->id) < 0)
2853
						{
2854
							$this->errors[]=$shipmentLot->errors;
2855
							$error++;
2856
						}
2857
					}
2858
				}
2859
			}
2860
		}
2861
		if (! $error)
2862
		{
2863
			// update line
2864
			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
2865
			$sql.= " fk_entrepot = ".($this->entrepot_id > 0 ? $this->entrepot_id : 'null');
2866
			$sql.= " , qty = ".$qty;
2867
			$sql.= " WHERE rowid = ".$this->id;
2868
2869
			if (!$this->db->query($sql))
2870
			{
2871
				$this->errors[]=$this->db->lasterror()." - sql=$sql";
2872
				$error++;
2873
			}
2874
		}
2875
2876
		if (! $error)
2877
		{
2878
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
2879
			{
2880
				$result=$this->insertExtraFields();
2881
				if ($result < 0)
2882
				{
2883
					$this->errors[]=$this->error;
2884
					$error++;
2885
				}
2886
			}
2887
		}
2888
2889
		if (! $error && ! $notrigger)
2890
		{
2891
			// Call trigger
2892
			$result=$this->call_trigger('LINESHIPPING_UPDATE', $user);
2893
			if ($result < 0)
2894
			{
2895
				$this->errors[]=$this->error;
2896
				$error++;
2897
			}
2898
			// End call triggers
2899
		}
2900
		if (!$error) {
2901
			$this->db->commit();
2902
			return 1;
2903
		}
2904
		else
2905
		{
2906
			foreach($this->errors as $errmsg)
2907
			{
2908
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2909
				$this->error.=($this->error?', '.$errmsg:$errmsg);
2910
			}
2911
			$this->db->rollback();
2912
			return -1*$error;
2913
		}
2914
	}
2915
}
2916