Passed
Branch develop (6dcba0)
by
unknown
30:53
created

MoLine::fetchLinesLinked()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2017  Laurent Destailleur <[email protected]>
3
 * Copyright (C) ---Put here your own copyright and developer email---
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
/**
20
 * \file        class/mo.class.php
21
 * \ingroup     mrp
22
 * \brief       This file is a CRUD class file for Mo (Create/Read/Update/Delete)
23
 */
24
25
// Put here all includes required by your class file
26
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
27
//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
28
//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
29
30
/**
31
 * Class for Mo
32
 */
33
class Mo extends CommonObject
34
{
35
	/**
36
	 * @var string ID to identify managed object
37
	 */
38
	public $element = 'mo';
39
40
	/**
41
	 * @var string Name of table without prefix where object is stored
42
	 */
43
	public $table_element = 'mrp_mo';
44
45
	/**
46
	 * @var int  Does mo support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
47
	 */
48
	public $ismultientitymanaged = 0;
49
50
	/**
51
	 * @var int  Does mo support extrafields ? 0=No, 1=Yes
52
	 */
53
	public $isextrafieldmanaged = 1;
54
55
	/**
56
	 * @var string String with name of icon for mo. Must be the part after the 'object_' into object_mo.png
57
	 */
58
	public $picto = 'mrp';
59
60
61
	const STATUS_DRAFT = 0;
62
	const STATUS_VALIDATED = 1; // To produce
63
	const STATUS_INPROGRESS = 2;
64
	const STATUS_PRODUCED = 3;
65
	const STATUS_CANCELED = -1;
66
67
68
69
	/**
70
	 *  'type' if the field format ('integer', 'integer:Class:pathtoclass', 'varchar(x)', 'double(24,8)', 'text', 'html', 'datetime', 'timestamp', 'float')
71
	 *  'label' the translation key.
72
	 *  'enabled' is a condition when the field must be managed.
73
	 *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). Using a negative value means field is not shown by default on list but can be selected for viewing)
74
	 *  'noteditable' says if field is not editable (1 or 0)
75
	 *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
76
	 *  'default' is a default value for creation (can still be replaced by the global setup of default values)
77
	 *  'index' if we want an index in database.
78
	 *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
79
	 *  'position' is the sort order of field.
80
	 *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
81
	 *  'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
82
	 *  'css' is the CSS style to use on field. For example: 'maxwidth200'
83
	 *  'help' is a string visible as a tooltip on field
84
	 *  'comment' is not used. You can store here any text of your choice. It is not used by application.
85
	 *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
86
	 *  'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
87
	 */
88
89
	// BEGIN MODULEBUILDER PROPERTIES
90
	/**
91
	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
92
	 */
93
	public $fields = array(
94
		'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",),
95
		'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'position'=>5, 'notnull'=>1, 'default'=>'1', 'index'=>1),
96
		'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>4, 'position'=>10, 'notnull'=>1, 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'showoncombobox'=>'1', 'noteditable'=>1),
97
		'fk_bom' => array('type'=>'integer:Bom:bom/class/bom.class.php:0:t.status=1', 'filter'=>'active=1', 'label'=>'BOM', 'enabled'=>1, 'visible'=>1, 'position'=>33, 'notnull'=>-1, 'index'=>1, 'comment'=>"Original BOM",),
98
		'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:0', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'comment'=>"Product to produce"),
99
		'qty' => array('type'=>'real', 'label'=>'QtyToProduce', 'enabled'=>1, 'visible'=>1, 'position'=>40, 'notnull'=>1, 'comment'=>"Qty to produce", 'css'=>'width75'),
100
		'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>42, 'notnull'=>-1, 'searchall'=>1, 'showoncombobox'=>'1',),
101
		'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'position'=>50, 'notnull'=>-1, 'index'=>1),
102
	    'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label'=>'WarehouseForProduction', 'enabled'=>1, 'visible'=>-1, 'position'=>52),
103
	    'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'notnull'=>-1,),
104
		'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62, 'notnull'=>-1,),
105
		'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>500, 'notnull'=>1,),
106
		'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'position'=>501, 'notnull'=>-1,),
107
		'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>510, 'notnull'=>1, 'foreignkey'=>'user.rowid',),
108
		'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'position'=>511, 'notnull'=>-1,),
109
		'date_start_planned' => array('type'=>'datetime', 'label'=>'DateStartPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>55, 'notnull'=>-1, 'index'=>1, 'help'=>'KeepEmptyForAsap'),
110
		'date_end_planned' => array('type'=>'datetime', 'label'=>'DateEndPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>56, 'notnull'=>-1, 'index'=>1,),
111
		'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>52, 'notnull'=>-1, 'index'=>1,),
112
		'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,),
113
		'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
114
		'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>2, 'position'=>1000, 'default'=>0, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Brouillon', '1'=>'Validated', '2'=>'InProgress', '3'=>'StatusMOProduced', '-1'=>'Canceled')),
115
	);
116
	public $rowid;
117
	public $ref;
118
	public $entity;
119
	public $label;
120
	public $qty;
121
	public $fk_warehouse;
122
	public $fk_soc;
123
124
	/**
125
	 * @var string public note
126
	 */
127
	public $note_public;
128
129
	/**
130
	 * @var string private note
131
	 */
132
	public $note_private;
133
134
	/**
135
	 * @var integer|string date_creation
136
	 */
137
	public $date_creation;
138
139
140
	public $tms;
141
	public $fk_user_creat;
142
	public $fk_user_modif;
143
	public $import_key;
144
	public $status;
145
	public $fk_product;
146
147
	/**
148
	 * @var integer|string date_start_planned
149
	 */
150
	public $date_start_planned;
151
152
	/**
153
	 * @var integer|string date_end_planned
154
	 */
155
	public $date_end_planned;
156
157
158
	public $fk_bom;
159
	public $fk_project;
160
	// END MODULEBUILDER PROPERTIES
161
162
163
	// If this object has a subtable with lines
164
165
	/**
166
	 * @var int    Name of subtable line
167
	 */
168
	public $table_element_line = 'mo_production';
169
170
	/**
171
	 * @var int    Field with ID of parent key if this field has a parent
172
	 */
173
	public $fk_element = 'fk_mo';
174
175
	/**
176
	 * @var int    Name of subtable class that manage subtable lines
177
	 */
178
	public $class_element_line = 'MoLine';
179
180
	/**
181
	 * @var array	List of child tables. To test if we can delete object.
182
	 */
183
	protected $childtables = array();
184
185
	/**
186
	 * @var array	List of child tables. To know object to delete on cascade.
187
	 */
188
	protected $childtablesoncascade = array('mrp_production');
189
190
	/**
191
	 * @var MoLine[]     Array of subtable lines
192
	 */
193
	public $lines = array();
194
195
196
197
	/**
198
	 * Constructor
199
	 *
200
	 * @param DoliDb $db Database handler
201
	 */
202
	public function __construct(DoliDB $db)
203
	{
204
		global $conf, $langs;
205
206
		$this->db = $db;
207
208
		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
209
		if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0;
210
211
		// Unset fields that are disabled
212
		foreach ($this->fields as $key => $val)
213
		{
214
			if (isset($val['enabled']) && empty($val['enabled']))
215
			{
216
				unset($this->fields[$key]);
217
			}
218
		}
219
220
		// Translate some data of arrayofkeyval
221
		foreach ($this->fields as $key => $val)
222
		{
223
			if (is_array($val['arrayofkeyval']))
224
			{
225
				foreach ($val['arrayofkeyval'] as $key2 => $val2)
226
				{
227
					$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
228
				}
229
			}
230
		}
231
	}
232
233
	/**
234
	 * Create object into database
235
	 *
236
	 * @param  User $user      User that creates
237
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
238
	 * @return int             <=0 if KO, Id of created object if OK
239
	 */
240
	public function create(User $user, $notrigger = false)
241
	{
242
		global $conf;
243
244
		$error = 0;
245
		$idcreated = 0;
246
247
		$this->db->begin();
248
249
		if (!$error) {
250
			$idcreated = $this->createCommon($user, $notrigger);
251
			if ($idcreated <= 0) {
252
				$error++;
253
			}
254
		}
255
256
		if (!$error) {
257
			$result = $this->updateProduction($user, $notrigger);
0 ignored issues
show
Unused Code introduced by
The call to Mo::updateProduction() has too many arguments starting with $notrigger. ( Ignorable by Annotation )

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

257
			/** @scrutinizer ignore-call */ 
258
   $result = $this->updateProduction($user, $notrigger);

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

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

Loading history...
258
			if ($result <= 0) {
259
				$error++;
260
			}
261
		}
262
263
		if (!$error) {
264
			$this->db->commit();
265
		} else {
266
			$this->db->rollback();
267
		}
268
269
		return $idcreated;
270
	}
271
272
	/**
273
	 * Clone an object into another one
274
	 *
275
	 * @param  	User 	$user      	User that creates
276
	 * @param  	int 	$fromid     Id of object to clone
277
	 * @return 	mixed 				New object created, <0 if KO
278
	 */
279
	public function createFromClone(User $user, $fromid)
280
	{
281
		global $langs, $extrafields;
282
	    $error = 0;
283
284
	    dol_syslog(__METHOD__, LOG_DEBUG);
285
286
	    $object = new self($this->db);
287
288
	    $this->db->begin();
289
290
	    // Load source object
291
	    $result = $object->fetchCommon($fromid);
292
	    if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines();
293
294
	    // get lines so they will be clone
295
	    //foreach($this->lines as $line)
296
	    //	$line->fetch_optionals();
297
298
	    // Reset some properties
299
	    unset($object->id);
300
	    unset($object->fk_user_creat);
301
	    unset($object->import_key);
302
303
	    // Clear fields
304
	    $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default'];
305
	    $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
306
	    $object->status = self::STATUS_DRAFT;
307
	    // ...
308
	    // Clear extrafields that are unique
309
	    if (is_array($object->array_options) && count($object->array_options) > 0)
310
	    {
311
	    	$extrafields->fetch_name_optionals_label($this->table_element);
312
	    	foreach ($object->array_options as $key => $option)
313
	    	{
314
	    		$shortkey = preg_replace('/options_/', '', $key);
315
	    		if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey]))
316
	    		{
317
	    			//var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
318
	    			unset($object->array_options[$key]);
319
	    		}
320
	    	}
321
	    }
322
323
	    // Create clone
324
		$object->context['createfromclone'] = 'createfromclone';
325
	    $result = $object->createCommon($user);
326
	    if ($result < 0) {
327
	        $error++;
328
	        $this->error = $object->error;
329
	        $this->errors = $object->errors;
330
	    }
331
332
	    if (!$error)
333
	    {
334
	    	// copy internal contacts
335
	    	if ($this->copy_linked_contact($object, 'internal') < 0)
336
	    	{
337
	    		$error++;
338
	    	}
339
	    }
340
341
	    if (!$error)
342
	    {
343
	    	// copy external contacts if same company
344
	    	if (property_exists($this, 'socid') && $this->socid == $object->socid)
1 ignored issue
show
Bug Best Practice introduced by
The property socid does not exist on Mo. Did you maybe forget to declare it?
Loading history...
345
	    	{
346
	    		if ($this->copy_linked_contact($object, 'external') < 0)
347
	    			$error++;
348
	    	}
349
	    }
350
351
	    unset($object->context['createfromclone']);
352
353
	    // End
354
	    if (!$error) {
355
	        $this->db->commit();
356
	        return $object;
357
	    } else {
358
	        $this->db->rollback();
359
	        return -1;
360
	    }
361
	}
362
363
	/**
364
	 * Load object in memory from the database
365
	 *
366
	 * @param int    $id   Id object
367
	 * @param string $ref  Ref
368
	 * @return int         <0 if KO, 0 if not found, >0 if OK
369
	 */
370
	public function fetch($id, $ref = null)
371
	{
372
		$result = $this->fetchCommon($id, $ref);
373
		if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
374
		return $result;
375
	}
376
377
	/**
378
	 * Load object lines in memory from the database
379
	 *
380
	 * @return int         <0 if KO, 0 if not found, >0 if OK
381
	 */
382
	public function fetchLines()
383
	{
384
		$this->lines = array();
385
386
		$result = $this->fetchLinesCommon();
387
		return $result;
388
	}
389
390
391
	/**
392
	 * Load list of objects in memory from the database.
393
	 *
394
	 * @param  string      $sortorder    Sort Order
395
	 * @param  string      $sortfield    Sort field
396
	 * @param  int         $limit        limit
397
	 * @param  int         $offset       Offset
398
	 * @param  array       $filter       Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
399
	 * @param  string      $filtermode   Filter mode (AND or OR)
400
	 * @return array|int                 int <0 if KO, array of pages if OK
401
	 */
402
	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
403
	{
404
		global $conf;
405
406
		dol_syslog(__METHOD__, LOG_DEBUG);
407
408
		$records = array();
409
410
		$sql = 'SELECT ';
411
		$sql .= $this->getFieldList();
412
		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
413
		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
414
		else $sql .= ' WHERE 1 = 1';
415
		// Manage filter
416
		$sqlwhere = array();
417
		if (count($filter) > 0) {
418
			foreach ($filter as $key => $value) {
419
				if ($key == 't.rowid') {
420
					$sqlwhere[] = $key.'='.$value;
421
				}
422
				elseif (strpos($key, 'date') !== false) {
423
					$sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
424
				}
425
				elseif ($key == 'customsql') {
426
					$sqlwhere[] = $value;
427
				}
428
				else {
429
					$sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
430
				}
431
			}
432
		}
433
		if (count($sqlwhere) > 0) {
434
			$sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')';
435
		}
436
437
		if (!empty($sortfield)) {
438
			$sql .= $this->db->order($sortfield, $sortorder);
439
		}
440
		if (!empty($limit)) {
441
			$sql .= ' '.$this->db->plimit($limit, $offset);
442
		}
443
444
		$resql = $this->db->query($sql);
445
		if ($resql) {
446
			$num = $this->db->num_rows($resql);
447
            $i = 0;
448
			while ($i < min($limit, $num))
449
			{
450
			    $obj = $this->db->fetch_object($resql);
451
452
				$record = new self($this->db);
453
				$record->setVarsFromFetchObj($obj);
454
455
				$records[$record->id] = $record;
456
457
				$i++;
458
			}
459
			$this->db->free($resql);
460
461
			return $records;
462
		} else {
463
			$this->errors[] = 'Error '.$this->db->lasterror();
464
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
465
466
			return -1;
467
		}
468
	}
469
470
	/**
471
	 * Update object into database
472
	 *
473
	 * @param  User $user      User that modifies
474
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
475
	 * @return int             <0 if KO, >0 if OK
476
	 */
477
	public function update(User $user, $notrigger = false)
478
	{
479
		global $langs;
480
481
		$error = 0;
482
483
		$this->db->begin();
484
485
		$result = $this->updateCommon($user, $notrigger);
486
		if ($result <= 0) {
487
			$error++;
488
		}
489
490
		$result = $this->updateProduction($user, $notrigger);
0 ignored issues
show
Unused Code introduced by
The call to Mo::updateProduction() has too many arguments starting with $notrigger. ( Ignorable by Annotation )

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

490
		/** @scrutinizer ignore-call */ 
491
  $result = $this->updateProduction($user, $notrigger);

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

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

Loading history...
491
		if ($result <= 0) {
492
			$error++;
493
		}
494
495
		if (! $error) {
496
			setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
497
			$this->db->commit();
498
			return 1;
499
		}
500
		else {
501
			setEventMessages($this->error, $this->errors, 'errors');
502
			$this->db->rollback();
503
			return -1;
504
		}
505
	}
506
507
	/**
508
	 * Erase and update the line to produce.
509
	 *
510
	 * @param  User $user      User that modifies
511
	 * @return int             <0 if KO, >0 if OK
512
	 */
513
	public function updateProduction(User $user)
514
	{
515
		$error = 0;
516
517
		if ($this->status != self::STATUS_DRAFT) {
518
			$this->error = 'BadStatus';
519
			return -1;
520
		}
521
522
		$this->db->begin();
523
524
		// Insert lines in mrp_production table from BOM data
525
		if (!$error && $this->fk_bom > 0)
526
		{
527
			// TODO Check that production has not started. If yes, we stop here.
528
			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.$this->id;
529
			$this->db->query($sql);
530
531
			include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
532
			$bom = new Bom($this->db);
533
			$bom->fetch($this->fk_bom);
534
			if ($bom->id > 0)
535
			{
536
				$moline = new MoLine($this->db);
537
538
				// Line to produce
539
				$moline->fk_mo = $this->id;
540
				$moline->qty = $this->qty;
541
				$moline->fk_product = $this->fk_product;
542
				$moline->role = 'toproduce';
543
				$moline->position = 1;
544
545
				$resultline = $moline->create($user);
546
				if ($resultline <= 0) {
547
					$error++;
548
					$this->error = $moline->error;
549
					$this->errors = $moline->errors;
550
					dol_print_error($this->db, $moline->error, $moline->errors);
551
				}
552
553
				// Lines to consume
554
				if (! $error) {
555
					foreach ($bom->lines as $line)
556
					{
557
						$moline = new MoLine($this->db);
558
559
						$moline->fk_mo = $this->id;
560
						if ($line->qty_frozen) {
561
							$moline->qty = $line->qty;		// Qty to consume does not depends on quantity to produce
562
						} else {
563
							$moline->qty = round($line->qty * $this->qty / $bom->efficiency, 2);
564
						}
565
						if ($moline->qty <= 0) {
566
							$error++;
567
							$this->error = "BadValueForquantityToConsume";
568
							break;
569
						}
570
						else {
571
							$moline->fk_product = $line->fk_product;
572
							$moline->role = 'toconsume';
573
							$moline->position = $line->position;
574
							$moline->qty_frozen = $line->qty_frozen;
575
							$moline->disable_stock_change = $line->disable_stock_change;
576
577
							$resultline = $moline->create($user);
578
							if ($resultline <= 0) {
579
								$error++;
580
								$this->error = $moline->error;
581
								$this->errors = $moline->errors;
582
								dol_print_error($this->db, $moline->error, $moline->errors);
583
								break;
584
							}
585
						}
586
					}
587
				}
588
			}
589
		}
590
591
		if (!$error) {
592
			$this->db->commit();
593
			return 1;
594
		} else {
595
			$this->db->rollback();
596
			return -1;
597
		}
598
	}
599
600
601
	/**
602
	 * Delete object in database
603
	 *
604
	 * @param User $user       User that deletes
605
	 * @param bool $notrigger  false=launch triggers after, true=disable triggers
606
	 * @return int             <0 if KO, >0 if OK
607
	 */
608
	public function delete(User $user, $notrigger = false)
609
	{
610
		return $this->deleteCommon($user, $notrigger);
611
		//return $this->deleteCommon($user, $notrigger, 1);
612
	}
613
614
	/**
615
	 *  Delete a line of object in database
616
	 *
617
	 *	@param  User	$user       User that delete
618
	 *  @param	int		$idline		Id of line to delete
619
	 *  @param 	bool 	$notrigger  false=launch triggers after, true=disable triggers
620
	 *  @return int         		>0 if OK, <0 if KO
621
	 */
622
	public function deleteLine(User $user, $idline, $notrigger = false)
623
	{
624
		if ($this->status < 0)
625
		{
626
			$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
627
			return -2;
628
		}
629
630
		return $this->deleteLineCommon($user, $idline, $notrigger);
631
	}
632
633
634
	/**
635
	 *  Returns the reference to the following non used MO depending on the active numbering module
636
	 *  defined into MRP_MO_ADDON
637
	 *
638
	 *  @param	Product		$prod 	Object product
639
	 *  @return string      		MO free reference
640
	 */
641
	public function getNextNumRef($prod)
642
	{
643
		global $langs, $conf;
644
		$langs->load("mrp");
645
646
		if (!empty($conf->global->MRP_MO_ADDON))
647
		{
648
			$mybool = false;
649
650
			$file = $conf->global->MRP_MO_ADDON.".php";
651
			$classname = $conf->global->MRP_MO_ADDON;
652
653
			// Include file with class
654
			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
655
			foreach ($dirmodels as $reldir)
656
			{
657
				$dir = dol_buildpath($reldir."core/modules/mrp/");
658
659
				// Load file with numbering class (if found)
660
				$mybool |= @include_once $dir.$file;
661
			}
662
663
			if ($mybool === false)
664
			{
665
				dol_print_error('', "Failed to include file ".$file);
666
				return '';
667
			}
668
669
			$obj = new $classname();
670
			$numref = $obj->getNextValue($prod, $this);
671
672
			if ($numref != "")
673
			{
674
				return $numref;
675
			}
676
			else
677
			{
678
				$this->error = $obj->error;
679
				//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
680
				return "";
681
			}
682
		}
683
		else
684
		{
685
			print $langs->trans("Error")." ".$langs->trans("Error_MRP_MO_ADDON_NotDefined");
686
			return "";
687
		}
688
	}
689
690
	/**
691
	 *	Validate Mo
692
	 *
693
	 *	@param		User	$user     		User making status change
694
	 *  @param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
695
	 *	@return  	int						<=0 if OK, 0=Nothing done, >0 if KO
696
	 */
697
	public function validate($user, $notrigger = 0)
698
	{
699
		global $conf, $langs;
700
701
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
702
703
		$error = 0;
704
705
		// Protection
706
		if ($this->status == self::STATUS_VALIDATED)
707
		{
708
			dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
709
			return 0;
710
		}
711
712
		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mrp->create))
713
		 || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mrp->mrp_advance->validate))))
714
		 {
715
		 $this->error='NotEnoughPermissions';
716
		 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
717
		 return -1;
718
		 }*/
719
720
		$now = dol_now();
721
722
		$this->db->begin();
723
724
		// Define new ref
725
		if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
726
		{
727
			$this->fetch_product();
728
			$num = $this->getNextNumRef($this->product);
729
		}
730
		else
731
		{
732
			$num = $this->ref;
733
		}
734
		$this->newref = $num;
735
736
		// Validate
737
		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
738
		$sql .= " SET ref = '".$this->db->escape($num)."',";
739
		$sql .= " status = ".self::STATUS_VALIDATED.",";
740
		$sql .= " date_valid='".$this->db->idate($now)."',";
741
		$sql .= " fk_user_valid = ".$user->id;
742
		$sql .= " WHERE rowid = ".$this->id;
743
744
		dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
745
		$resql = $this->db->query($sql);
746
		if (!$resql)
747
		{
748
			dol_print_error($this->db);
749
			$this->error = $this->db->lasterror();
750
			$error++;
751
		}
752
753
		if (!$error && !$notrigger)
754
		{
755
			// Call trigger
756
			$result = $this->call_trigger('MRP_MO_VALIDATE', $user);
757
			if ($result < 0) $error++;
758
			// End call triggers
759
		}
760
761
		if (!$error)
762
		{
763
			$this->oldref = $this->ref;
764
765
			// Rename directory if dir was a temporary ref
766
			if (preg_match('/^[\(]?PROV/i', $this->ref))
767
			{
768
				// Now we rename also files into index
769
				$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'mrp/".$this->db->escape($this->newref)."'";
770
				$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
771
				$resql = $this->db->query($sql);
772
				if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
773
774
				// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
775
				$oldref = dol_sanitizeFileName($this->ref);
776
				$newref = dol_sanitizeFileName($num);
777
				$dirsource = $conf->mrp->dir_output.'/'.$oldref;
778
				$dirdest = $conf->mrp->dir_output.'/'.$newref;
779
				if (!$error && file_exists($dirsource))
780
				{
781
					dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
782
783
					if (@rename($dirsource, $dirdest))
784
					{
785
						dol_syslog("Rename ok");
786
						// Rename docs starting with $oldref with $newref
787
						$listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
788
						foreach ($listoffiles as $fileentry)
789
						{
790
							$dirsource = $fileentry['name'];
791
							$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
792
							$dirsource = $fileentry['path'].'/'.$dirsource;
793
							$dirdest = $fileentry['path'].'/'.$dirdest;
794
							@rename($dirsource, $dirdest);
795
						}
796
					}
797
				}
798
			}
799
		}
800
801
		// Set new ref and current status
802
		if (!$error)
803
		{
804
			$this->ref = $num;
805
			$this->status = self::STATUS_VALIDATED;
806
		}
807
808
		if (!$error)
809
		{
810
			$this->db->commit();
811
			return 1;
812
		}
813
		else
814
		{
815
			$this->db->rollback();
816
			return -1;
817
		}
818
	}
819
820
	/**
821
	 *	Set draft status
822
	 *
823
	 *	@param	User	$user			Object user that modify
824
	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
825
	 *	@return	int						<0 if KO, >0 if OK
826
	 */
827
	public function setDraft($user, $notrigger = 0)
828
	{
829
		// Protection
830
		if ($this->status <= self::STATUS_DRAFT)
831
		{
832
			return 0;
833
		}
834
835
		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
836
		 || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
837
		 {
838
		 $this->error='Permission denied';
839
		 return -1;
840
		 }*/
841
842
		return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MO_UNVALIDATE');
843
	}
844
845
	/**
846
	 *	Set cancel status
847
	 *
848
	 *	@param	User	$user			Object user that modify
849
	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
850
	 *	@return	int						<0 if KO, 0=Nothing done, >0 if OK
851
	 */
852
	public function cancel($user, $notrigger = 0)
853
	{
854
		// Protection
855
		if ($this->status != self::STATUS_VALIDATED)
856
		{
857
			return 0;
858
		}
859
860
		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
861
		 || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
862
		 {
863
		 $this->error='Permission denied';
864
		 return -1;
865
		 }*/
866
867
		return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MO_CLOSE');
868
	}
869
870
	/**
871
	 *	Set back to validated status
872
	 *
873
	 *	@param	User	$user			Object user that modify
874
	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
875
	 *	@return	int						<0 if KO, 0=Nothing done, >0 if OK
876
	 */
877
	public function reopen($user, $notrigger = 0)
878
	{
879
		// Protection
880
		if ($this->status != self::STATUS_CANCELED)
881
		{
882
			return 0;
883
		}
884
885
		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
886
		 || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
887
		 {
888
		 $this->error='Permission denied';
889
		 return -1;
890
		 }*/
891
892
		return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MO_REOPEN');
893
	}
894
895
    /**
896
     *  Return a link to the object card (with optionaly the picto)
897
     *
898
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
899
     *  @param  string  $option                     On what the link point to ('nolink', ...)
900
     *  @param  int     $notooltip                  1=Disable tooltip
901
     *  @param  string  $morecss                    Add more css on link
902
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
903
     *  @return	string                              String with URL
904
     */
905
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
906
    {
907
        global $conf, $langs, $hookmanager;
908
909
        if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
910
911
        $result = '';
912
913
        $label = '<u>'.$langs->trans("MO").'</u>';
914
        $label .= '<br>';
915
        $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
916
917
        $url = dol_buildpath('/mrp/mo_card.php', 1).'?id='.$this->id;
918
919
        if ($option != 'nolink')
920
        {
921
            // Add param to save lastsearch_values or not
922
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
923
            if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
924
            if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
925
        }
926
927
        $linkclose = '';
928
        if (empty($notooltip))
929
        {
930
            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
931
            {
932
                $label = $langs->trans("ShowMo");
933
                $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
934
            }
935
            $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
936
            $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
937
        }
938
        else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
939
940
		$linkstart = '<a href="'.$url.'"';
941
		$linkstart .= $linkclose.'>';
942
		$linkend = '</a>';
943
944
		$result .= $linkstart;
945
		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
946
		if ($withpicto != 2) $result .= $this->ref;
947
		$result .= $linkend;
948
		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
949
950
		global $action, $hookmanager;
951
		$hookmanager->initHooks(array('modao'));
952
		$parameters = array('id'=>$this->id, 'getnomurl'=>$result);
953
		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
954
		if ($reshook > 0) $result = $hookmanager->resPrint;
955
		else $result .= $hookmanager->resPrint;
956
957
		return $result;
958
    }
959
960
	/**
961
	 *  Return label of the status
962
	 *
963
	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
964
	 *  @return	string 			       Label of status
965
	 */
966
	public function getLibStatut($mode = 0)
967
	{
968
		return $this->LibStatut($this->status, $mode);
969
	}
970
971
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
972
	/**
973
	 *  Return the status
974
	 *
975
	 *  @param	int		$status        Id status
976
	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
977
	 *  @return string 			       Label of status
978
	 */
979
	public function LibStatut($status, $mode = 0)
980
	{
981
		// phpcs:enable
982
		if (empty($this->labelStatus))
983
		{
984
			global $langs;
985
			//$langs->load("mrp");
986
			$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
987
			$this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Validated').' ('.$langs->trans("ToProduce").')';
988
			$this->labelStatus[self::STATUS_INPROGRESS] = $langs->trans('InProgress');
989
			$this->labelStatus[self::STATUS_PRODUCED] = $langs->trans('StatusMOProduced');
990
			$this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Canceled');
991
992
			$this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
993
			$this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Validated');
994
			$this->labelStatusShort[self::STATUS_INPROGRESS] = $langs->trans('InProgress');
995
			$this->labelStatusShort[self::STATUS_PRODUCED] = $langs->trans('StatusMOProduced');
996
			$this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Canceled');
997
		}
998
999
		$statusType = 'status'.$status;
1000
		if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
1001
		if ($status == self::STATUS_INPROGRESS) $statusType = 'status3';
1002
		if ($status == self::STATUS_PRODUCED) $statusType = 'status5';
1003
		if ($status == self::STATUS_CANCELED) $statusType = 'status6';
1004
1005
		return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1006
	}
1007
1008
	/**
1009
	 *	Load the info information in the object
1010
	 *
1011
	 *	@param  int		$id       Id of object
1012
	 *	@return	void
1013
	 */
1014
	public function info($id)
1015
	{
1016
		$sql = 'SELECT rowid, date_creation as datec, tms as datem,';
1017
		$sql .= ' fk_user_creat, fk_user_modif';
1018
		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1019
		$sql .= ' WHERE t.rowid = '.$id;
1020
		$result = $this->db->query($sql);
1021
		if ($result)
1022
		{
1023
			if ($this->db->num_rows($result))
1024
			{
1025
				$obj = $this->db->fetch_object($result);
1026
				$this->id = $obj->rowid;
1027
				if ($obj->fk_user_author)
1028
				{
1029
					$cuser = new User($this->db);
1030
					$cuser->fetch($obj->fk_user_author);
1031
					$this->user_creation = $cuser;
1032
				}
1033
1034
				if ($obj->fk_user_valid)
1035
				{
1036
					$vuser = new User($this->db);
1037
					$vuser->fetch($obj->fk_user_valid);
1038
					$this->user_validation = $vuser;
1039
				}
1040
1041
				if ($obj->fk_user_cloture)
1042
				{
1043
					$cluser = new User($this->db);
1044
					$cluser->fetch($obj->fk_user_cloture);
1045
					$this->user_cloture = $cluser;
1046
				}
1047
1048
				$this->date_creation     = $this->db->jdate($obj->datec);
1049
				$this->date_modification = $this->db->jdate($obj->datem);
1050
				$this->date_validation   = $this->db->jdate($obj->datev);
1051
			}
1052
1053
			$this->db->free($result);
1054
		}
1055
		else
1056
		{
1057
			dol_print_error($this->db);
1058
		}
1059
	}
1060
1061
	/**
1062
	 * Initialise object with example values
1063
	 * Id must be 0 if object instance is a specimen
1064
	 *
1065
	 * @return void
1066
	 */
1067
	public function initAsSpecimen()
1068
	{
1069
		$this->initAsSpecimenCommon();
1070
	}
1071
1072
	/**
1073
	 * 	Create an array of lines
1074
	 *
1075
	 * 	@return array|int		array of lines if OK, <0 if KO
1076
	 */
1077
	public function getLinesArray()
1078
	{
1079
	    $this->lines = array();
1080
1081
	    $objectline = new MoLine($this->db);
1082
	    $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_mo = '.$this->id));
1083
1084
	    if (is_numeric($result))
1 ignored issue
show
introduced by
The condition is_numeric($result) is always true.
Loading history...
1085
	    {
1086
	        $this->error = $this->error;
1087
	        $this->errors = $this->errors;
1088
	        return $result;
1089
	    }
1090
	    else
1091
	    {
1092
	        $this->lines = $result;
1093
	        return $this->lines;
1094
	    }
1095
	}
1096
1097
	/**
1098
	 *  Create a document onto disk according to template module.
1099
	 *
1100
	 *  @param	    string		$modele			Force template to use ('' to not force)
1101
	 *  @param		Translate	$outputlangs	objet lang a utiliser pour traduction
1102
	 *  @param      int			$hidedetails    Hide details of lines
1103
	 *  @param      int			$hidedesc       Hide description
1104
	 *  @param      int			$hideref        Hide ref
1105
	 *  @param      null|array  $moreparams     Array to provide more information
1106
	 *  @return     int         				0 if KO, 1 if OK
1107
	 */
1108
	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1109
	{
1110
		global $conf, $langs;
1111
1112
		$langs->load("mrp");
1113
1114
		if (!dol_strlen($modele)) {
1115
			//$modele = 'standard';
1116
			$modele = '';					// Remove this once a pdf_standard.php exists.
1117
1118
			if ($this->modelpdf) {
1119
				$modele = $this->modelpdf;
1120
			} elseif (!empty($conf->global->MO_ADDON_PDF)) {
1121
				$modele = $conf->global->MO_ADDON_PDF;
1122
			}
1123
		}
1124
1125
		$modelpath = "core/modules/mrp/doc/";
1126
1127
		if (empty($modele)) return 1;	// Remove this once a pdf_standard.php exists.
1128
1129
		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1130
	}
1131
1132
	/**
1133
	 * Action executed by scheduler
1134
	 * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
1135
	 *
1136
	 * @return	int			0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
1137
	 */
1138
	//public function doScheduledJob($param1, $param2, ...)
1139
	public function doScheduledJob()
1140
	{
1141
		global $conf, $langs;
1142
1143
		//$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1144
1145
		$error = 0;
1146
		$this->output = '';
1147
		$this->error = '';
1148
1149
		dol_syslog(__METHOD__, LOG_DEBUG);
1150
1151
		$now = dol_now();
1152
1153
		$this->db->begin();
1154
1155
		// ...
1156
1157
		$this->db->commit();
1158
1159
		return $error;
1160
	}
1161
1162
	/**
1163
	 * 	Return HTML table table of source object lines
1164
	 *  TODO Move this and previous function into output html class file (htmlline.class.php).
1165
	 *  If lines are into a template, title must also be into a template
1166
	 *  But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
1167
	 *
1168
	 *	@param	string		$restrictlist		''=All lines, 'services'=Restrict to services only
1169
	 *  @param  array       $selectedLines      Array of lines id for selected lines
1170
	 *  @return	void
1171
	 */
1172
	public function printOriginLinesList($restrictlist = '', $selectedLines = array())
1173
	{
1174
		global $langs, $hookmanager, $conf, $form;
1175
1176
		print '<tr class="liste_titre">';
1177
		print '<td>'.$langs->trans('Ref').'</td>';
1178
		print '<td class="right">'.$langs->trans('Qty').'</td>';
1179
		print '<td class="center">'.$langs->trans('QtyFrozen').'</td>';
1180
		print '<td class="center">'.$langs->trans('DisableStockChange').'</td>';
1181
		//print '<td class="right">'.$langs->trans('Efficiency').'</td>';
1182
		//print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
1183
		print '<td class="center"></td>';
1184
		print '</tr>';
1185
		$i = 0;
1186
1187
		if (!empty($this->lines))
1188
		{
1189
			foreach ($this->lines as $line)
1190
			{
1191
				/*if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
1192
				{
1193
					if (empty($line->fk_parent_line))
1194
					{
1195
						$parameters = array('line'=>$line, 'i'=>$i);
1196
						$action = '';
1197
						$result = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1198
					}
1199
				}
1200
				else
1201
				{*/
1202
					$this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
1203
				//}
1204
1205
				$i++;
1206
			}
1207
		}
1208
	}
1209
1210
1211
	/**
1212
	 * 	Return HTML with a line of table array of source object lines
1213
	 *  TODO Move this and previous function into output html class file (htmlline.class.php).
1214
	 *  If lines are into a template, title must also be into a template
1215
	 *  But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
1216
	 *
1217
	 * 	@param	CommonObjectLine	$line				Line
1218
	 * 	@param	string				$var				Var
1219
	 *	@param	string				$restrictlist		''=All lines, 'services'=Restrict to services only (strike line if not)
1220
	 *  @param	string				$defaulttpldir		Directory where to find the template
1221
	 *  @param  array       		$selectedLines      Array of lines id for selected lines
1222
	 * 	@return	void
1223
	 */
1224
	public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
1225
	{
1226
		global $langs, $conf;
1227
1228
		$this->tpl['id'] = $line->id;
1229
1230
		$this->tpl['label'] = '';
1231
		if (!empty($line->fk_product))
1232
		{
1233
			$productstatic = new Product($this->db);
1234
			$productstatic->fetch($line->fk_product);
1235
			$this->tpl['label'] .= $productstatic->getNomUrl(1);
1236
			//$this->tpl['label'].= ' - '.$productstatic->label;
1237
		}
1238
		else
1239
		{
1240
			// If origin MRP line is not a product, but another MRP
1241
			// TODO
1242
		}
1243
1244
		$this->tpl['qty'] = $line->qty;
1245
		$this->tpl['qty_frozen'] = $line->qty_frozen;
1246
		$this->tpl['disable_stock_change'] = $line->disable_stock_change;
1247
		//$this->tpl['efficiency'] = $line->efficiency;
1248
1249
		$tpl = DOL_DOCUMENT_ROOT.'/mrp/tpl/originproductline.tpl.php';
1250
		$res = include $tpl;
1251
	}
1252
}
1253
1254
/**
1255
 * Class MoLine. You can also remove this and generate a CRUD class for lines objects.
1256
 */
1257
class MoLine extends CommonObjectLine
1258
{
1259
	/**
1260
	 * @var string ID to identify managed object
1261
	 */
1262
	public $element = 'mrp_production';
1263
1264
	/**
1265
	 * @var string Name of table without prefix where object is stored
1266
	 */
1267
	public $table_element = 'mrp_production';
1268
1269
	/**
1270
	 * @var int  Does myobject support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
1271
	 */
1272
	public $ismultientitymanaged = 0;
1273
1274
	/**
1275
	 * @var int  Does moline support extrafields ? 0=No, 1=Yes
1276
	 */
1277
	public $isextrafieldmanaged = 0;
1278
1279
	public $fields = array(
1280
		'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
1281
		'fk_mo' =>array('type'=>'integer', 'label'=>'Fk mo', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
1282
		'position' =>array('type'=>'integer', 'label'=>'Position', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20),
1283
		'fk_product' =>array('type'=>'integer', 'label'=>'Fk product', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
1284
		'fk_warehouse' =>array('type'=>'integer', 'label'=>'Fk warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
1285
		'qty' =>array('type'=>'integer', 'label'=>'Qty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
1286
		'qty_frozen' => array('type'=>'smallint', 'label'=>'QuantityFrozen', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>105, 'css'=>'maxwidth50imp', 'help'=>'QuantityConsumedInvariable'),
1287
		'disable_stock_change' => array('type'=>'smallint', 'label'=>'DisableStockChange', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>108, 'css'=>'maxwidth50imp', 'help'=>'DisableStockChangeHelp'),
1288
		'batch' =>array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
1289
		'role' =>array('type'=>'varchar(10)', 'label'=>'Role', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
1290
		'fk_mrp_production' =>array('type'=>'integer', 'label'=>'Fk mrp production', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
1291
		'fk_stock_movement' =>array('type'=>'integer', 'label'=>'Fk stock movement', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
1292
		'date_creation' =>array('type'=>'datetime', 'label'=>'Date creation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>160),
1293
		'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>165),
1294
		'fk_user_creat' =>array('type'=>'integer', 'label'=>'Fk user creat', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>170),
1295
		'fk_user_modif' =>array('type'=>'integer', 'label'=>'Fk user modif', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
1296
		'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
1297
	);
1298
1299
	public $rowid;
1300
	public $fk_mo;
1301
	public $position;
1302
	public $fk_product;
1303
	public $fk_warehouse;
1304
	public $qty;
1305
	public $qty_frozen;
1306
	public $disable_stock_change;
1307
	public $batch;
1308
	public $role;
1309
	public $fk_mrp_production;
1310
	public $fk_stock_movement;
1311
	public $date_creation;
1312
	public $tms;
1313
	public $fk_user_creat;
1314
	public $fk_user_modif;
1315
	public $import_key;
1316
1317
	/**
1318
	 * Constructor
1319
	 *
1320
	 * @param DoliDb $db Database handler
1321
	 */
1322
	public function __construct(DoliDB $db)
1323
	{
1324
		global $conf, $langs;
1325
1326
		$this->db = $db;
1327
1328
		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
1329
		if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0;
1330
1331
		// Unset fields that are disabled
1332
		foreach ($this->fields as $key => $val)
1333
		{
1334
			if (isset($val['enabled']) && empty($val['enabled']))
1335
			{
1336
				unset($this->fields[$key]);
1337
			}
1338
		}
1339
1340
		// Translate some data of arrayofkeyval
1341
		if (is_object($langs))
1342
		{
1343
			foreach ($this->fields as $key => $val)
1344
			{
1345
				if (is_array($val['arrayofkeyval']))
1346
				{
1347
					foreach ($val['arrayofkeyval'] as $key2 => $val2)
1348
					{
1349
						$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
1350
					}
1351
				}
1352
			}
1353
		}
1354
	}
1355
1356
	/**
1357
	 * Create object into database
1358
	 *
1359
	 * @param  User $user      User that creates
1360
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
1361
	 * @return int             <0 if KO, Id of created object if OK
1362
	 */
1363
	public function create(User $user, $notrigger = false)
1364
	{
1365
		return $this->createCommon($user, $notrigger);
1366
	}
1367
1368
	/**
1369
	 * Load object in memory from the database
1370
	 *
1371
	 * @param int    $id   Id object
1372
	 * @param string $ref  Ref
1373
	 * @return int         <0 if KO, 0 if not found, >0 if OK
1374
	 */
1375
	public function fetch($id, $ref = null)
1376
	{
1377
		$result = $this->fetchCommon($id, $ref);
1378
		if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
0 ignored issues
show
Bug introduced by
The method fetchLines() does not exist on MoLine. Did you maybe mean fetchLinesCommon()? ( Ignorable by Annotation )

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

1378
		if ($result > 0 && !empty($this->table_element_line)) $this->/** @scrutinizer ignore-call */ fetchLines();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1379
		return $result;
1380
	}
1381
1382
	/**
1383
	 * Load list of objects in memory from the database.
1384
	 *
1385
	 * @param  string      $sortorder    Sort Order
1386
	 * @param  string      $sortfield    Sort field
1387
	 * @param  int         $limit        limit
1388
	 * @param  int         $offset       Offset
1389
	 * @param  array       $filter       Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
1390
	 * @param  string      $filtermode   Filter mode (AND or OR)
1391
	 * @return array|int                 int <0 if KO, array of pages if OK
1392
	 */
1393
	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
1394
	{
1395
		global $conf;
1396
1397
		dol_syslog(__METHOD__, LOG_DEBUG);
1398
1399
		$records = array();
1400
1401
		$sql = 'SELECT ';
1402
		$sql .= $this->getFieldList();
1403
		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1404
		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
1405
		else $sql .= ' WHERE 1 = 1';
1406
		// Manage filter
1407
		$sqlwhere = array();
1408
		if (count($filter) > 0) {
1409
			foreach ($filter as $key => $value) {
1410
				if ($key == 't.rowid') {
1411
					$sqlwhere[] = $key.'='.$value;
1412
				}
1413
				elseif (strpos($key, 'date') !== false) {
1414
					$sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
1415
				}
1416
				elseif ($key == 'customsql') {
1417
					$sqlwhere[] = $value;
1418
				}
1419
				else {
1420
					$sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
1421
				}
1422
			}
1423
		}
1424
		if (count($sqlwhere) > 0) {
1425
			$sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')';
1426
		}
1427
1428
		if (!empty($sortfield)) {
1429
			$sql .= $this->db->order($sortfield, $sortorder);
1430
		}
1431
		if (!empty($limit)) {
1432
			$sql .= ' '.$this->db->plimit($limit, $offset);
1433
		}
1434
1435
		$resql = $this->db->query($sql);
1436
		if ($resql) {
1437
			$num = $this->db->num_rows($resql);
1438
			$i = 0;
1439
			while ($i < min($limit, $num))
1440
			{
1441
				$obj = $this->db->fetch_object($resql);
1442
1443
				$record = new self($this->db);
1444
				$record->setVarsFromFetchObj($obj);
1445
1446
				$records[$record->id] = $record;
1447
1448
				$i++;
1449
			}
1450
			$this->db->free($resql);
1451
1452
			return $records;
1453
		} else {
1454
			$this->errors[] = 'Error '.$this->db->lasterror();
1455
			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1456
1457
			return -1;
1458
		}
1459
	}
1460
1461
	/**
1462
	 * Get list of lines linked to current line for a defined role
1463
	 *
1464
	 * @param  string $role      Get lines linked to current line with the selected role ('consumed', 'produced', ...)
1465
	 * @return array             Array of lines
1466
	 */
1467
	public function fetchLinesLinked($role) {
1468
		$array = array();
1469
1470
		$sql = 'SELECT rowid, qty ';
1471
		$sql .= $this->getFieldList();
1472
		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1473
		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
1474
		else $sql .= ' WHERE 1 = 1';
1475
1476
		return $array;
1477
	}
1478
1479
	/**
1480
	 * Update object into database
1481
	 *
1482
	 * @param  User $user      User that modifies
1483
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
1484
	 * @return int             <0 if KO, >0 if OK
1485
	 */
1486
	public function update(User $user, $notrigger = false)
1487
	{
1488
		return $this->updateCommon($user, $notrigger);
1489
	}
1490
1491
	/**
1492
	 * Delete object in database
1493
	 *
1494
	 * @param User $user       User that deletes
1495
	 * @param bool $notrigger  false=launch triggers after, true=disable triggers
1496
	 * @return int             <0 if KO, >0 if OK
1497
	 */
1498
	public function delete(User $user, $notrigger = false)
1499
	{
1500
		return $this->deleteCommon($user, $notrigger);
1501
		//return $this->deleteCommon($user, $notrigger, 1);
1502
	}
1503
}
1504