ActionsSubtotal   F
last analyzed

Complexity

Total Complexity 816

Size/Duplication

Total Lines 3312
Duplicated Lines 0 %

Importance

Changes 110
Bugs 15 Features 9
Metric Value
eloc 1735
dl 0
loc 3312
rs 0.8
c 110
b 15
f 9
wmc 816

46 Methods

Rating   Name   Duplication   Size   Complexity  
D getTotalLineFromObject() 0 69 18
A printFieldListSelect() 0 19 3
F printObjectLine() 0 762 279
C getArrayOfLineForAGroup() 0 25 12
B pdf_getlineprogress() 0 26 9
C formatNumerotation() 0 37 13
D pdf_getlinetotalexcltax() 0 76 19
C pdf_getlineremisepercent() 0 41 14
A ODTSubstitutionLine() 0 49 5
F pdf_add_total() 0 130 21
F formObjectOptions() 0 114 40
A formEditProductOptions() 0 9 2
A isModSubtotalLine() 0 24 6
A __construct() 0 8 1
A callHook() 0 25 4
D beforePDFCreation() 0 183 34
B pdf_getlineupwithtax() 0 28 11
F formBuilddocOptions() 0 73 27
C pdf_getlineupexcltax() 0 65 16
C createFrom() 0 42 15
B afterPDFCreation() 0 15 8
A implodeHtmlData() 0 14 3
A defineColumnField() 0 14 1
C printNewFormat() 0 141 11
A handleExpeditionTitleAndTotal() 0 15 3
B getTitle() 0 17 8
A getlinetotalremise() 0 10 2
C pdf_getlinevatrate() 0 54 13
B pdf_getlineunit() 0 27 9
D printOriginObjectLine() 0 105 36
A formAddObjectLine() 0 2 1
F doActions() 0 197 50
B pdf_add_title() 0 38 11
C pdf_getlineqty() 0 46 15
F pdf_writelinedesc() 0 121 22
A showSelectTitleToAdd() 0 17 1
C _ajax_block_order_js() 0 111 10
A pdf_writelinedesc_ref() 0 4 1
B createDictionaryFieldlist() 0 60 9
B changeRoundingMode() 0 25 11
A setDocTVA() 0 9 2
B addMoreActionsButtons() 0 87 8
B pdf_getlinetotalwithtax() 0 28 9
A getTitlesFlatArray() 0 16 5
C add_numerotation() 0 36 13
A _getHtmlData() 0 33 5

How to fix   Complexity   

Complex Class

Complex classes like ActionsSubtotal often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ActionsSubtotal, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
dol_include_once('/subtotal/class/subtotal.class.php');
4
5
class ActionsSubtotal
6
{
7
8
	function __construct($db)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
9
	{
10
		global $langs;
11
12
		$this->db = $db;
13
		$langs->load('subtotal@subtotal');
14
15
		$this->allow_move_block_lines = true;
16
	}
17
18
	function printFieldListSelect($parameters, &$object, &$action, $hookmanager) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
19
20
		global $type_element, $where;
21
22
		$contexts = explode(':',$parameters['context']);
23
24
		if(in_array('consumptionthirdparty',$contexts) && in_array($type_element, array('propal', 'order', 'invoice', 'supplier_order', 'supplier_invoice', 'supplier_proposal'))) {
25
			$mod_num = TSubtotal::$module_number;
26
27
			// Not a title (can't use TSubtotal class methods in sql)
28
			$where.= ' AND (d.special_code != '.$mod_num.' OR d.product_type != 9 OR d.qty > 9)';
29
			// Not a subtotal (can't use TSubtotal class methods in sql)
30
			$where.= ' AND (d.special_code != '.$mod_num.' OR d.product_type != 9 OR d.qty < 90)';
31
			// Not a free line text (can't use TSubtotal class methods in sql)
32
			$where.= ' AND (d.special_code != '.$mod_num.' OR d.product_type != 9 OR d.qty != 50)';
33
34
		}
35
36
		return 0;
37
	}
38
39
40
	function createDictionaryFieldlist($parameters, &$object, &$action, $hookmanager)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
41
	{
42
		global $conf;
43
44
		if ($parameters['tabname'] == MAIN_DB_PREFIX.'c_subtotal_free_text')
45
		{
46
			// Merci Dolibarr de remplacer les textarea par un input text
47
			if ((float) DOL_VERSION >= 6.0)
48
			{
49
				$value = '';
50
				$sql = 'SELECT content FROM '.MAIN_DB_PREFIX.'c_subtotal_free_text WHERE rowid = '.GETPOST('rowid', 'int');
51
				$resql = $this->db->query($sql);
52
				if ($resql && ($obj = $this->db->fetch_object($resql))) $value = $obj->content;
53
			}
54
55
			?>
56
			<script type="text/javascript">
57
				$(function() {
58
59
					<?php if ((float) DOL_VERSION >= 6.0) { ?>
60
							if ($('input[name=content]').length > 0)
61
							{
62
								$('input[name=content]').each(function(i,item) {
63
									var value = '';
64
									// Le dernier item correspond à l'édition
65
									if (i == $('input[name=content]').length) value = <?php echo json_encode($value); ?>;
66
									$(item).replaceWith($('<textarea name="content">'+value+'</textarea>'));
67
								});
68
69
								<?php if (!empty($conf->fckeditor->enabled) && !empty($conf->global->FCKEDITOR_ENABLE_DETAILS)) { ?>
70
								$('textarea[name=content]').each(function(i, item) {
71
									CKEDITOR.replace(item, {
72
										toolbar: 'dolibarr_notes'
73
										,customConfig : ckeditorConfig
74
									});
75
								});
76
								<?php } ?>
77
							}
78
					<?php } else { ?>
79
						// <= 5.0
80
						// Le CKEditor est forcé sur la page dictionnaire, pas possible de mettre une valeur custom
81
						// petit js qui supprimer le wysiwyg et affiche le textarea car avant la version 6.0 le wysiwyg sur une page de dictionnaire est inexploitable
82
						<?php if (!empty($conf->fckeditor->enabled)) { ?>
83
							CKEDITOR.on('instanceReady', function(ev) {
84
								var editor = ev.editor;
85
86
								if (editor.name == 'content') // Mon champ en bdd s'appel "content", pas le choix si je veux avoir un textarea sur une page de dictionnaire
87
								{
88
									editor.element.show();
89
									editor.destroy();
90
								}
91
							});
92
						<?php } ?>
93
					<?php } ?>
94
				});
95
			</script>
96
			<?php
97
		}
98
99
		return 0;
100
	}
101
102
	/** Overloading the doActions function : replacing the parent's function with the one below
103
	 * @param      $parameters  array           meta datas of the hook (context, etc...)
104
	 * @param      $object      CommonObject    the object you want to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
105
	 * @param      $action      string          current action (if set). Generally create or edit or null
106
	 * @param      $hookmanager HookManager     current hook manager
107
	 * @return     void
108
	 */
109
110
    var $module_number = 104777;
111
112
    function formObjectOptions($parameters, &$object, &$action, $hookmanager)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
113
    {
114
      	global $langs,$db,$user, $conf;
115
116
		$langs->load('subtotal@subtotal');
117
118
		$contexts = explode(':',$parameters['context']);
119
120
		if(in_array('ordercard',$contexts) || in_array('ordersuppliercard',$contexts) || in_array('propalcard',$contexts) || in_array('supplier_proposalcard',$contexts) || in_array('invoicecard',$contexts) || in_array('invoicesuppliercard',$contexts) || in_array('invoicereccard',$contexts) || in_array('expeditioncard',$contexts)) {
121
122
			$createRight = $user->rights->{$object->element}->creer;
123
			if($object->element == 'facturerec' )
124
			{
125
				$object->statut = 0; // hack for facture rec
126
				$createRight = $user->rights->facture->creer;
127
			} elseif($object->element == 'order_supplier' )
128
			{
129
			    $createRight = $user->rights->fournisseur->commande->creer;
130
			} elseif($object->element == 'invoice_supplier' )
131
			{
132
			    $createRight = $user->rights->fournisseur->facture->creer;
133
			}
134
			elseif($object->element == 'shipping')
135
			{
136
				$createRight = true; // No rights management for shipments
137
			}
138
139
			if ($object->statut == 0  && $createRight) {
140
141
142
				if($object->element=='facture')$idvar = 'facid';
143
				else $idvar='id';
144
145
				if(in_array($action, array('add_title_line', 'add_total_line', 'add_subtitle_line', 'add_subtotal_line', 'add_free_text')) )
146
				{
147
					$level = GETPOST('level', 'int'); //New avec SUBTOTAL_USE_NEW_FORMAT
148
149
					if($action=='add_title_line') {
150
						$title = GETPOST('title', 'none');
151
						if(empty($title)) $title = $langs->trans('title');
152
						$qty = $level<1 ? 1 : $level ;
153
					}
154
					else if($action=='add_free_text') {
155
						$title = GETPOST('title', 'restricthtml');
156
157
						if (empty($title)) {
158
							$free_text = GETPOST('free_text', 'int');
159
							if (!empty($free_text)) {
160
								$TFreeText = getTFreeText();
161
								if (!empty($TFreeText[$free_text])) {
162
									$title = $TFreeText[$free_text]->content;
163
								}
164
							}
165
						}
166
						if(empty($title)) $title = $langs->trans('subtotalAddLineDescription');
167
						$qty = 50;
168
					}
169
					else if($action=='add_subtitle_line') {
170
						$title = GETPOST('title', 'none');
171
						if(empty($title)) $title = $langs->trans('subtitle');
172
						$qty = 2;
173
					}
174
					else if($action=='add_subtotal_line') {
175
						$title = $langs->trans('SubSubTotal');
176
						$qty = 98;
177
					}
178
					else {
179
						$title = GETPOST('title', 'none') ? GETPOST('title', 'none') : $langs->trans('SubTotal');
180
						$qty = $level ? 100-$level : 99;
181
					}
182
					dol_include_once('/subtotal/class/subtotal.class.php');
183
184
					if (!empty($conf->global->SUBTOTAL_AUTO_ADD_SUBTOTAL_ON_ADDING_NEW_TITLE) && $qty < 10) TSubtotal::addSubtotalMissing($object, $qty);
185
186
	    			TSubtotal::addSubTotalLine($object, $title, $qty);
187
				}
188
				else if($action==='ask_deleteallline') {
189
						$form=new Form($db);
190
191
						$lineid = GETPOST('lineid','integer');
192
						$TIdForGroup = TSubtotal::getLinesFromTitleId($object, $lineid, true);
193
194
						$nbLines = count($TIdForGroup);
195
196
						$formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('deleteWithAllLines'), $langs->trans('ConfirmDeleteAllThisLines',$nbLines), 'confirm_delete_all_lines','',0,1);
197
						print $formconfirm;
198
				}
199
200
				if (!empty($conf->global->SUBTOTAL_ALLOW_ADD_LINE_UNDER_TITLE))
201
				{
202
					$this->showSelectTitleToAdd($object);
203
				}
204
205
206
				if($object->element != 'shipping' && $action!='editline') {
207
					// New format is for 3.8
208
					$this->printNewFormat($object, $conf, $langs, $idvar);
209
				}
210
			}
211
		}
212
		elseif ((!empty($parameters['currentcontext']) && $parameters['currentcontext'] == 'orderstoinvoice') || in_array('orderstoinvoice',$contexts) || in_array('orderstoinvoicesupplier',$contexts))
213
		{
214
			?>
215
			<script type="text/javascript">
216
				$(function() {
217
					var tr = $("<tr><td><?php echo $langs->trans('subtotal_add_title_bloc_from_orderstoinvoice'); ?></td><td><input type='checkbox' value='1' name='subtotal_add_title_bloc_from_orderstoinvoice' checked='checked' /></td></tr>")
218
					$("textarea[name=note]").closest('tr').after(tr);
219
				});
220
			</script>
221
			<?php
222
223
		}
224
225
		return 0;
226
	}
227
228
	function printNewFormat(&$object, &$conf, &$langs, $idvar)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
229
	{
230
		if (empty($conf->global->SUBTOTAL_ALLOW_ADD_BLOCK)) return false;
231
		if ($line->fk_prev_id != null && !empty($line->fk_prev_id)) return false; // Si facture de situation
232
		?>
233
		 	<script type="text/javascript">
234
				$(document).ready(function() {
235
					$('div.fiche div.tabsAction').append('<br />');
236
237
					$('div.fiche div.tabsAction').append('<div class="inline-block divButAction"><a id="add_title_line" rel="add_title_line" href="javascript:;" class="butAction"><?php echo  $langs->trans('AddTitle' )?></a></div>');
238
					$('div.fiche div.tabsAction').append('<div class="inline-block divButAction"><a id="add_total_line" rel="add_total_line" href="javascript:;" class="butAction"><?php echo  $langs->trans('AddSubTotal')?></a></div>');
239
					$('div.fiche div.tabsAction').append('<div class="inline-block divButAction"><a id="add_free_text" rel="add_free_text" href="javascript:;" class="butAction"><?php echo  $langs->trans('AddFreeText')?></a></div>');
240
241
242
					function updateAllMessageForms(){
243
				         for (instance in CKEDITOR.instances) {
244
				             CKEDITOR.instances[instance].updateElement();
245
				         }
246
				    }
247
248
					function promptSubTotal(action, titleDialog, label, url_to, url_ajax, params, use_textarea, show_free_text, show_under_title) {
249
					     $( "#dialog-prompt-subtotal" ).remove();
250
251
						 var dialog_html = '<div id="dialog-prompt-subtotal" '+(action == 'addSubtotal' ? 'class="center"' : '')+' >';
252
						 dialog_html += '<input id="token" name="token" type="hidden" value="<?php echo ((float) DOL_VERSION < 11.0) ?  $_SESSION['newtoken'] : newToken(); ?>" />';
253
254
						 if (typeof show_under_title != 'undefined' && show_under_title)
255
						 {
256
							 var selectUnderTitle = <?php echo json_encode(getHtmlSelectTitle($object, true)); ?>;
257
							 dialog_html += selectUnderTitle + '<br /><br />';
258
						 }
259
260
						if (action == 'addTitle' || action == 'addFreeTxt')
261
						{
262
							if (typeof show_free_text != 'undefined' && show_free_text)
263
							{
264
							   var selectFreeText = <?php echo json_encode(getHtmlSelectFreeText()); ?>;
265
							   dialog_html += selectFreeText + ' <?php echo $langs->transnoentities('subtotalFreeTextOrDesc'); ?><br />';
266
							}
267
268
							if (typeof use_textarea != 'undefined' && use_textarea) dialog_html += '<textarea id="sub-total-title" rows="<?php echo ROWS_8; ?>" cols="80" placeholder="'+label+'"></textarea>';
269
							else dialog_html += '<input id="sub-total-title" size="30" value="" placeholder="'+label+'" />';
270
						}
271
272
						if (action == 'addTitle' || action == 'addSubtotal')
273
						{
274
							if (action == 'addSubtotal') dialog_html += '<input id="sub-total-title" size="30" value="" placeholder="'+label+'" />';
275
276
							dialog_html += "&nbsp;<select name='subtotal_line_level'>";
277
							for (var i=1;i<10;i++)
278
							{
279
								dialog_html += "<option value="+i+"><?php echo $langs->trans('Level'); ?> "+i+"</option>";
280
							}
281
							dialog_html += "</select>";
282
						}
283
284
						 dialog_html += '</div>';
285
286
						$('body').append(dialog_html);
287
288
						<?php
289
						$editorTool = empty($conf->global->FCKEDITOR_EDITORNAME)?'ckeditor':$conf->global->FCKEDITOR_EDITORNAME;
290
						$editorConf = empty($conf->global->FCKEDITOR_ENABLE_DETAILS)?false:$conf->global->FCKEDITOR_ENABLE_DETAILS;
291
						if($editorConf && in_array($editorTool,array('textarea','ckeditor'))){
292
						?>
293
						if (action == 'addTitle' || action == 'addFreeTxt')
294
						{
295
							if (typeof use_textarea != 'undefined' && use_textarea && typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" )
296
							{
297
								 CKEDITOR.replace( 'sub-total-title', {toolbar: 'dolibarr_details', toolbarStartupExpanded: false} );
298
							}
299
						}
300
						<?php } ?>
301
302
					     $( "#dialog-prompt-subtotal" ).dialog({
303
	                        resizable: false,
304
							height: 'auto',
305
							width: 'auto',
306
	                        modal: true,
307
	                        title: titleDialog,
308
	                        buttons: {
309
	                            "Ok": function() {
310
	                            	if (typeof use_textarea != 'undefined' && use_textarea && typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" ){ updateAllMessageForms(); }
311
									params.title = (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && "sub-total-title" in CKEDITOR.instances ? CKEDITOR.instances["sub-total-title"].getData() : $(this).find('#sub-total-title').val());
312
									params.under_title = $(this).find('select[name=under_title]').val();
313
									params.free_text = $(this).find('select[name=free_text]').val();
314
									params.level = $(this).find('select[name=subtotal_line_level]').val();
315
									params.token = $(this).find('input[name=token]').val();
316
317
									$.ajax({
318
										url: url_ajax
319
										,type: 'POST'
320
										,data: params
321
									}).done(function() {
322
										document.location.href=url_to;
323
									});
324
325
                                    $( this ).dialog( "close" );
326
	                            },
327
	                            "<?php echo $langs->trans('Cancel') ?>": function() {
328
	                                $( this ).dialog( "close" );
329
	                            }
330
	                        }
331
	                     });
332
					}
333
334
					$('a[rel=add_title_line]').click(function()
335
					{
336
						promptSubTotal('addTitle'
337
							 , "<?php echo $langs->trans('YourTitleLabel') ?>"
338
							 , "<?php echo $langs->trans('title'); ?>"
339
							 , '?<?php echo $idvar ?>=<?php echo $object->id; ?>'
340
							 , '<?php echo $_SERVER['PHP_SELF']; ?>'
341
							 , {<?php echo $idvar; ?>: <?php echo (int) $object->id; ?>, action:'add_title_line'}
342
						);
343
					});
344
345
					$('a[rel=add_total_line]').click(function()
346
					{
347
						promptSubTotal('addSubtotal'
348
							, '<?php echo $langs->trans('YourSubtotalLabel') ?>'
349
							, '<?php echo $langs->trans('subtotal'); ?>'
350
							, '?<?php echo $idvar ?>=<?php echo $object->id; ?>'
351
							, '<?php echo $_SERVER['PHP_SELF']; ?>'
352
							, {<?php echo $idvar; ?>: <?php echo (int) $object->id; ?>, action:'add_total_line'}
353
							/*,false,false, <?php echo !empty($conf->global->SUBTOTAL_ALLOW_ADD_LINE_UNDER_TITLE) ? 'true' : 'false'; ?>*/
354
						);
355
					});
356
357
					$('a[rel=add_free_text]').click(function()
358
					{
359
						promptSubTotal('addFreeTxt'
360
							, "<?php echo $langs->transnoentitiesnoconv('YourTextLabel') ?>"
361
							, "<?php echo $langs->trans('subtotalAddLineDescription'); ?>"
362
							, '?<?php echo $idvar ?>=<?php echo $object->id; ?>'
363
							, '<?php echo $_SERVER['PHP_SELF']; ?>'
364
							, {<?php echo $idvar; ?>: <?php echo (int) $object->id; ?>, action:'add_free_text'}
365
							, true
366
							, true
367
							, <?php echo !empty($conf->global->SUBTOTAL_ALLOW_ADD_LINE_UNDER_TITLE) ? 'true' : 'false'; ?>
368
						);
369
					});
370
				});
371
		 	</script>
372
		 <?php
373
	}
374
375
	function showSelectTitleToAdd(&$object)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
376
	{
377
		global $langs;
378
379
		dol_include_once('/subtotal/class/subtotal.class.php');
380
		dol_include_once('/subtotal/lib/subtotal.lib.php');
381
		$TTitle = TSubtotal::getAllTitleFromDocument($object);
382
383
		?>
384
		<script type="text/javascript">
385
			$(function() {
386
				var add_button = $("#addline");
387
388
				if (add_button.length > 0)
389
				{
390
					add_button.closest('tr').prev('tr.liste_titre').children('td:last').addClass('center').text("<?php echo $langs->trans('subtotal_title_to_add_under_title'); ?>");
391
					var select_title = $(<?php echo json_encode(getHtmlSelectTitle($object)); ?>);
392
393
					add_button.before(select_title);
394
				}
395
			});
396
		</script>
397
		<?php
398
	}
399
400
401
	function formBuilddocOptions($parameters, &$object) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
402
	/* Réponse besoin client */
403
404
		global $conf, $langs, $bc;
405
406
		$action = GETPOST('action', 'none');
407
		$TContext = explode(':',$parameters['context']);
408
		if (
409
				in_array('invoicecard',$TContext)
410
		        || in_array('invoicesuppliercard',$TContext)
411
				|| in_array('propalcard',$TContext)
412
				|| in_array('ordercard',$TContext)
413
		        || in_array('ordersuppliercard',$TContext)
414
				|| in_array('invoicereccard',$TContext)
415
			)
416
	        {
417
	            $hideInnerLines	= isset( $_SESSION['subtotal_hideInnerLines_'.$parameters['modulepart']][$object->id] ) ?  $_SESSION['subtotal_hideInnerLines_'.$parameters['modulepart']][$object->id] : 0;
418
	            $hidedetails	= isset( $_SESSION['subtotal_hidedetails_'.$parameters['modulepart']][$object->id] ) ?  $_SESSION['subtotal_hidedetails_'.$parameters['modulepart']][$object->id] : 0;
419
				$hidepricesDefaultConf = !empty($conf->global->SUBTOTAL_HIDE_PRICE_DEFAULT_CHECKED)?$conf->global->SUBTOTAL_HIDE_PRICE_DEFAULT_CHECKED:0;
420
				$hideprices= isset( $_SESSION['subtotal_hideprices_'.$parameters['modulepart']][$object->id] ) ?  $_SESSION['subtotal_hideprices_'.$parameters['modulepart']][$object->id] : $hidepricesDefaultConf;
421
422
				$var=false;
423
				$out = '';
424
		     	$out.= '<tr '.$bc[$var].'>
425
		     			<td colspan="4" align="right">
426
		     				<label for="hideInnerLines">'.$langs->trans('HideInnerLines').'</label>
427
		     				<input type="checkbox" onclick="if($(this).is(\':checked\')) { $(\'#hidedetails\').prop(\'checked\', \'checked\')  }" id="hideInnerLines" name="hideInnerLines" value="1" '.(( $hideInnerLines ) ? 'checked="checked"' : '' ).' />
428
		     			</td>
429
		     			</tr>';
430
431
		     	$var=!$var;
0 ignored issues
show
introduced by
The condition $var is always false.
Loading history...
432
		     	$out.= '<tr '.$bc[$var].'>
433
		     			<td colspan="4" align="right">
434
		     				<label for="hidedetails">'.$langs->trans('SubTotalhidedetails').'</label>
435
		     				<input type="checkbox" id="hidedetails" name="hidedetails" value="1" '.(( $hidedetails ) ? 'checked="checked"' : '' ).' />
436
		     			</td>
437
		     			</tr>';
438
439
		     	$var=!$var;
0 ignored issues
show
introduced by
The condition $var is always true.
Loading history...
440
		     	$out.= '<tr '.$bc[$var].'>
441
		     			<td colspan="4" align="right">
442
		     				<label for="hideprices">'.$langs->trans('SubTotalhidePrice').'</label>
443
		     				<input type="checkbox" id="hideprices" name="hideprices" value="1" '.(( $hideprices ) ? 'checked="checked"' : '' ).' />
444
		     			</td>
445
		     			</tr>';
446
447
448
449
				if (
450
					(in_array('propalcard',$TContext) && !empty($conf->global->SUBTOTAL_PROPAL_ADD_RECAP))
451
					|| (in_array('ordercard',$TContext) && !empty($conf->global->SUBTOTAL_COMMANDE_ADD_RECAP))
452
				    || (in_array('ordersuppliercard',$TContext) && !empty($conf->global->SUBTOTAL_COMMANDE_ADD_RECAP))
453
					|| (in_array('invoicecard',$TContext) && !empty($conf->global->SUBTOTAL_INVOICE_ADD_RECAP))
454
				    || (in_array('invoicesuppliercard',$TContext) && !empty($conf->global->SUBTOTAL_INVOICE_ADD_RECAP))
455
					|| (in_array('invoicereccard',$TContext)  && !empty($conf->global->SUBTOTAL_INVOICE_ADD_RECAP ))
456
				)
457
				{
458
					$var=!$var;
0 ignored issues
show
introduced by
The condition $var is always false.
Loading history...
459
					$out.= '
460
						<tr '.$bc[$var].'>
461
							<td colspan="4" align="right">
462
								<label for="subtotal_add_recap">'.$langs->trans('subtotal_add_recap').'</label>
463
								<input type="checkbox" id="subtotal_add_recap" name="subtotal_add_recap" value="1" '.( GETPOST('subtotal_add_recap', 'none') ? 'checked="checked"' : '' ).' />
464
							</td>
465
						</tr>';
466
				}
467
468
469
				$this->resprints = $out;
470
			}
471
472
473
        return 1;
474
	}
475
476
    function formEditProductOptions($parameters, &$object, &$action, $hookmanager)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
477
    {
478
479
    	if (in_array('invoicecard',explode(':',$parameters['context'])))
480
        {
481
482
        }
483
484
        return 0;
485
    }
486
487
	function ODTSubstitutionLine(&$parameters, &$object, $action, $hookmanager) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
488
		global $conf;
489
490
		if($action === 'builddoc') {
491
492
			$line = &$parameters['line'];
493
			$object = &$parameters['object'];
494
			$substitutionarray = &$parameters['substitutionarray'];
495
496
            $substitutionarray['line_not_modsubtotal'] = true;
497
            $substitutionarray['line_modsubtotal'] = false;
498
            $substitutionarray['line_modsubtotal_total'] = false;
499
            $substitutionarray['line_modsubtotal_title'] = false;
500
501
			if($line->product_type == 9 && $line->special_code == $this->module_number) {
502
				$substitutionarray['line_modsubtotal'] = 1;
503
                $substitutionarray['line_not_modsubtotal'] = false;
504
505
				$substitutionarray['line_price_ht']
506
					 = $substitutionarray['line_price_vat']
507
					 = $substitutionarray['line_price_ttc']
508
					 = $substitutionarray['line_vatrate']
509
					 = $substitutionarray['line_qty']
510
					 = $substitutionarray['line_up']
511
					 = '';
512
513
				if($line->qty>90) {
514
					$substitutionarray['line_modsubtotal_total'] = true;
515
516
					//list($total, $total_tva, $total_ttc, $TTotal_tva) = $this->getTotalLineFromObject($object, $line, '', 1);
517
                    $TInfo = $this->getTotalLineFromObject($object, $line, '', 1);
518
519
					$substitutionarray['line_price_ht'] = price($TInfo[0]);
520
					$substitutionarray['line_price_vat'] = price($TInfo[1]);
521
					$substitutionarray['line_price_ttc'] = price($TInfo[2]);
522
				} else {
523
					$substitutionarray['line_modsubtotal_title'] = true;
524
				}
525
526
527
			}
528
			else{
529
				$substitutionarray['line_not_modsubtotal'] = true;
530
				$substitutionarray['line_modsubtotal'] = 0;
531
			}
532
533
		}
534
535
		return 0;
536
	}
537
538
	function createFrom($parameters, &$object, $action, $hookmanager) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
539
540
		if (
541
				in_array('invoicecard',explode(':',$parameters['context']))
542
		        || in_array('invoicesuppliercard',explode(':',$parameters['context']))
543
				|| in_array('propalcard',explode(':',$parameters['context']))
544
		        || in_array('supplier_proposalcard',explode(':',$parameters['context']))
545
				|| in_array('ordercard',explode(':',$parameters['context']))
546
		        || in_array('ordersuppliercard',explode(':',$parameters['context']))
547
				|| in_array('invoicereccard',explode(':',$parameters['context']))
548
		) {
549
550
			global $db;
551
552
			$objFrom = $parameters['objFrom'];
553
554
			if(empty($object->lines) && method_exists($object, 'fetch_lines')) $object->fetch_lines();
555
556
			foreach($objFrom->lines as $k=> &$lineOld) {
557
558
					if($lineOld->product_type == 9 && $lineOld->info_bits > 0 ) {
559
560
							$line = & $object->lines[$k];
561
562
							$idLine = (int) ($line->id ? $line->id : $line->rowid);
563
564
							if($line->info_bits != $lineOld->info_bits) {
565
								$db->query("UPDATE ".MAIN_DB_PREFIX.$line->table_element."
566
								SET info_bits=".(int)$lineOld->info_bits."
567
								WHERE rowid = ".$idLine."
568
								");
569
							}
570
571
					}
572
573
574
			}
575
576
577
		}
578
579
		return 0;
580
	}
581
582
	function doActions($parameters, &$object, $action, $hookmanager)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
583
	{
584
		global $db, $conf, $langs,$user;
585
586
		dol_include_once('/subtotal/class/subtotal.class.php');
587
		dol_include_once('/subtotal/lib/subtotal.lib.php');
588
		require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
589
590
		$showBlockExtrafields = GETPOST('showBlockExtrafields', 'none');
591
592
		if($object->element=='facture') $idvar = 'facid';
593
		else $idvar = 'id';
594
595
		if ($action == 'updateligne' || $action == 'updateline')
596
		{
597
			$found = false;
598
			$lineid = GETPOST('lineid', 'int');
599
			foreach ($object->lines as &$line)
600
			{
601
602
				if ($line->id == $lineid && TSubtotal::isModSubtotalLine($line))
603
				{
604
					$found = true;
605
					if(TSubtotal::isTitle($line) && !empty($showBlockExtrafields)) {
606
						$extrafieldsline = new ExtraFields($db);
607
						$extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
608
						$extrafieldsline->setOptionalsFromPost($extralabelsline, $line);
609
					}
610
					_updateSubtotalLine($object, $line);
611
					_updateSubtotalBloc($object, $line);
612
613
					TSubtotal::generateDoc($object);
614
					break;
615
				}
616
			}
617
618
			if ($found)
619
			{
620
				header('Location: '.$_SERVER['PHP_SELF'].'?'.$idvar.'='.$object->id);
621
				exit; // Surtout ne pas laisser Dolibarr faire du traitement sur le updateligne sinon ça plante les données de la ligne
622
			}
623
		}
624
		else if($action === 'builddoc') {
625
626
			if (
627
				in_array('invoicecard',explode(':',$parameters['context']))
628
				|| in_array('propalcard',explode(':',$parameters['context']))
629
				|| in_array('ordercard',explode(':',$parameters['context']))
630
			    || in_array('ordersuppliercard',explode(':',$parameters['context']))
631
			    || in_array('invoicesuppliercard',explode(':',$parameters['context']))
632
			    || in_array('supplier_proposalcard',explode(':',$parameters['context']))
633
			)
634
	        {
635
				if(in_array('invoicecard',explode(':',$parameters['context']))) {
636
					$sessname = 'subtotal_hideInnerLines_facture';
637
					$sessname2 = 'subtotal_hidedetails_facture';
638
					$sessname3 = 'subtotal_hideprices_facture';
639
				}
640
				elseif(in_array('invoicesuppliercard',explode(':',$parameters['context']))) {
641
				    $sessname = 'subtotal_hideInnerLines_facture_fournisseur';
642
				    $sessname2 = 'subtotal_hidedetails_facture_fournisseur';
643
				    $sessname3 = 'subtotal_hideprices_facture_fournisseur';
644
				}
645
				elseif(in_array('propalcard',explode(':',$parameters['context']))) {
646
					$sessname = 'subtotal_hideInnerLines_propal';
647
					$sessname2 = 'subtotal_hidedetails_propal';
648
					$sessname3 = 'subtotal_hideprices_propal';
649
				}
650
				elseif(in_array('supplier_proposalcard',explode(':',$parameters['context']))) {
651
				    $sessname = 'subtotal_hideInnerLines_supplier_proposal';
652
				    $sessname2 = 'subtotal_hidedetails_supplier_proposal';
653
				    $sessname3 = 'subtotal_hideprices_supplier_proposal';
654
				}
655
				elseif(in_array('ordercard',explode(':',$parameters['context']))) {
656
					$sessname = 'subtotal_hideInnerLines_commande';
657
					$sessname2 = 'subtotal_hidedetails_commande';
658
					$sessname3 = 'subtotal_hideprices_commande';
659
				}
660
				elseif(in_array('ordersuppliercard',explode(':',$parameters['context']))) {
661
				    $sessname = 'subtotal_hideInnerLines_commande_fournisseur';
662
				    $sessname2 = 'subtotal_hidedetails_commande_fournisseur';
663
				    $sessname3 = 'subtotal_hideprices_commande_fournisseur';
664
				}
665
				else {
666
					$sessname = 'subtotal_hideInnerLines_unknown';
667
					$sessname2 = 'subtotal_hidedetails_unknown';
668
					$sessname3 = 'subtotal_hideprices_unknown';
669
				}
670
671
				global $hideprices;
672
673
				$hideInnerLines = GETPOST('hideInnerLines', 'int');
674
				if(empty($_SESSION[$sessname]) || !is_array($_SESSION[$sessname][$object->id]) ) $_SESSION[$sessname] = array(); // prevent old system
675
				$_SESSION[$sessname][$object->id] = $hideInnerLines;
676
677
				$hidedetails= GETPOST('hidedetails', 'int');
678
				if(empty($_SESSION[$sessname2]) || !is_array($_SESSION[$sessname2][$object->id]) ) $_SESSION[$sessname2] = array(); // prevent old system
679
				$_SESSION[$sessname2][$object->id] = $hidedetails;
680
681
				$hideprices= GETPOST('hideprices', 'int');
682
				if(empty($_SESSION[$sessname3]) || !is_array($_SESSION[$sessname3][$object->id]) ) $_SESSION[$sessname3] = array(); // prevent old system
683
				$_SESSION[$sessname3][$object->id] = $hideprices;
684
685
				foreach($object->lines as &$line) {
686
					if ($line->product_type == 9 && $line->special_code == $this->module_number) {
687
688
                        if($line->qty>=90) {
689
                            $line->modsubtotal_total = 1;
690
                        }
691
                        else{
692
                            $line->modsubtotal_title = 1;
693
                        }
694
695
						$line->total_ht = $this->getTotalLineFromObject($object, $line, '');
696
					}
697
	        	}
698
	        }
699
700
		}
701
		else if($action === 'confirm_delete_all_lines' && GETPOST('confirm', 'none')=='yes') {
702
703
			$Tab = TSubtotal::getLinesFromTitleId($object, GETPOST('lineid', 'int'), true);
704
			foreach($Tab as $line) {
705
                $result = 0;
706
707
				$idLine = $line->id;
708
				/**
709
				 * @var $object Facture
710
				 */
711
				if($object->element=='facture') $result = $object->deleteline($idLine);
712
				/**
713
				 * @var $object Facture fournisseur
714
				 */
715
				else if($object->element=='invoice_supplier')
716
				{
717
					$result = $object->deleteline($idLine);
718
				}
719
				/**
720
				 * @var $object Propal
721
				 */
722
				else if($object->element=='propal') $result = $object->deleteline($idLine);
723
				/**
724
				 * @var $object Propal Fournisseur
725
				 */
726
				else if($object->element=='supplier_proposal') $result = $object->deleteline($idLine);
727
				/**
728
				 * @var $object Commande
729
				 */
730
				else if($object->element=='commande')
731
				{
732
					if ((float) DOL_VERSION >= 5.0) $result = $object->deleteline($user, $idLine);
733
					else $result = $object->deleteline($idLine);
734
				}
735
				/**
736
				 * @var $object Commande fournisseur
737
				 */
738
				else if($object->element=='order_supplier')
739
				{
740
                    			$result = $object->deleteline($idLine);
741
				}
742
				/**
743
				 * @var $object Facturerec
744
				 */
745
				else if($object->element=='facturerec') $result = $object->deleteline($idLine);
746
				/**
747
				 * @var $object Expedition
748
				 */
749
				else if($object->element=='shipping') $result = $object->deleteline($user, $idLine);
750
751
                if ($result < 0) $error++;
752
			}
753
754
            if ($error) {
755
                setEventMessages($object->error, $object->errors, 'errors');
756
                $db->rollback();
757
            } else {
758
                $db->commit();
759
            }
760
761
			header('location:?id='.$object->id);
762
			exit;
763
764
		}
765
		else if ($action == 'duplicate')
766
		{
767
			$lineid = GETPOST('lineid', 'int');
768
			$nbDuplicate = TSubtotal::duplicateLines($object, $lineid, true);
769
770
			if ($nbDuplicate > 0) setEventMessage($langs->trans('subtotal_duplicate_success', $nbDuplicate));
771
			elseif ($nbDuplicate == 0) setEventMessage($langs->trans('subtotal_duplicate_lineid_not_found'), 'warnings');
772
			else setEventMessage($langs->trans('subtotal_duplicate_error'), 'errors');
773
774
			header('Location: ?id='.$object->id);
775
			exit;
776
		}
777
778
		return 0;
779
	}
780
781
	function formAddObjectLine ($parameters, &$object, &$action, $hookmanager) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
782
		return 0;
783
	}
784
785
	function changeRoundingMode($parameters, &$object, &$action, $hookmanager)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
786
	{
787
		global $conf;
788
		if (!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) && !empty($object->table_element_line) && in_array($object->element, array('commande', 'facture', 'propal')))
789
		{
790
			if ($object->element == 'commande')
791
				$obj = new OrderLine($object->db);
792
			if ($object->element == 'propal')
793
				$obj = new PropaleLigne($object->db);
794
			if ($object->element == 'facture')
795
				$obj = new FactureLigne($object->db);
796
			if (!empty($parameters['fk_element']))
797
			{
798
799
				if($obj->fetch($parameters['fk_element'])){
800
					$obj->id= $obj->rowid;
801
					if (empty($obj->array_options))
802
						$obj->fetch_optionals();
803
					if (!empty($obj->array_options['options_subtotal_nc']))
804
						return 1;
805
				}
806
			}
807
		}
808
809
		return 0;
810
	}
811
812
	function getArrayOfLineForAGroup(&$object, $lineid) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
813
		$qty_line = 0;
814
        $qty_end_line = 0;
815
		$found = false;
816
		$Tab= array();
817
818
		foreach($object->lines as $l) {
819
		    $lid = (!empty($l->rowid) ? $l->rowid : $l->id);
820
821
			if($lid == $lineid && $l->qty > 0 && $l->qty < 10) {
822
				$found = true;
823
				$qty_line = $l->qty;
824
                $qty_end_line = 100 - $qty_line;
825
			}
826
827
			if($found) {
828
                if ($l->special_code == $this->module_number && $lid != $lineid && ($l->qty <= $qty_line || $l->qty >= $qty_end_line)) {
829
                    if ($l->qty == $qty_end_line) $Tab[] = $lid;
830
                    break;
831
                }
832
                else $Tab[] = $lid;
833
			}
834
		}
835
836
		return $Tab;
837
	}
838
839
	function getTotalLineFromObject(&$object, &$line, $use_level=false, $return_all=0) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
840
		global $conf;
841
842
		$rang = $line->rang;
843
		$qty_line = $line->qty;
844
		$lvl = 0;
845
        if (TSubtotal::isSubtotal($line)) $lvl = TSubtotal::getNiveau($line);
846
847
		$title_break = TSubtotal::getParentTitleOfLine($object, $rang, $lvl);
848
849
		$total = 0;
850
		$total_tva = 0;
851
		$total_ttc = 0;
852
		$TTotal_tva = array();
853
854
855
		$sign=1;
856
		if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
857
858
		if (GETPOST('action', 'none') == 'builddoc') $builddoc = true;
859
		else $builddoc = false;
860
861
		dol_include_once('/subtotal/class/subtotal.class.php');
862
863
		$TLineReverse = array_reverse($object->lines);
864
865
		foreach($TLineReverse as $l)
866
		{
867
			$l->total_ttc = doubleval($l->total_ttc);
868
			$l->total_ht = doubleval($l->total_ht);
869
870
			//print $l->rang.'>='.$rang.' '.$total.'<br/>';
871
            if ($l->rang>=$rang) continue;
872
            if (!empty($title_break) && $title_break->id == $l->id) break;
873
            elseif (!TSubtotal::isModSubtotalLine($l))
874
            {
875
                // TODO retirer le test avec $builddoc quand Dolibarr affichera le total progression sur la card et pas seulement dans le PDF
876
                if ($builddoc && $object->element == 'facture' && $object->type==Facture::TYPE_SITUATION)
877
                {
878
                    if ($l->situation_percent > 0 && !empty($l->total_ht))
879
                    {
880
                        $prev_progress = 0;
881
                        $progress = 1;
882
                        if (method_exists($l, 'get_prev_progress'))
883
                        {
884
                            $prev_progress = $l->get_prev_progress($object->id);
885
                            $progress = ($l->situation_percent - $prev_progress) / 100;
886
                        }
887
888
                        $result = $sign * ($l->total_ht / ($l->situation_percent / 100)) * $progress;
889
                        $total+= $result;
890
                        // TODO check si les 3 lignes du dessous sont corrects
891
                        $total_tva += $sign * ($l->total_tva / ($l->situation_percent / 100)) * $progress;
892
                        $TTotal_tva[$l->tva_tx] += $sign * ($l->total_tva / ($l->situation_percent / 100)) * $progress;
893
                        $total_ttc += $sign * ($l->total_tva / ($l->total_ttc / 100)) * $progress;
894
895
                    }
896
                }
897
                else
898
                {
899
                    $total += $l->total_ht;
900
                    $total_tva += $l->total_tva;
901
                    $TTotal_tva[$l->tva_tx] += $l->total_tva;
902
                    $total_ttc += $l->total_ttc;
903
                }
904
            }
905
		}
906
		if (!$return_all) return $total;
907
		else return array($total, $total_tva, $total_ttc, $TTotal_tva);
908
	}
909
910
	/**
911
	 * @param $pdf          TCPDF               PDF object
912
	 * @param $object       CommonObject        dolibarr object
913
	 * @param $line         CommonObjectLine    dolibarr object line
914
	 * @param $label        string
915
	 * @param $description  string
916
	 * @param $posx         float               horizontal position
917
	 * @param $posy         float               vertical position
918
	 * @param $w            float               width
919
	 * @param $h            float               height
920
	 */
921
	function pdf_add_total(&$pdf,&$object, &$line, $label, $description,$posx, $posy, $w, $h) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
922
		global $conf,$subtotal_last_title_posy,$langs;
923
924
		$hideInnerLines = GETPOST('hideInnerLines', 'int');
925
		if (!empty($conf->global->SUBTOTAL_ONE_LINE_IF_HIDE_INNERLINES) && $hideInnerLines && !empty($subtotal_last_title_posy))
926
		{
927
			$posy = $subtotal_last_title_posy;
928
			$subtotal_last_title_posy = null;
929
		}
930
931
		$hidePriceOnSubtotalLines = GETPOST('hide_price_on_subtotal_lines', 'int');
932
933
		if($object->element == 'shipping' || $object->element == 'delivery')
934
		{
935
			$hidePriceOnSubtotalLines = 1;
936
		}
937
938
		$set_pagebreak_margin = false;
939
		if(method_exists('Closure','bind')) {
940
			$pageBreakOriginalValue = $pdf->AcceptPageBreak();
941
			$sweetsThief = function ($pdf) {
942
		    		return $pdf->bMargin ;
943
			};
944
			$sweetsThief = Closure::bind($sweetsThief, null, $pdf);
945
946
			$bMargin  = $sweetsThief($pdf);
947
948
			$pdf->SetAutoPageBreak( false );
949
950
			$set_pagebreak_margin = true;
951
		}
952
953
954
		if($line->qty==99)
955
			$pdf->SetFillColor(220,220,220);
956
		elseif ($line->qty==98)
957
			$pdf->SetFillColor(230,230,230);
958
		else
959
			$pdf->SetFillColor(240,240,240);
960
961
		$style = 'B';
962
		if (!empty($conf->global->SUBTOTAL_SUBTOTAL_STYLE)) $style = $conf->global->SUBTOTAL_SUBTOTAL_STYLE;
963
964
		$pdf->SetFont('', $style, 9);
965
966
		$pdf->writeHTMLCell($w, $h, $posx, $posy, $label, 0, 1, false, true, 'R',true);
967
//		var_dump($bMargin);
968
		$pageAfter = $pdf->getPage();
969
970
		//Print background
971
		$cell_height = $pdf->getStringHeight($w, $label);
972
973
		if(!empty($object->subtotalPdfModelInfo->cols)){
974
			include_once __DIR__ . '/staticPdf.model.php';
975
			$staticPdfModel = new ModelePDFStatic($object->db);
976
			$staticPdfModel->marge_droite 	= $object->subtotalPdfModelInfo->marge_droite;
977
			$staticPdfModel->marge_gauche 	= $object->subtotalPdfModelInfo->marge_gauche;
978
			$staticPdfModel->page_largeur 	= $object->subtotalPdfModelInfo->page_largeur;
979
			$staticPdfModel->page_hauteur 	= $object->subtotalPdfModelInfo->page_hauteur;
980
			$staticPdfModel->cols 			= $object->subtotalPdfModelInfo->cols;
981
			$staticPdfModel->defaultTitlesFieldsStyle 	= $object->subtotalPdfModelInfo->defaultTitlesFieldsStyle;
982
			$staticPdfModel->defaultContentsFieldsStyle = $object->subtotalPdfModelInfo->defaultContentsFieldsStyle;
983
			$staticPdfModel->prepareArrayColumnField($object, $langs);
984
985
			$pdf->SetXY($object->subtotalPdfModelInfo->marge_droite, $posy);
986
			$pdf->MultiCell($object->subtotalPdfModelInfo->page_largeur - $object->subtotalPdfModelInfo->marge_gauche - $object->subtotalPdfModelInfo->marge_droite, $cell_height, '', 0, '', 1);
987
		}
988
		else{
989
			$pdf->SetXY($posx, $posy);
990
			$pdf->MultiCell($pdf->page_largeur - $pdf->marge_droite, $cell_height, '', 0, '', 1);
991
		}
992
993
		if (!$hidePriceOnSubtotalLines) {
994
			$total_to_print = price($line->total);
995
996
			if (!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS))
997
			{
998
				$TTitle = TSubtotal::getAllTitleFromLine($line);
999
				foreach ($TTitle as &$line_title)
1000
				{
1001
					if (!empty($line_title->array_options['options_subtotal_nc']))
1002
					{
1003
						$total_to_print = ''; // TODO Gestion "Compris/Non compris", voir si on affiche une annotation du genre "NC"
1004
						break;
1005
					}
1006
				}
1007
			}
1008
1009
			if($total_to_print !== '') {
1010
1011
				if (GETPOST('hideInnerLines', 'int'))
1012
				{
1013
					// Dans le cas des lignes cachés, le calcul est déjà fait dans la méthode beforePDFCreation et les lignes de sous-totaux sont déjà renseignés
1014
//					$line->TTotal_tva
1015
//					$line->total_ht
1016
//					$line->total_tva
1017
//					$line->total
1018
//					$line->total_ttc
1019
				}
1020
				else
1021
				{
1022
					//					list($total, $total_tva, $total_ttc, $TTotal_tva) = $this->getTotalLineFromObject($object, $line, '', 1);
1023
1024
					$TInfo = $this->getTotalLineFromObject($object, $line, '', 1);
1025
					$TTotal_tva = $TInfo[3];
1026
					$total_to_print = price($TInfo[0]);
1027
1028
                    $line->total_ht = $TInfo[0];
1029
					$line->total = $TInfo[0];
1030
					if (!TSubtotal::isModSubtotalLine($line)) $line->total_tva = $TInfo[1];
1031
					$line->total_ttc = $TInfo[2];
1032
				}
1033
			}
1034
1035
			$pdf->SetXY($pdf->postotalht, $posy);
1036
			if($set_pagebreak_margin) $pdf->SetAutoPageBreak( $pageBreakOriginalValue , $bMargin);
1037
1038
			if(!empty($object->subtotalPdfModelInfo->cols)){
1039
				$staticPdfModel->printStdColumnContent($pdf, $posy, 'totalexcltax', $total_to_print);
1040
			}
1041
			else{
1042
				$pdf->MultiCell($pdf->page_largeur-$pdf->marge_droite-$pdf->postotalht, 3, $total_to_print, 0, 'R', 0);
1043
			}
1044
		}
1045
		else{
1046
			if($set_pagebreak_margin) $pdf->SetAutoPageBreak( $pageBreakOriginalValue , $bMargin);
1047
		}
1048
1049
		$posy = $posy + $cell_height;
1050
		$pdf->SetXY($posx, $posy);
1051
1052
1053
	}
1054
1055
	/**
1056
	 * @param $pdf          TCPDF               PDF object
1057
	 * @param $object       CommonObject        dolibarr object
1058
	 * @param $line         CommonObjectLine    dolibarr object line
1059
	 * @param $label        string
1060
	 * @param $description  string
1061
	 * @param $posx         float               horizontal position
1062
	 * @param $posy         float               vertical position
1063
	 * @param $w            float               width
1064
	 * @param $h            float               height
1065
	 */
1066
	function pdf_add_title(&$pdf,&$object, &$line, $label, $description,$posx, $posy, $w, $h) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1067
1068
		global $db,$conf,$subtotal_last_title_posy;
1069
1070
		$subtotal_last_title_posy = $posy;
1071
		$pdf->SetXY ($posx, $posy);
1072
1073
		$hideInnerLines = GETPOST('hideInnerLines', 'int');
1074
1075
1076
1077
		$style = ($line->qty==1) ? 'BU' : 'BUI';
1078
		if (!empty($conf->global->SUBTOTAL_TITLE_STYLE)) $style = $conf->global->SUBTOTAL_TITLE_STYLE;
1079
1080
		if($hideInnerLines) {
1081
			if($line->qty==1)$pdf->SetFont('', $style, 9);
1082
			else
1083
			{
1084
				if (!empty($conf->global->SUBTOTAL_STYLE_TITRES_SI_LIGNES_CACHEES)) $style = $conf->global->SUBTOTAL_STYLE_TITRES_SI_LIGNES_CACHEES;
1085
				$pdf->SetFont('', $style, 9);
1086
			}
1087
		}
1088
		else {
1089
1090
			if($line->qty==1)$pdf->SetFont('', $style, 9); //TODO if super utile
1091
			else $pdf->SetFont('', $style, 9);
1092
1093
		}
1094
1095
		if ($label === strip_tags($label) && $label === dol_html_entity_decode($label, ENT_QUOTES)) $pdf->MultiCell($w, $h, $label, 0, 'L'); // Pas de HTML dans la chaine
1096
		else $pdf->writeHTMLCell($w, $h, $posx, $posy, $label, 0, 1, false, true, 'J',true); // et maintenant avec du HTML
1097
1098
		if($description && !$hidedesc) {
1099
			$posy = $pdf->GetY();
1100
1101
			$pdf->SetFont('', '', 8);
1102
1103
			$pdf->writeHTMLCell($w, $h, $posx, $posy, $description, 0, 1, false, true, 'J',true);
1104
1105
		}
1106
1107
	}
1108
1109
	function pdf_writelinedesc_ref($parameters=array(), &$object, &$action='') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1110
	// ultimate PDF hook O_o
1111
1112
		return $this->pdf_writelinedesc($parameters,$object,$action);
1113
1114
	}
1115
1116
	function isModSubtotalLine(&$parameters, &$object) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1117
1118
		if(is_array($parameters)) {
1119
			$i = & $parameters['i'];
1120
		}
1121
		else {
1122
			$i = (int)$parameters;
1123
		}
1124
1125
		$line = $object->lines[$i];
1126
1127
		if($object->element == 'shipping' || $object->element == 'delivery')
1128
		{
1129
			dol_include_once('/commande/class/commande.class.php');
1130
			$line = new OrderLine($object->db);
1131
			$line->fetch($object->lines[$i]->fk_origin_line);
1132
		}
1133
1134
1135
		if($line->special_code == $this->module_number && $line->product_type == 9) {
1136
			return true;
1137
		}
1138
1139
		return false;
1140
1141
	}
1142
1143
	function pdf_getlineqty($parameters=array(), &$object, &$action='') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1144
		global $conf,$hideprices;
1145
1146
		if($this->isModSubtotalLine($parameters,$object) ){
1147
			$this->resprints = ' ';
1148
1149
			if((float)DOL_VERSION<=3.6) {
1150
				return '';
1151
			}
1152
			else if((float)DOL_VERSION>=3.8) {
1153
				return 1;
1154
			}
1155
1156
		}
1157
		elseif(!empty($hideprices)) {
1158
			$this->resprints = $object->lines[$parameters['i']]->qty;
1159
			return 1;
1160
		}
1161
		elseif (!empty($conf->global->SUBTOTAL_IF_HIDE_PRICES_SHOW_QTY))
1162
		{
1163
			$hideInnerLines = GETPOST('hideInnerLines', 'int');
1164
			$hidedetails = GETPOST('hidedetails', 'int');
1165
			if (empty($hideInnerLines) && !empty($hidedetails))
1166
			{
1167
				$this->resprints = $object->lines[$parameters['i']]->qty;
1168
			}
1169
		}
1170
1171
		if(is_array($parameters)) $i = & $parameters['i'];
1172
		else $i = (int)$parameters;
1173
1174
		/** Attention, ici on peut ce retrouver avec un objet de type stdClass à cause de l'option cacher le détail des ensembles avec la notion de Non Compris (@see beforePDFCreation()) et dû à l'appel de TSubtotal::hasNcTitle() */
1175
		if (empty($object->lines[$i]->id)) return 0; // hideInnerLines => override $object->lines et Dolibarr ne nous permet pas de mettre à jour la variable qui conditionne la boucle sur les lignes (PR faite pour 6.0)
1176
1177
		if(empty($object->lines[$i]->array_options)) $object->lines[$i]->fetch_optionals();
1178
1179
		if (!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) && (!empty($object->lines[$i]->array_options['options_subtotal_nc']) || TSubtotal::hasNcTitle($object->lines[$i])) )
1180
		{
1181
			if (!in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1182
			{
1183
				$this->resprints = ' ';
1184
				return 1;
1185
			}
1186
		}
1187
1188
		return 0;
1189
	}
1190
1191
	function pdf_getlinetotalexcltax($parameters=array(), &$object, &$action='') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1192
	    global $conf, $hideprices, $hookmanager;
1193
1194
		if(is_array($parameters)) $i = & $parameters['i'];
1195
		else $i = (int)$parameters;
1196
1197
		if($this->isModSubtotalLine($parameters,$object) ){
1198
1199
			$this->resprints = ' ';
1200
1201
			if((float)DOL_VERSION<=3.6) {
1202
				return '';
1203
			}
1204
			else if((float)DOL_VERSION>=3.8) {
1205
				return 1;
1206
			}
1207
1208
		}
1209
		elseif (!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS))
1210
		{
1211
			if (!in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1212
			{
1213
				if (!empty($object->lines[$i]->array_options['options_subtotal_nc']))
1214
				{
1215
					$this->resprints = ' ';
1216
					return 1;
1217
				}
1218
1219
				$TTitle = TSubtotal::getAllTitleFromLine($object->lines[$i]);
1220
				foreach ($TTitle as &$line_title)
1221
				{
1222
					if (!empty($line_title->array_options['options_subtotal_nc']))
1223
					{
1224
						$this->resprints = ' ';
1225
						return 1;
1226
					}
1227
				}
1228
			}
1229
		}
1230
		if (GETPOST('hideInnerLines', 'int') && !empty($conf->global->SUBTOTAL_REPLACE_WITH_VAT_IF_HIDE_INNERLINES)){
1231
		    $this->resprints = price($object->lines[$i]->total_ht);
1232
		}
1233
1234
		// Si la gestion C/NC est active et que je suis sur un ligne dont l'extrafield est coché
1235
		if (
1236
			!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) &&
1237
			(!empty($object->lines[$i]->array_options['options_subtotal_nc']) || TSubtotal::hasNcTitle($object->lines[$i]))
1238
		)
1239
		{
1240
			// alors je dois vérifier si la méthode fait partie de la conf qui l'exclue
1241
			if (!in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1242
			{
1243
				$this->resprints = ' ';
1244
1245
				// currentcontext à modifier celon l'appel
1246
				$params = array('parameters' => $parameters, 'currentmethod' => 'pdf_getlinetotalexcltax', 'currentcontext'=>'subtotal_hide_nc', 'i' => $i);
1247
				return $this->callHook($object, $hookmanager, $action, $params); // return 1 (qui est la valeur par défaut) OU -1 si erreur OU overrideReturn (contient -1 ou 0 ou 1)
1248
			}
1249
		}
1250
		// Cache le prix pour les lignes standards dolibarr qui sont dans un ensemble
1251
		else if (!empty($hideprices))
1252
		{
1253
			// Check if a title exist for this line && if the title have subtotal
1254
			$lineTitle = TSubtotal::getParentTitleOfLine($object, $object->lines[$i]->rang);
1255
			if ($lineTitle && TSubtotal::titleHasTotalLine($object, $lineTitle, true))
1256
			{
1257
1258
				$this->resprints = ' ';
1259
1260
				// currentcontext à modifier celon l'appel
1261
				$params = array('parameters' => $parameters, 'currentmethod' => 'pdf_getlinetotalexcltax', 'currentcontext'=>'subtotal_hideprices', 'i' => $i);
1262
				return $this->callHook($object, $hookmanager, $action, $params); // return 1 (qui est la valeur par défaut) OU -1 si erreur OU overrideReturn (contient -1 ou 0 ou 1)
1263
			}
1264
		}
1265
1266
		return 0;
1267
	}
1268
1269
	/**
1270
	 * Remplace le retour de la méthode qui l'appelle par un standard 1 ou autre chose celon le hook
1271
	 * @return int 1, 0, -1
1272
	 */
1273
	private function callHook(&$object, &$hookmanager, $action, $params, $defaultReturn = 1)
1274
	{
1275
		$reshook=$hookmanager->executeHooks('subtotalHidePrices',$params, $object, $action);
1276
		if ($reshook < 0)
1277
		{
1278
			$this->error = $hookmanager->error;
1279
			$this->errors = $hookmanager->errors;
1280
			return -1;
1281
		}
1282
		elseif (empty($reshook))
1283
		{
1284
			$this->resprints .= $hookmanager->resprints;
1285
		}
1286
		else
1287
		{
1288
			$this->resprints = $hookmanager->resprints;
1289
1290
			// override return (use  $this->results['overrideReturn'] or $this->resArray['overrideReturn'] in other module action_xxxx.class.php )
1291
			if(isset($hookmanager->resArray['overrideReturn']))
1292
			{
1293
				return $hookmanager->resArray['overrideReturn'];
1294
			}
1295
		}
1296
1297
		return $defaultReturn;
1298
	}
1299
1300
	function pdf_getlinetotalwithtax($parameters=array(), &$object, &$action='') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1301
		global $conf;
1302
1303
		if($this->isModSubtotalLine($parameters,$object) ){
1304
1305
			$this->resprints = ' ';
1306
1307
			if((float)DOL_VERSION<=3.6) {
1308
				return '';
1309
			}
1310
			else if((float)DOL_VERSION>=3.8) {
1311
				return 1;
1312
			}
1313
		}
1314
1315
		if(is_array($parameters)) $i = & $parameters['i'];
1316
		else $i = (int)$parameters;
1317
1318
		if (!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) && (!empty($object->lines[$i]->array_options['options_subtotal_nc']) || TSubtotal::hasNcTitle($object->lines[$i])) )
1319
		{
1320
			if (!in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1321
			{
1322
				$this->resprints = ' ';
1323
				return 1;
1324
			}
1325
		}
1326
1327
		return 0;
1328
	}
1329
1330
	function pdf_getlineunit($parameters=array(), &$object, &$action='') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1331
		global $conf;
1332
1333
		if($this->isModSubtotalLine($parameters,$object) ){
1334
			$this->resprints = ' ';
1335
1336
			if((float)DOL_VERSION<=3.6) {
1337
				return '';
1338
			}
1339
			else if((float)DOL_VERSION>=3.8) {
1340
				return 1;
1341
			}
1342
		}
1343
1344
		if(is_array($parameters)) $i = & $parameters['i'];
1345
		else $i = (int)$parameters;
1346
1347
		if (!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) && (!empty($object->lines[$i]->array_options['options_subtotal_nc']) || TSubtotal::hasNcTitle($object->lines[$i])) )
1348
		{
1349
			if (!in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1350
			{
1351
				$this->resprints = ' ';
1352
				return 1;
1353
			}
1354
		}
1355
1356
		return 0;
1357
	}
1358
1359
	function pdf_getlineupexcltax($parameters=array(), &$object, &$action='') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1360
	    global $conf,$hideprices,$hookmanager;
1361
1362
		if(is_array($parameters)) $i = & $parameters['i'];
1363
		else $i = (int)$parameters;
1364
1365
		if($this->isModSubtotalLine($parameters,$object) ) {
1366
			$this->resprints = ' ';
1367
1368
            $line = $object->lines[$i];
1369
1370
            // On récupère les montants du bloc pour les afficher dans la ligne de sous-total
1371
            if(TSubtotal::isSubtotal($line)) {
1372
                $parentTitle = TSubtotal::getParentTitleOfLine($object, $line->rang);
1373
1374
                if(is_object($parentTitle) && empty($parentTitle->array_options)) $parentTitle->fetch_optionals();
1375
                if(! empty($parentTitle->array_options['options_show_total_ht'])) {
1376
                    $TTotal = TSubtotal::getTotalBlockFromTitle($object, $parentTitle);
1377
                    $this->resprints = price($TTotal['total_unit_subprice']);
1378
                }
1379
            }
1380
1381
			if((float)DOL_VERSION<=3.6) {
1382
				return '';
1383
			}
1384
			else if((float)DOL_VERSION>=3.8) {
1385
				return 1;
1386
			}
1387
		}
1388
1389
		// Si la gestion C/NC est active et que je suis sur un ligne dont l'extrafield est coché
1390
		if (
1391
		!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) &&
1392
		(!empty($object->lines[$i]->array_options['options_subtotal_nc']) || TSubtotal::hasNcTitle($object->lines[$i]))
1393
		)
1394
		{
1395
		    // alors je dois vérifier si la méthode fait partie de la conf qui l'exclue
1396
		    if (!in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1397
		    {
1398
		        $this->resprints = ' ';
1399
1400
		        // currentcontext à modifier celon l'appel
1401
		        $params = array('parameters' => $parameters, 'currentmethod' => 'pdf_getlineupexcltax', 'currentcontext'=>'subtotal_hide_nc', 'i' => $i);
1402
		        return $this->callHook($object, $hookmanager, $action, $params); // return 1 (qui est la valeur par défaut) OU -1 si erreur OU overrideReturn (contient -1 ou 0 ou 1)
1403
1404
		    }
1405
		}
1406
		// Cache le prix pour les lignes standards dolibarr qui sont dans un ensemble
1407
		else if (!empty($hideprices))
1408
		{
1409
1410
		    // Check if a title exist for this line && if the title have subtotal
1411
		    $lineTitle = TSubtotal::getParentTitleOfLine($object, $object->lines[$i]->rang);
1412
		    if ($lineTitle && TSubtotal::titleHasTotalLine($object, $lineTitle, true))
1413
		    {
1414
1415
		        $this->resprints = ' ';
1416
1417
		        // currentcontext à modifier celon l'appel
1418
		        $params = array('parameters' => $parameters, 'currentmethod' => 'pdf_getlineupexcltax', 'currentcontext'=>'subtotal_hideprices', 'i' => $i);
1419
		        return $this->callHook($object, $hookmanager, $action, $params); // return 1 (qui est la valeur par défaut) OU -1 si erreur OU overrideReturn (contient -1 ou 0 ou 1)
1420
		    }
1421
		}
1422
1423
		return 0;
1424
	}
1425
1426
	function pdf_getlineremisepercent($parameters=array(), &$object, &$action='') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1427
	    global $conf,$hideprices,$hookmanager;
1428
1429
        if(is_array($parameters)) $i = & $parameters['i'];
1430
        else $i = (int) $parameters;
1431
1432
		if($this->isModSubtotalLine($parameters,$object) ) {
1433
			$this->resprints = ' ';
1434
1435
            $line = $object->lines[$i];
1436
1437
            // Affichage de la remise
1438
            if(TSubtotal::isSubtotal($line)) {
1439
                $parentTitle = TSubtotal::getParentTitleOfLine($object, $line->rang);
1440
1441
                if(empty($parentTitle->array_options)) $parentTitle->fetch_optionals();
1442
                if(! empty($parentTitle->array_options['options_show_reduc'])) {
1443
                    $TTotal = TSubtotal::getTotalBlockFromTitle($object, $parentTitle);
1444
                    $this->resprints = price((1-$TTotal['total_ht'] / $TTotal['total_subprice'])*100, 0, '', 1, 2, 2).'%';
1445
                }
1446
            }
1447
1448
			if((float)DOL_VERSION<=3.6) {
1449
				return '';
1450
			}
1451
			else if((float)DOL_VERSION>=3.8) {
1452
				return 1;
1453
			}
1454
		}
1455
		elseif (!empty($hideprices)
1456
		        || (!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) && (!empty($object->lines[$i]->array_options['options_subtotal_nc']) || TSubtotal::hasNcTitle($object->lines[$i])) )
1457
		        )
1458
		    {
1459
		        if (!empty($hideprices) || !in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1460
		        {
1461
		            $this->resprints = ' ';
1462
		            return 1;
1463
		        }
1464
		    }
1465
1466
		return 0;
1467
	}
1468
1469
	function pdf_getlineupwithtax($parameters=array(), &$object, &$action='') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1470
		global $conf,$hideprices;
1471
1472
		if($this->isModSubtotalLine($parameters,$object) ){
1473
			$this->resprints = ' ';
1474
			if((float)DOL_VERSION<=3.6) {
1475
				return '';
1476
			}
1477
			else if((float)DOL_VERSION>=3.8) {
1478
				return 1;
1479
			}
1480
		}
1481
1482
		if(is_array($parameters)) $i = & $parameters['i'];
1483
		else $i = (int)$parameters;
1484
1485
		if (!empty($hideprices)
1486
				|| (!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) && (!empty($object->lines[$i]->array_options['options_subtotal_nc']) || TSubtotal::hasNcTitle($object->lines[$i])) )
1487
		)
1488
		{
1489
			if (!empty($hideprices) || !in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1490
			{
1491
				$this->resprints = ' ';
1492
				return 1;
1493
			}
1494
		}
1495
1496
		return 0;
1497
	}
1498
1499
	function pdf_getlinevatrate($parameters=array(), &$object, &$action='') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1500
	    global $conf,$hideprices,$hookmanager;
1501
1502
		if($this->isModSubtotalLine($parameters,$object) ){
1503
			$this->resprints = ' ';
1504
1505
			if((float)DOL_VERSION<=3.6) {
1506
				return '';
1507
			}
1508
			else if((float)DOL_VERSION>=3.8) {
1509
				return 1;
1510
			}
1511
		}
1512
1513
		if(is_array($parameters)) $i = & $parameters['i'];
1514
		else $i = (int)$parameters;
1515
1516
		if (empty($object->lines[$i])) return 0; // hideInnerLines => override $object->lines et Dolibarr ne nous permet pas de mettre à jour la variable qui conditionne la boucle sur les lignes (PR faite pour 6.0)
1517
1518
		$object->lines[$i]->fetch_optionals();
1519
		// Si la gestion C/NC est active et que je suis sur un ligne dont l'extrafield est coché
1520
		if (
1521
		!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) &&
1522
		(!empty($object->lines[$i]->array_options['options_subtotal_nc']) || TSubtotal::hasNcTitle($object->lines[$i]))
1523
		)
1524
		{
1525
		    // alors je dois vérifier si la méthode fait partie de la conf qui l'exclue
1526
		    if (!in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1527
		    {
1528
		        $this->resprints = ' ';
1529
1530
		        // currentcontext à modifier celon l'appel
1531
		        $params = array('parameters' => $parameters, 'currentmethod' => 'pdf_getlinevatrate', 'currentcontext'=>'subtotal_hide_nc', 'i' => $i);
1532
		        return $this->callHook($object, $hookmanager, $action, $params); // return 1 (qui est la valeur par défaut) OU -1 si erreur OU overrideReturn (contient -1 ou 0 ou 1)
1533
		    }
1534
		}
1535
		// Cache le prix pour les lignes standards dolibarr qui sont dans un ensemble
1536
		else if (!empty($hideprices))
1537
		{
1538
1539
		    // Check if a title exist for this line && if the title have subtotal
1540
		    $lineTitle = TSubtotal::getParentTitleOfLine($object, $object->lines[$i]->rang);
1541
		    if ($lineTitle && TSubtotal::titleHasTotalLine($object, $lineTitle, true))
1542
		    {
1543
1544
		        $this->resprints = ' ';
1545
1546
		        // currentcontext à modifier celon l'appel
1547
		        $params = array('parameters' => $parameters, 'currentmethod' => 'pdf_getlinevatrate', 'currentcontext'=>'subtotal_hideprices', 'i' => $i);
1548
		        return $this->callHook($object, $hookmanager, $action, $params); // return 1 (qui est la valeur par défaut) OU -1 si erreur OU overrideReturn (contient -1 ou 0 ou 1)
1549
		    }
1550
		}
1551
1552
		return 0;
1553
	}
1554
1555
	function pdf_getlineprogress($parameters=array(), &$object, &$action) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1556
		global $conf;
1557
1558
		if($this->isModSubtotalLine($parameters,$object) ){
1559
			$this->resprints = ' ';
1560
			if((float)DOL_VERSION<=3.6) {
1561
				return '';
1562
			}
1563
			else if((float)DOL_VERSION>=3.8) {
1564
				return 1;
1565
			}
1566
		}
1567
1568
		if(is_array($parameters)) $i = & $parameters['i'];
1569
		else $i = (int)$parameters;
1570
1571
		if (!empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) && (!empty($object->lines[$i]->array_options['options_subtotal_nc']) || TSubtotal::hasNcTitle($object->lines[$i])) )
1572
		{
1573
			if (!in_array(__FUNCTION__, explode(',', $conf->global->SUBTOTAL_TFIELD_TO_KEEP_WITH_NC)))
1574
			{
1575
				$this->resprints = ' ';
1576
				return 1;
1577
			}
1578
		}
1579
1580
		return 0;
1581
	}
1582
1583
	function add_numerotation(&$object) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1584
		global $conf;
1585
1586
		if(!empty($conf->global->SUBTOTAL_USE_NUMEROTATION)) {
1587
1588
			$TLineTitle = $TTitle = $TLineSubtotal = array();
1589
			$prevlevel = 0;
1590
			dol_include_once('/subtotal/class/subtotal.class.php');
1591
1592
			foreach($object->lines as $k=>&$line)
1593
			{
1594
				if ($line->id > 0 && $this->isModSubtotalLine($k, $object) && $line->qty <= 10)
1595
				{
1596
					$TLineTitle[] = &$line;
1597
				}
1598
				else if ($line->id > 0 && TSubtotal::isSubtotal($line))
1599
				{
1600
					$TLineSubtotal[] = &$line;
1601
				}
1602
1603
			}
1604
1605
			if (!empty($TLineTitle))
1606
			{
1607
				$TTitleNumeroted = $this->formatNumerotation($TLineTitle);
1608
1609
				$TTitle = $this->getTitlesFlatArray($TTitleNumeroted);
1610
1611
				if (!empty($TLineSubtotal))
1612
				{
1613
					foreach ($TLineSubtotal as &$stLine)
1614
					{
1615
						$parentTitle = TSubtotal::getParentTitleOfLine($object, $stLine->rang);
1616
						if (!empty($parentTitle) && array_key_exists($parentTitle->id, $TTitle))
1617
						{
1618
							$stLine->label = $TTitle[$parentTitle->id]['numerotation'] . ' ' . $stLine->label;
1619
						}
1620
					}
1621
				}
1622
			}
1623
		}
1624
1625
	}
1626
1627
	private function getTitlesFlatArray($TTitleNumeroted = array(), &$resArray = array())
1628
	{
1629
		if (is_array($TTitleNumeroted) && !empty($TTitleNumeroted))
1630
		{
1631
			foreach ($TTitleNumeroted as $tn)
1632
			{
1633
				$resArray[$tn['line']->id] = $tn;
1634
				if (array_key_exists('children', $tn))
1635
				{
1636
					$this->getTitlesFlatArray($tn['children'], $resArray);
1637
				}
1638
1639
			}
1640
		}
1641
1642
		return $resArray;
1643
	}
1644
1645
	// TODO ne gère pas encore la numération des lignes "Totaux"
1646
	private function formatNumerotation(&$TLineTitle, $line_reference='', $level=1, $prefix_num=0)
1647
	{
1648
		$TTitle = array();
1649
1650
		$i=1;
1651
		$j=0;
1652
		foreach ($TLineTitle as $k => &$line)
1653
		{
1654
			if (!empty($line_reference) && $line->rang <= $line_reference->rang) continue;
1655
			if (!empty($line_reference) && $line->qty <= $line_reference->qty) break;
1656
1657
			if ($line->qty == $level)
1658
			{
1659
				$TTitle[$j]['numerotation'] = ($prefix_num == 0) ? $i : $prefix_num.'.'.$i;
1660
				//var_dump('Prefix == '.$prefix_num.' // '.$line->desc.' ==> numerotation == '.$TTitle[$j]['numerotation'].'   ###    '.$line->qty .'=='. $level);
1661
				if (empty($line->label) && (float)DOL_VERSION < 6)
1662
				{
1663
					$line->label = !empty($line->desc) ? $line->desc : $line->description;
1664
					$line->desc = $line->description = '';
1665
				}
1666
1667
				$line->label = $TTitle[$j]['numerotation'].' '.$line->label;
1668
				$TTitle[$j]['line'] = &$line;
1669
1670
				$deep_level = $line->qty;
1671
				do {
1672
					$deep_level++;
1673
					$TTitle[$j]['children'] = $this->formatNumerotation($TLineTitle, $line, $deep_level, $TTitle[$j]['numerotation']);
1674
				} while (empty($TTitle[$j]['children']) && $deep_level <= 10); // Exemple si un bloc Titre lvl 1 contient pas de sous lvl 2 mais directement un sous lvl 5
1675
				// Rappel on peux avoir jusqu'a 10 niveau de titre
1676
1677
				$i++;
1678
				$j++;
1679
			}
1680
		}
1681
1682
		return $TTitle;
1683
	}
1684
1685
	function setDocTVA(&$pdf, &$object) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1686
1687
		$hidedetails = GETPOST('hidedetails', 'int');
1688
1689
		if(empty($hidedetails)) return false;
1690
1691
		// TODO can't add VAT to document without lines... :-/
1692
1693
		return true;
1694
	}
1695
1696
	function beforePDFCreation($parameters=array(), &$object, &$action)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1697
	{
1698
		/**
1699
		 * @var $pdf    TCPDF
1700
		 */
1701
		global $pdf,$conf, $langs;
1702
1703
		$object->subtotalPdfModelInfo = new stdClass(); // see defineColumnFiel method in this class
1704
		$object->subtotalPdfModelInfo->cols = false;
1705
1706
		// var_dump($object->lines);
1707
		dol_include_once('/subtotal/class/subtotal.class.php');
1708
1709
		$i = $parameters['i'];
1710
		foreach($parameters as $key=>$value) {
1711
			${$key} = $value;
1712
		}
1713
1714
		$this->setDocTVA($pdf, $object);
1715
1716
		$this->add_numerotation($object);
1717
1718
        foreach($object->lines as $k => &$l) {
1719
            if(TSubtotal::isSubtotal($l)) {
1720
                $parentTitle = TSubtotal::getParentTitleOfLine($object, $l->rang);
1721
                if(is_object($parentTitle) && empty($parentTitle->array_options)) $parentTitle->fetch_optionals();
1722
                if(! empty($parentTitle->id) && ! empty($parentTitle->array_options['options_show_reduc'])) {
1723
                    $l->remise_percent = 100;    // Affichage de la réduction sur la ligne de sous-total
1724
                }
1725
            }
1726
1727
1728
            // Pas de hook sur les colonnes du PDF expédition, on unset les bonnes variables
1729
            if(($object->element == 'shipping' || $object->element == 'delivery') && $this->isModSubtotalLine($k, $object))
1730
			{
1731
				$l->qty = $l->qty_asked;
1732
				unset($l->qty_asked, $l->qty_shipped, $l->volume, $l->weight);
1733
			}
1734
        }
1735
1736
		$hideInnerLines = GETPOST('hideInnerLines', 'int');
1737
		$hidedetails = GETPOST('hidedetails', 'int');
1738
1739
		if ($hideInnerLines) { // si c une ligne de titre
1740
	    	$fk_parent_line=0;
1741
			$TLines =array();
1742
1743
			$original_count=count($object->lines);
1744
		    $TTvas = array(); // tableau de tva
1745
1746
			foreach($object->lines as $k=>&$line)
1747
			{
1748
1749
				if($line->product_type==9 && $line->rowid>0)
1750
				{
1751
					$fk_parent_line = $line->rowid;
1752
1753
					// Fix tk7201 - si on cache le détail, la TVA est renseigné au niveau du sous-total, l'erreur c'est s'il y a plusieurs sous-totaux pour les même lignes, ça va faire la somme
1754
					if(TSubtotal::isSubtotal($line))
1755
					{
1756
						/*$total = $this->getTotalLineFromObject($object, $line, '');
1757
1758
						$line->total_ht = $total;
1759
						$line->total = $total;
1760
						*/
1761
						//list($total, $total_tva, $total_ttc, $TTotal_tva) = $this->getTotalLineFromObject($object, $line, '', 1);
1762
1763
						$TInfo = $this->getTotalLineFromObject($object, $line, '', 1);
1764
1765
						if (TSubtotal::getNiveau($line) == 1) $line->TTotal_tva = $TInfo[3];
1766
						$line->total_ht = $TInfo[0];
1767
						$line->total_tva = $TInfo[1];
1768
						$line->total = $line->total_ht;
1769
						$line->total_ttc = $TInfo[2];
1770
1771
//                        $TTitle = TSubtotal::getParentTitleOfLine($object, $line->rang);
1772
//                        $parentTitle = array_shift($TTitle);
1773
//                        if(! empty($parentTitle->id) && ! empty($parentTitle->array_option['options_show_total_ht'])) {
1774
//                            exit('la?');
1775
//                            $line->remise_percent = 100;    // Affichage de la réduction sur la ligne de sous-total
1776
//                            $line->update();
1777
//                        }
1778
					}
1779
//                    if(TSub)
1780
1781
				}
1782
1783
				if ($hideInnerLines)
1784
				{
1785
				    if(!empty($conf->global->SUBTOTAL_REPLACE_WITH_VAT_IF_HIDE_INNERLINES))
1786
				    {
1787
				        if($line->tva_tx != '0.000' && $line->product_type!=9){
1788
1789
    				        // on remplit le tableau de tva pour substituer les lignes cachées
1790
    				        $TTvas[$line->tva_tx]['total_tva'] += $line->total_tva;
1791
    				        $TTvas[$line->tva_tx]['total_ht'] += $line->total_ht;
1792
    				        $TTvas[$line->tva_tx]['total_ttc'] += $line->total_ttc;
1793
    				    }
1794
    					if($line->product_type==9 && $line->rowid>0)
1795
    					{
1796
    					    //Cas où je doit cacher les produits et afficher uniquement les sous-totaux avec les titres
1797
    					    // génère des lignes d'affichage des montants HT soumis à tva
1798
    					    $nbtva = count($TTvas);
1799
    					    if(!empty($nbtva)){
1800
    					        foreach ($TTvas as $tx =>$val){
1801
    					            $l = clone $line;
1802
    					            $l->product_type = 1;
1803
    					            $l->special_code = '';
1804
    					            $l->qty = 1;
1805
    					            $l->desc = $langs->trans('AmountBeforeTaxesSubjectToVATX%', $langs->transnoentitiesnoconv('VAT'), price($tx));
1806
    					            $l->tva_tx = $tx;
1807
    					            $l->total_ht = $val['total_ht'];
1808
    					            $l->total_tva = $val['total_tva'];
1809
    					            $l->total = $line->total_ht;
1810
    					            $l->total_ttc = $val['total_ttc'];
1811
    					            $TLines[] = $l;
1812
    					            array_shift($TTvas);
1813
    					       }
1814
    					    }
1815
1816
    					    // ajoute la ligne de sous-total
1817
    					    $TLines[] = $line;
1818
    					}
1819
				    } else {
1820
1821
				        if($line->product_type==9 && $line->rowid>0)
1822
				        {
1823
				            // ajoute la ligne de sous-total
1824
				            $TLines[] = $line;
1825
				        }
1826
				    }
1827
1828
1829
				}
1830
				elseif ($hidedetails)
1831
				{
1832
					$TLines[] = $line; //Cas où je cache uniquement les prix des produits
1833
				}
1834
1835
				if ($line->product_type != 9) { // jusqu'au prochain titre ou total
1836
					//$line->fk_parent_line = $fk_parent_line;
1837
1838
				}
1839
1840
				/*if($hideTotal) {
1841
					$line->total = 0;
1842
					$line->subprice= 0;
1843
				}*/
1844
1845
			}
1846
1847
			// cas incongru où il y aurait des produits en dessous du dernier sous-total
1848
			$nbtva = count($TTvas);
1849
			if(!empty($nbtva) && $hideInnerLines && !empty($conf->global->SUBTOTAL_REPLACE_WITH_VAT_IF_HIDE_INNERLINES))
1850
			{
1851
			    foreach ($TTvas as $tx =>$val){
1852
			        $l = clone $line;
1853
			        $l->product_type = 1;
1854
			        $l->special_code = '';
1855
			        $l->qty = 1;
1856
			        $l->desc = $langs->trans('AmountBeforeTaxesSubjectToVATX%', $langs->transnoentitiesnoconv('VAT'), price($tx));
1857
			        $l->tva_tx = $tx;
1858
			        $l->total_ht = $val['total_ht'];
1859
			        $l->total_tva = $val['total_tva'];
1860
			        $l->total = $line->total_ht;
1861
			        $l->total_ttc = $val['total_ttc'];
1862
			        $TLines[] = $l;
1863
			        array_shift($TTvas);
1864
			    }
1865
			}
1866
1867
			global $nblignes;
1868
			$nblignes=count($TLines);
1869
1870
			$object->lines = $TLines;
1871
1872
			if($i>count($object->lines)) {
1873
				$this->resprints = '';
1874
				return 0;
1875
			}
1876
	    }
1877
1878
		return 0;
1879
	}
1880
1881
	function pdf_writelinedesc($parameters=array(), &$object, &$action)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1882
	{
1883
		/**
1884
		 * @var $pdf    TCPDF
1885
		 */
1886
		global $pdf,$conf;
1887
1888
		foreach($parameters as $key=>$value) {
1889
			${$key} = $value;
1890
		}
1891
1892
		// même si le foreach du dessu fait ce qu'il faut, l'IDE n'aime pas
1893
		$outputlangs = $parameters['outputlangs'];
1894
		$i = $parameters['i'];
1895
		$posx = $parameters['posx'];
1896
		$h = $parameters['h'];
1897
		$w = $parameters['w'];
1898
1899
		$hideInnerLines = GETPOST('hideInnerLines', 'int');
1900
		$hidedetails = GETPOST('hidedetails', 'int');
1901
1902
		if($this->isModSubtotalLine($parameters,$object) ){
1903
1904
				global $hideprices;
1905
1906
				if(!empty($hideprices)) {
1907
					foreach($object->lines as &$line) {
1908
						if($line->fk_product_type!=9) $line->fk_parent_line = -1;
1909
					}
1910
				}
1911
1912
				$line = &$object->lines[$i];
1913
1914
				if($object->element == 'delivery' && ! empty($object->commande->expeditions[$line->fk_origin_line])) unset($object->commande->expeditions[$line->fk_origin_line]);
1915
1916
				$margin = $pdf->getMargins();
1917
				if(!empty($margin) && $line->info_bits>0) { // PAGE BREAK
1918
					$pdf->addPage();
1919
					$posy = $margin['top'];
1920
				}
1921
1922
				$label = $line->label;
1923
				$description= !empty($line->desc) ? $outputlangs->convToOutputCharset($line->desc) : $outputlangs->convToOutputCharset($line->description);
1924
1925
				if(empty($label)) {
1926
					$label = $description;
1927
					$description='';
1928
				}
1929
1930
				if($line->qty>90) {
1931
					if ($conf->global->SUBTOTAL_USE_NEW_FORMAT)	$label .= ' '.$this->getTitle($object, $line);
1932
1933
					$pageBefore = $pdf->getPage();
1934
					$this->pdf_add_total($pdf,$object, $line, $label, $description,$posx, $posy, $w, $h);
1935
					$pageAfter = $pdf->getPage();
1936
1937
					if($pageAfter>$pageBefore) {
1938
						//print "ST $pageAfter>$pageBefore<br>";
1939
						$pdf->rollbackTransaction(true);
1940
						$pdf->addPage('', '', true);
1941
						$posy = $pdf->GetY();
1942
						$this->pdf_add_total($pdf, $object, $line, $label, $description, $posx, $posy, $w, $h);
1943
						$posy = $pdf->GetY();
1944
						//print 'add ST'.$pdf->getPage().'<br />';
1945
					}
1946
1947
					// On delivery PDF, we don't want quantities to appear and there are no hooks => setting text color to background color;
1948
					if($object->element == 'delivery')
1949
					{
1950
						switch($line->qty)
1951
						{
1952
							case 99:
1953
								$grey = 220;
1954
								break;
1955
1956
							case 98:
1957
								$grey = 230;
1958
								break;
1959
1960
							default:
1961
								$grey = 240;
1962
						}
1963
1964
						$pdf->SetTextColor($grey, $grey, $grey);
1965
					}
1966
1967
					$posy = $pdf->GetY();
1968
					return 1;
1969
				}
1970
				else if ($line->qty < 10) {
1971
					$pageBefore = $pdf->getPage();
1972
1973
					$this->pdf_add_title($pdf,$object, $line, $label, $description,$posx, $posy, $w, $h);
1974
					$pageAfter = $pdf->getPage();
1975
1976
					if($object->element == 'delivery')
1977
					{
1978
						$pdf->SetTextColor(255,255,255);
1979
					}
1980
1981
					$posy = $pdf->GetY();
1982
					return 1;
1983
				} elseif(!empty($margin)) {
1984
1985
					$labelproductservice = pdf_getlinedesc($object, $i, $outputlangs, $parameters['hideref'], $parameters['hidedesc'], $parameters['issupplierline']);
1986
1987
					$labelproductservice = preg_replace('/(<img[^>]*src=")([^"]*)(&amp;)([^"]*")/', '\1\2&\4', $labelproductservice, -1, $nbrep);
1988
1989
					$pdf->writeHTMLCell($parameters['w'], $parameters['h'], $parameters['posx'], $posy, $outputlangs->convToOutputCharset($labelproductservice), 0, 1, false, true, 'J', true);
1990
1991
					return 1;
1992
				}
1993
1994
			return 0;
1995
		}
1996
		elseif (empty($object->lines[$parameters['i']]))
1997
		{
1998
			$this->resprints = -1;
1999
		}
2000
2001
        return 0;
2002
	}
2003
2004
	/**
2005
	 * Permet de récupérer le titre lié au sous-total
2006
	 *
2007
	 * @return string
2008
	 */
2009
	function getTitle(&$object, &$currentLine)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
2010
	{
2011
		$res = '';
2012
2013
		foreach ($object->lines as $line)
2014
		{
2015
			if ($line->id == $currentLine->id) break;
2016
2017
			$qty_search = 100 - $currentLine->qty;
2018
2019
			if ($line->product_type == 9 && $line->special_code == $this->module_number && $line->qty == $qty_search)
2020
			{
2021
				$res = ($line->label) ? $line->label : (($line->description) ? $line->description : $line->desc);
2022
			}
2023
		}
2024
2025
		return $res;
2026
	}
2027
2028
	/**
2029
	 * @param $parameters   array
2030
	 * @param $object       CommonObject
2031
	 * @param $action       string
2032
	 * @param $hookmanager  HookManager
2033
	 * @return int
2034
	 */
2035
	function printObjectLine ($parameters, &$object, &$action, $hookmanager)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
2036
	{
2037
		global $conf,$langs,$user,$db,$bc;
2038
2039
		$num = &$parameters['num'];
2040
		$line = &$parameters['line'];
2041
		$i = &$parameters['i'];
2042
2043
		$var = &$parameters['var'];
2044
2045
		$contexts = explode(':',$parameters['context']);
2046
		if($parameters['currentcontext'] === 'paiementcard') return 0;
2047
		$originline = null;
2048
2049
		$createRight = $user->rights->{$object->element}->creer;
2050
		if($object->element == 'facturerec' )
2051
		{
2052
			$object->statut = 0; // hack for facture rec
2053
			$createRight = $user->rights->facture->creer;
2054
		}
2055
		elseif($object->element == 'order_supplier' )
2056
		{
2057
		    $createRight = $user->rights->fournisseur->commande->creer;
2058
		}
2059
		elseif($object->element == 'invoice_supplier' )
2060
		{
2061
		    $createRight = $user->rights->fournisseur->facture->creer;
2062
		}
2063
		elseif($object->element == 'commande' && in_array('ordershipmentcard', $contexts))
2064
		{
2065
			// H4cK 4n0nYm0u$-style : $line n'est pas un objet instancié mais provient d'un fetch_object d'une requête SQL
2066
			$line->id = $line->rowid;
2067
			$line->product_type = $line->type;
2068
		}
2069
		elseif($object->element == 'shipping' || $object->element == 'delivery')
2070
		{
2071
			if(empty($line->origin_line_id) && ! empty($line->fk_origin_line))
2072
			{
2073
				$line->origin_line_id = $line->fk_origin_line;
2074
			}
2075
2076
			$originline = new OrderLine($db);
2077
			$originline->fetch($line->fk_origin_line);
2078
2079
			foreach(get_object_vars($line) as $property => $value)
2080
			{
2081
				if(empty($originline->{ $property }))
2082
				{
2083
					$originline->{ $property } = $value;
2084
				}
2085
			}
2086
2087
			$line = $originline;
2088
		}
2089
 		if($object->element=='facture')$idvar = 'facid';
2090
        else $idvar='id';
2091
		if($line->special_code!=$this->module_number || $line->product_type!=9) {
2092
			if ($object->statut == 0  && $createRight && !empty($conf->global->SUBTOTAL_ALLOW_DUPLICATE_LINE) && $object->element !== 'invoice_supplier')
2093
            {
2094
                if(!(TSubtotal::isModSubtotalLine($line)) && ( $line->fk_prev_id === null ) && !($action == "editline" && GETPOST('lineid', 'int') == $line->id)) {
2095
                    echo '<a name="duplicate-'.$line->id.'" href="' . $_SERVER['PHP_SELF'] . '?' . $idvar . '=' . $object->id . '&action=duplicate&lineid=' . $line->id . '"><i class="fa fa-clone" aria-hidden="true"></i></a>';
2096
2097
                    ?>
2098
                        <script type="text/javascript">
2099
                            $(document).ready(function() {
2100
                                $("a[name='duplicate-<?php echo $line->id; ?>']").prependTo($('#row-<?php echo $line->id; ?>').find('.linecoledit'));
2101
                            });
2102
                        </script>
2103
                    <?php
2104
                }
2105
2106
            }
2107
			return 0;
2108
		}
2109
		else if (in_array('invoicecard',$contexts) || in_array('invoicesuppliercard',$contexts) || in_array('propalcard',$contexts) || in_array('supplier_proposalcard',$contexts) || in_array('ordercard',$contexts) || in_array('ordersuppliercard',$contexts) || in_array('invoicereccard',$contexts))
2110
        {
2111
2112
2113
			if((float)DOL_VERSION <= 3.4)
2114
			{
2115
				?>
2116
				<script type="text/javascript">
2117
					$(document).ready(function() {
2118
						$('#tablelines tr[rel=subtotal]').mouseleave(function() {
2119
2120
							id_line =$(this).attr('id');
2121
2122
							$(this).find('td[rel=subtotal_total]').each(function() {
2123
								$.get(document.location.href, function(data) {
2124
									var total = $(data).find('#tablelines tr#'+id_line+' td[rel=subtotal_total]').html();
2125
2126
									$('#tablelines tr#'+id_line+' td[rel=subtotal_total]').html(total);
2127
2128
								});
2129
							});
2130
						});
2131
					});
2132
2133
				</script>
2134
				<?php
2135
			}
2136
			if(empty($line->description)) $line->description = $line->desc;
2137
			$colspan = 5;
2138
			if($object->element == 'facturerec' ) $colspan = 3;
2139
			if($object->element == 'order_supplier') (float) DOL_VERSION < 7.0 ? $colspan = 3 : $colspan = 6;
2140
			if($object->element == 'invoice_supplier') (float) DOL_VERSION < 7.0 ? $colspan = 4: $colspan = 7;
2141
			if($object->element == 'supplier_proposal') (float) DOL_VERSION < 6.0 ? $colspan = 4 : $colspan = 3;
2142
			if(!empty($conf->multicurrency->enabled) && ((float) DOL_VERSION < 8.0 || $object->multicurrency_code != $conf->currency)) {
2143
				$colspan++; // Colonne PU Devise
2144
			}
2145
			if($object->element == 'commande' && $object->statut < 3 && !empty($conf->shippableorder->enabled)) $colspan++;
2146
			$margins_hidden_by_module = empty($conf->affmarges->enabled) ? false : !($_SESSION['marginsdisplayed']);
2147
			if(!empty($conf->margin->enabled) && !$margins_hidden_by_module) $colspan++;
2148
			if(!empty($conf->margin->enabled) && !empty($conf->global->DISPLAY_MARGIN_RATES) && !$margins_hidden_by_module) $colspan++;
2149
			if(!empty($conf->margin->enabled) && !empty($conf->global->DISPLAY_MARK_RATES) && !$margins_hidden_by_module) $colspan++;
2150
			if($object->element == 'facture' && !empty($conf->global->INVOICE_USE_SITUATION) && $object->type == Facture::TYPE_SITUATION) $colspan++;
2151
			if(!empty($conf->global->PRODUCT_USE_UNITS)) $colspan++;
2152
			// Compatibility module showprice
2153
			if(!empty($conf->showprice->enabled)) $colspan++;
2154
2155
			/* Titre */
2156
			//var_dump($line);
2157
2158
			// HTML 5 data for js
2159
            $data = $this->_getHtmlData($parameters, $object, $action, $hookmanager);
2160
2161
2162
			?>
2163
			<tr <?php echo $bc[$var]; $var=!$var; echo $data; ?> rel="subtotal" id="row-<?php echo $line->id ?>" style="<?php
2164
					if (!empty($conf->global->SUBTOTAL_USE_NEW_FORMAT))
2165
					{
2166
						if($line->qty==99) print 'background:#adadcf';
2167
						else if($line->qty==98) print 'background:#ddddff;';
2168
						else if($line->qty<=97 && $line->qty>=91) print 'background:#eeeeff;';
2169
						else if($line->qty==1) print 'background:#adadcf;';
2170
						else if($line->qty==2) print 'background:#ddddff;';
2171
						else if($line->qty==50) print '';
2172
						else print 'background:#eeeeff;';
2173
2174
						//A compléter si on veux plus de nuances de couleurs avec les niveau 4,5,6,7,8 et 9
2175
					}
2176
					else
2177
					{
2178
						if($line->qty==99) print 'background:#ddffdd';
2179
						else if($line->qty==98) print 'background:#ddddff;';
2180
						else if($line->qty==2) print 'background:#eeeeff; ';
2181
						else if($line->qty==50) print '';
2182
						else print 'background:#eeffee;' ;
2183
					}
2184
2185
			?>;">
2186
2187
				<?php if(! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { ?>
2188
				<td class="linecolnum"><?php echo $i + 1; ?></td>
2189
				<?php } ?>
2190
2191
				<td colspan="<?php echo $colspan; ?>" style="<?php TSubtotal::isFreeText($line) ? '' : 'font-weight:bold;'; ?>  <?php echo ($line->qty>90)?'text-align:right':'' ?> "><?php
2192
					if($action=='editline' && GETPOST('lineid', 'int') == $line->id && TSubtotal::isModSubtotalLine($line) ) {
2193
2194
						$params=array('line'=>$line);
2195
						$reshook=$hookmanager->executeHooks('formEditProductOptions',$params,$object,$action);
2196
2197
						echo '<div id="line_'.$line->id.'"></div>'; // Imitation Dolibarr
2198
						echo '<input type="hidden" value="'.$line->id.'" name="lineid">';
2199
						echo '<input id="product_type" type="hidden" value="'.$line->product_type.'" name="type">';
2200
						echo '<input id="product_id" type="hidden" value="'.$line->fk_product.'" name="type">';
2201
						echo '<input id="special_code" type="hidden" value="'.$line->special_code.'" name="type">';
2202
2203
						$isFreeText=false;
2204
						if (TSubtotal::isTitle($line))
2205
						{
2206
							$qty_displayed = $line->qty;
2207
							print img_picto('', 'subsubtotal@subtotal').'<span style="font-size:9px;margin-left:-3px;color:#0075DE;">'.$qty_displayed.'</span>&nbsp;&nbsp;';
2208
2209
						}
2210
						else if (TSubtotal::isSubtotal($line))
2211
						{
2212
							$qty_displayed = 100 - $line->qty;
2213
							print img_picto('', 'subsubtotal2@subtotal').'<span style="font-size:9px;margin-left:-1px;color:#0075DE;">'.$qty_displayed.'</span>&nbsp;&nbsp;';
2214
						}
2215
						else
2216
						{
2217
							$isFreeText = true;
2218
						}
2219
2220
						if ($object->element == 'order_supplier' || $object->element == 'invoice_supplier') {
2221
						    $line->label = !empty($line->description) ? $line->description : $line->desc;
2222
						    $line->description = '';
2223
						}
2224
						$newlabel = $line->label;
2225
						if($line->label=='' && !$isFreeText) {
2226
							if(TSubtotal::isSubtotal($line)) {
2227
								$newlabel = $line->description.' '.$this->getTitle($object, $line);
2228
								$line->description='';
2229
							} elseif( (float)DOL_VERSION < 6 ) {
2230
								$newlabel= $line->description;
2231
								$line->description='';
2232
							}
2233
						}
2234
2235
						$readonlyForSituation = '';
2236
						if (!empty($line->fk_prev_id) && $line->fk_prev_id != null) $readonlyForSituation = 'readonly';
2237
2238
						if (!$isFreeText) echo '<input type="text" name="line-title" id-line="'.$line->id.'" value="'.$newlabel.'" size="80" '.$readonlyForSituation.'/>&nbsp;';
2239
2240
						if (!empty($conf->global->SUBTOTAL_USE_NEW_FORMAT) && (TSubtotal::isTitle($line) || TSubtotal::isSubtotal($line)) )
2241
						{
2242
							$select = '<select name="subtotal_level">';
2243
							for ($j=1; $j<10; $j++)
2244
							{
2245
								if (!empty($readonlyForSituation)) {
2246
									if ($qty_displayed == $j) $select .= '<option selected="selected" value="'.$j.'">'.$langs->trans('Level').' '.$j.'</option>';
2247
								} else $select .= '<option '.($qty_displayed == $j ? 'selected="selected"' : '').' value="'.$j.'">'.$langs->trans('Level').' '.$j.'</option>';
2248
							}
2249
							$select .= '</select>&nbsp;';
2250
2251
							echo $select;
2252
						}
2253
2254
2255
						echo '<div class="subtotal_underline" style="margin-left:24px; line-height: 25px;">';
2256
                        echo '<div>';
2257
                        echo '<input style="vertical-align:sub;"  type="checkbox" name="line-pagebreak" id="subtotal-pagebreak" value="8" '.(($line->info_bits > 0) ? 'checked="checked"' : '') .' />&nbsp;';
2258
                        echo '<label for="subtotal-pagebreak">'.$langs->trans('AddBreakPageBefore').'</label>';
2259
                        echo '</div>';
2260
2261
                        if (TSubtotal::isTitle($line))
2262
                        {
2263
                            $form = new Form($db);
2264
                            echo '<div>';
2265
                            echo '<label for="subtotal_tva_tx">'.$form->textwithpicto($langs->trans('subtotal_apply_default_tva'), $langs->trans('subtotal_apply_default_tva_help')).'</label>';
2266
                            echo '<select id="subtotal_tva_tx" name="subtotal_tva_tx" class="flat"><option selected="selected" value="">-</option>';
2267
                            if (empty($readonlyForSituation)) echo str_replace('selected', '', $form->load_tva('subtotal_tva_tx', '', $parameters['seller'], $parameters['buyer'], 0, 0, '', true));
2268
                            echo '</select>';
2269
                            echo '</div>';
2270
2271
                            if (!empty($conf->global->INVOICE_USE_SITUATION) && $object->element == 'facture' && $object->type == Facture::TYPE_SITUATION)
2272
                            {
2273
                                echo '<div>';
2274
                                echo '<label for="subtotal_progress">'.$langs->trans('subtotal_apply_progress').'</label> <input id="subtotal_progress" name="subtotal_progress" value="" size="1" />%';
2275
                                echo '</div>';
2276
                            }
2277
                            echo '<div>';
2278
                            echo '<input style="vertical-align:sub;"  type="checkbox" name="line-showTotalHT" id="subtotal-showTotalHT" value="9" '.(($line->array_options['options_show_total_ht'] > 0) ? 'checked="checked"' : '') .' />&nbsp;';
2279
                            echo '<label for="subtotal-showTotalHT">'.$langs->trans('ShowTotalHTOnSubtotalBlock').'</label>';
2280
                            echo '</div>';
2281
2282
                            echo '<div>';
2283
                            echo '<input style="vertical-align:sub;"  type="checkbox" name="line-showReduc" id="subtotal-showReduc" value="1" '.(($line->array_options['options_show_reduc'] > 0) ? 'checked="checked"' : '') .' />&nbsp;';
2284
                            echo '<label for="subtotal-showReduc">'.$langs->trans('ShowReducOnSubtotalBlock').'</label>';
2285
                            echo '</div>';
2286
                        }
2287
                        else if ($isFreeText) echo TSubtotal::getFreeTextHtml($line, (bool) $readonlyForSituation);
2288
						echo '</div>';
2289
2290
						if (TSubtotal::isTitle($line))
2291
						{
2292
							// WYSIWYG editor
2293
							require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
2294
							$nbrows = ROWS_2;
2295
							$cked_enabled = (!empty($conf->global->FCKEDITOR_ENABLE_DETAILS) ? $conf->global->FCKEDITOR_ENABLE_DETAILS : 0);
2296
							if (!empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) {
2297
								$nbrows = $conf->global->MAIN_INPUT_DESC_HEIGHT;
2298
							}
2299
							$toolbarname = 'dolibarr_details';
2300
							if (!empty($conf->global->FCKEDITOR_ENABLE_DETAILS_FULL)) {
2301
								$toolbarname = 'dolibarr_notes';
2302
							}
2303
							$doleditor = new DolEditor('line-description', $line->description, '', 100, $toolbarname, '',
2304
								false, true, $cked_enabled, $nbrows, '98%', (bool) $readonlyForSituation);
2305
							$doleditor->Create();
2306
2307
							$TKey = null;
2308
							if ($line->element == 'propaldet') $TKey = explode(',', $conf->global->SUBTOTAL_LIST_OF_EXTRAFIELDS_PROPALDET);
2309
							elseif ($line->element == 'commandedet') $TKey = explode(',', $conf->global->SUBTOTAL_LIST_OF_EXTRAFIELDS_COMMANDEDET);
2310
							elseif ($line->element == 'facturedet') $TKey = explode(',', $conf->global->SUBTOTAL_LIST_OF_EXTRAFIELDS_FACTUREDET);
2311
							// TODO ajouter la partie fournisseur
2312
2313
							if (!empty($TKey))
2314
							{
2315
								$extrafields = new ExtraFields($this->db);
2316
								$extrafields->fetch_name_optionals_label($object->table_element_line);
2317
								foreach ($extrafields->attributes[$line->element]['param'] as $code => $val)
2318
								{
2319
									if (in_array($code, $TKey) && $extrafields->attributes[$line->element]['list'][$code] > 0)
2320
									{
2321
										echo '<div class="sub-'.$code.'">';
2322
										echo '<label class="">'.$extrafields->attributes[$line->element]['label'][$code].'</label>';
2323
										echo $extrafields->showInputField($code, $line->array_options['options_'.$code], '', '', 'subtotal_');
2324
										echo '</div>';
2325
									}
2326
								}
2327
							}
2328
						}
2329
2330
					}
2331
					else {
2332
2333
						 if ($conf->global->SUBTOTAL_USE_NEW_FORMAT)
2334
						 {
2335
							if(TSubtotal::isTitle($line) || TSubtotal::isSubtotal($line))
2336
							{
2337
								echo str_repeat('&nbsp;&nbsp;&nbsp;', $line->qty-1);
2338
2339
								if (TSubtotal::isTitle($line)) print img_picto('', 'subtotal@subtotal').'<span style="font-size:9px;margin-left:-3px;">'.$line->qty.'</span>&nbsp;&nbsp;';
2340
								else print img_picto('', 'subtotal2@subtotal').'<span style="font-size:9px;margin-left:-1px;">'.(100-$line->qty).'</span>&nbsp;&nbsp;';
2341
							}
2342
						 }
2343
						 else
2344
						 {
2345
							if($line->qty<=1) print img_picto('', 'subtotal@subtotal');
2346
							else if($line->qty==2) print img_picto('', 'subsubtotal@subtotal').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
2347
						 }
2348
2349
2350
						 // Get display styles and apply them
2351
						 $titleStyleItalic = strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'I') === false ? '' : ' font-style: italic;';
2352
						 $titleStyleBold =  strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'B') === false ? '' : ' font-weight:bold;';
2353
						 $titleStyleUnderline =  strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'U') === false ? '' : ' text-decoration: underline;';
2354
2355
						 if (empty($line->label)) {
2356
							if ($line->qty >= 91 && $line->qty <= 99 && $conf->global->SUBTOTAL_USE_NEW_FORMAT) print  $line->description.' '.$this->getTitle($object, $line);
2357
							else print  $line->description;
2358
						 }
2359
						 else {
2360
2361
							if (! empty($conf->global->PRODUIT_DESC_IN_FORM) && !empty($line->description)) {
2362
								print '<span class="subtotal_label" style="'.$titleStyleItalic.$titleStyleBold.$titleStyleUnderline.'" >'.$line->label.'</span><br><div class="subtotal_desc">'.dol_htmlentitiesbr($line->description).'</div>';
2363
							}
2364
							else{
2365
								print '<span class="subtotal_label classfortooltip '.$titleStyleItalic.$titleStyleBold.$titleStyleUnderline.'" title="'.$line->description.'">'.$line->label.'</span>';
2366
							}
2367
2368
						 }
2369
						if($line->qty>90) print ' : ';
2370
						if($line->info_bits > 0) echo img_picto($langs->trans('Pagebreak'), 'pagebreak@subtotal');
2371
2372
2373
2374
2375
					}
2376
			?></td>
2377
2378
			<?php
2379
				if($line->qty>90) {
2380
					/* Total */
2381
					$total_line = $this->getTotalLineFromObject($object, $line, '');
2382
					echo '<td class="linecolht nowrap" align="right" style="font-weight:bold;" rel="subtotal_total">'.price($total_line).'</td>';
2383
					if (!empty($conf->multicurrency->enabled) && ((float) DOL_VERSION < 8.0 || $object->multicurrency_code != $conf->currency)) {
2384
						echo '<td class="linecoltotalht_currency">&nbsp;</td>';
2385
					}
2386
				} else {
2387
					echo '<td class="linecolht movetitleblock">&nbsp;</td>';
2388
					if (!empty($conf->multicurrency->enabled) && ((float) DOL_VERSION < 8.0 || $object->multicurrency_code != $conf->currency)) {
2389
						echo '<td class="linecoltotalht_currency">&nbsp;</td>';
2390
					}
2391
				}
2392
			?>
2393
2394
			<td align="center" class="nowrap linecoledit">
2395
				<?php
2396
				if ($action != 'selectlines') {
2397
2398
					if($action=='editline' && GETPOST('lineid', 'int') == $line->id && TSubtotal::isModSubtotalLine($line) ) {
2399
						?>
2400
						<input id="savelinebutton" class="button" type="submit" name="save" value="<?php echo $langs->trans('Save') ?>" />
2401
						<br />
2402
						<input class="button" type="button" name="cancelEditlinetitle" value="<?php echo $langs->trans('Cancel') ?>" />
2403
						<script type="text/javascript">
2404
							$(document).ready(function() {
2405
								$('input[name=cancelEditlinetitle]').click(function () {
2406
									document.location.href="<?php echo '?'.$idvar.'='.$object->id ?>";
2407
								});
2408
							});
2409
2410
						</script>
2411
						<?php
2412
2413
					}
2414
					else{
2415
						if ($object->statut == 0  && $createRight && !empty($conf->global->SUBTOTAL_ALLOW_DUPLICATE_BLOCK) && $object->element !== 'invoice_supplier')
2416
						{
2417
							if(TSubtotal::isTitle($line) && ( $line->fk_prev_id === null )) echo '<a href="'.$_SERVER['PHP_SELF'].'?'.$idvar.'='.$object->id.'&action=duplicate&lineid='.$line->id.'">'. img_picto($langs->trans('Duplicate'), 'duplicate@subtotal').'</a>';
2418
						}
2419
2420
						if ($object->statut == 0  && $createRight && !empty($conf->global->SUBTOTAL_ALLOW_EDIT_BLOCK))
2421
						{
2422
							echo '<a href="'.$_SERVER['PHP_SELF'].'?'.$idvar.'='.$object->id.'&action=editline&lineid='.$line->id.'#row-'.$line->id.'">'.img_edit().'</a>';
2423
						}
2424
					}
2425
2426
				}
2427
2428
				?>
2429
			</td>
2430
2431
			<td align="center" class="nowrap linecoldelete">
2432
				<?php
2433
2434
				if ($action != 'editline' && $action != 'selectlines') {
2435
						if ($object->statut == 0  && $createRight && !empty($conf->global->SUBTOTAL_ALLOW_REMOVE_BLOCK))
2436
						{
2437
2438
							if ($line->fk_prev_id === null)
2439
							{
2440
								echo '<a href="'.$_SERVER['PHP_SELF'].'?'.$idvar.'='.$object->id.'&action=ask_deleteline&lineid='.$line->id.'">'.img_delete().'</a>';
2441
							}
2442
2443
							if(TSubtotal::isTitle($line) && ($line->fk_prev_id === null) )
2444
							{
2445
								if ((float) DOL_VERSION >= 8.0) {
2446
									$img_delete = img_delete($langs->trans('deleteWithAllLines'), ' style="color:#be3535 !important;" class="pictodelete pictodeleteallline"');
2447
								} elseif ((float) DOL_VERSION >= 3.8) {
2448
									$img_delete = img_picto($langs->trans('deleteWithAllLines'), 'delete_all.3.8@subtotal',' class="pictodelete" ');
2449
								} else {
2450
									$img_delete = img_picto($langs->trans('deleteWithAllLines'), 'delete_all@subtotal');
2451
								}
2452
2453
								echo '<a href="'.$_SERVER['PHP_SELF'].'?'.$idvar.'='.$object->id.'&action=ask_deleteallline&lineid='.$line->id.'">'.$img_delete.'</a>';
2454
							}
2455
						}
2456
					}
2457
				?>
2458
			</td>
2459
2460
			<?php
2461
			if ($object->statut == 0  && $createRight && !empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) && TSubtotal::isTitle($line) && $action != 'editline')
2462
			{
2463
				echo '<td class="subtotal_nc">';
2464
				echo '<input id="subtotal_nc-'.$line->id.'" class="subtotal_nc_chkbx" data-lineid="'.$line->id.'" type="checkbox" name="subtotal_nc" value="1" '.(!empty($line->array_options['options_subtotal_nc']) ? 'checked="checked"' : '').' />';
2465
				echo '</td>';
2466
			}
2467
2468
			if ($num > 1 && empty($conf->browser->phone)) { ?>
2469
			<td align="center" class="linecolmove tdlineupdown">
2470
			</td>
2471
			<?php } else { ?>
2472
			<td align="center"<?php echo ((empty($conf->browser->phone) && ($object->statut == 0  && $createRight ))?' class="tdlineupdown"':''); ?>></td>
2473
			<?php } ?>
2474
2475
2476
			<?php  if($action == 'selectlines'){ // dolibarr 8 ?>
2477
			<td class="linecolcheck" align="center"><input type="checkbox" class="linecheckbox" name="line_checkbox[<?php echo $i+1; ?>]" value="<?php echo $line->id; ?>" ></td>
2478
			<?php } ?>
2479
2480
			</tr>
2481
			<?php
2482
2483
2484
			// Affichage des extrafields à la Dolibarr (car sinon non affiché sur les titres)
2485
			if(TSubtotal::isTitle($line) && !empty($conf->global->SUBTOTAL_ALLOW_EXTRAFIELDS_ON_TITLE)) {
2486
2487
				require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
2488
2489
				// Extrafields
2490
				$extrafieldsline = new ExtraFields($db);
2491
				$extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
2492
2493
				$colspan+=3; $mode = 'view';
2494
				if($action === 'editline' && $line->rowid == GETPOST('lineid', 'int')) $mode = 'edit';
2495
2496
				$ex_element = $line->element;
2497
				$line->element = 'tr_extrafield_title '.$line->element; // Pour pouvoir manipuler ces tr
2498
				print $line->showOptionals($extrafieldsline, $mode, array('style'=>' style="background:#eeffee;" ','colspan'=>$colspan));
2499
				$isExtraSelected = false;
2500
				foreach($line->array_options as $option) {
2501
					if(!empty($option) && $option != "-1") {
2502
						$isExtraSelected = true;
2503
						break;
2504
					}
2505
				}
2506
2507
				if($mode === 'edit') {
2508
					?>
2509
					<script>
2510
						$(document).ready(function(){
2511
2512
							var all_tr_extrafields = $("tr.tr_extrafield_title");
2513
							<?php
2514
							// Si un extrafield est rempli alors on affiche directement les extrafields
2515
							if(!$isExtraSelected) {
2516
								echo 'all_tr_extrafields.hide();';
2517
								echo 'var trad = "'.$langs->trans('showExtrafields').'";';
2518
								echo 'var extra = 0;';
2519
							} else {
2520
								echo 'all_tr_extrafields.show();';
2521
								echo 'var trad = "'.$langs->trans('hideExtrafields').'";';
2522
								echo 'var extra = 1;';
2523
							}
2524
							?>
2525
2526
							$("div .subtotal_underline").append(
2527
									'<a id="printBlocExtrafields" onclick="return false;" href="#">' + trad + '</a>'
2528
									+ '<input type="hidden" name="showBlockExtrafields" id="showBlockExtrafields" value="'+ extra +'" />');
2529
2530
							$(document).on('click', "#printBlocExtrafields", function() {
2531
								var btnShowBlock = $("#showBlockExtrafields");
2532
								var val = btnShowBlock.val();
2533
								if(val == '0') {
2534
									btnShowBlock.val('1');
2535
									$("#printBlocExtrafields").html("<?php print $langs->trans('hideExtrafields'); ?>");
2536
									$(all_tr_extrafields).show();
2537
								} else {
2538
									btnShowBlock.val('0');
2539
									$("#printBlocExtrafields").html("<?php print $langs->trans('showExtrafields'); ?>");
2540
									$(all_tr_extrafields).hide();
2541
								}
2542
							});
2543
						});
2544
					</script>
2545
					<?php
2546
				}
2547
				$line->element = $ex_element;
2548
2549
			}
2550
2551
			return 1;
2552
2553
		}
2554
		elseif(($object->element == 'commande' && in_array('ordershipmentcard', $contexts)) || (in_array('expeditioncard', $contexts) && $action == 'create'))
2555
		{
2556
			$colspan = 4;
2557
2558
			// HTML 5 data for js
2559
			$data = $this->_getHtmlData($parameters, $object, $action, $hookmanager);
2560
?>
2561
			<tr <?php echo $bc[$var]; $var=!$var; echo $data; ?> rel="subtotal" id="row-<?php echo $line->id ?>" style="<?php
2562
					if (!empty($conf->global->SUBTOTAL_USE_NEW_FORMAT))
2563
					{
2564
						if($line->qty==99) print 'background:#adadcf';
2565
						else if($line->qty==98) print 'background:#ddddff;';
2566
						else if($line->qty<=97 && $line->qty>=91) print 'background:#eeeeff;';
2567
						else if($line->qty==1) print 'background:#adadcf;';
2568
						else if($line->qty==2) print 'background:#ddddff;';
2569
						else if($line->qty==50) print '';
2570
						else print 'background:#eeeeff;';
2571
2572
						//A compléter si on veux plus de nuances de couleurs avec les niveau 4,5,6,7,8 et 9
2573
					}
2574
					else
2575
					{
2576
						if($line->qty==99) print 'background:#ddffdd';
2577
						else if($line->qty==98) print 'background:#ddddff;';
2578
						else if($line->qty==2) print 'background:#eeeeff; ';
2579
						else if($line->qty==50) print '';
2580
						else print 'background:#eeffee;' ;
2581
					}
2582
2583
			?>;">
2584
2585
				<td style="<?php TSubtotal::isFreeText($line) ? '' : 'font-weight:bold;'; ?>  <?php echo ($line->qty>90)?'text-align:right':'' ?> "><?php
2586
2587
2588
						 if ($conf->global->SUBTOTAL_USE_NEW_FORMAT)
2589
						 {
2590
							if(TSubtotal::isTitle($line) || TSubtotal::isSubtotal($line))
2591
							{
2592
								echo str_repeat('&nbsp;&nbsp;&nbsp;', $line->qty-1);
2593
2594
								if (TSubtotal::isTitle($line)) print img_picto('', 'subtotal@subtotal').'<span style="font-size:9px;margin-left:-3px;">'.$line->qty.'</span>&nbsp;&nbsp;';
2595
								else print img_picto('', 'subtotal2@subtotal').'<span style="font-size:9px;margin-left:-1px;">'.(100-$line->qty).'</span>&nbsp;&nbsp;';
2596
							}
2597
						 }
2598
						 else
2599
						 {
2600
							if($line->qty<=1) print img_picto('', 'subtotal@subtotal');
2601
							else if($line->qty==2) print img_picto('', 'subsubtotal@subtotal').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
2602
						 }
2603
2604
2605
						 // Get display styles and apply them
2606
						 $titleStyleItalic = strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'I') === false ? '' : ' font-style: italic;';
2607
						 $titleStyleBold =  strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'B') === false ? '' : ' font-weight:bold;';
2608
						 $titleStyleUnderline =  strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'U') === false ? '' : ' text-decoration: underline;';
2609
2610
						 if (empty($line->label)) {
2611
							if ($line->qty >= 91 && $line->qty <= 99 && $conf->global->SUBTOTAL_USE_NEW_FORMAT) print  $line->description.' '.$this->getTitle($object, $line);
2612
							else print  $line->description;
2613
						 }
2614
						 else {
2615
2616
							if (! empty($conf->global->PRODUIT_DESC_IN_FORM) && !empty($line->description)) {
2617
								print '<span class="subtotal_label" style="'.$titleStyleItalic.$titleStyleBold.$titleStyleUnderline.'" >'.$line->label.'</span><br><div class="subtotal_desc">'.dol_htmlentitiesbr($line->description).'</div>';
2618
							}
2619
							else{
2620
								print '<span class="subtotal_label classfortooltip '.$titleStyleItalic.$titleStyleBold.$titleStyleUnderline.'" title="'.$line->description.'">'.$line->label.'</span>';
2621
							}
2622
2623
						 }
2624
						//if($line->qty>90) print ' : ';
2625
						if($line->info_bits > 0) echo img_picto($langs->trans('Pagebreak'), 'pagebreak@subtotal');
2626
2627
			?>
2628
				</td>
2629
				 <td colspan="<?php echo $colspan; ?>">
2630
<?php
2631
						if(in_array('expeditioncard', $contexts) && $action == 'create')
2632
						{
2633
							$fk_entrepot = GETPOST('entrepot_id', 'int');
2634
?>
2635
2636
						<input type="hidden" name="idl<?php echo $i; ?>" value="<?php echo $line->id; ?>" />
2637
						<input type="hidden" name="qtyasked<?php echo $i; ?>" value="<?php echo $line->qty; ?>" />
2638
						<input type="hidden" name="qdelivered<?php echo $i; ?>" value="0" />
2639
						<input type="hidden" name="qtyl<?php echo $i; ?>" value="<?php echo $line->qty; ?>" />
2640
						<input type="hidden" name="entl<?php echo $i; ?>" value="<?php echo $fk_entrepot; ?>" />
2641
<?php
2642
						}
2643
?>
2644
					 </td>
2645
			</tr>
2646
<?php
2647
			return 1;
2648
		}
2649
		elseif ($object->element == 'shipping' || $object->element == 'delivery')
2650
		{
2651
			global $form;
2652
2653
			$alreadysent = $parameters['alreadysent'];
2654
2655
			$shipment_static = new Expedition($db);
2656
			$warehousestatic = new Entrepot($db);
2657
			$extrafieldsline = new ExtraFields($db);
2658
			$extralabelslines=$extrafieldsline->fetch_name_optionals_label($object->table_element_line);
2659
2660
			$colspan = 4;
2661
			if($object->origin && $object->origin_id > 0) $colspan++;
2662
			if(! empty($conf->stock->enabled)) $colspan++;
2663
			if(! empty($conf->productbatch->enabled)) $colspan++;
2664
			if($object->statut == 0) $colspan++;
2665
			if($object->statut == 0 && empty($conf->global->SUBTOTAL_ALLOW_REMOVE_BLOCK)) $colspan++;
2666
2667
			if($object->element == 'delivery') $colspan = 2;
2668
2669
			print '<!-- origin line id = '.$line->origin_line_id.' -->'; // id of order line
2670
2671
			// HTML 5 data for js
2672
			$data = $this->_getHtmlData($parameters, $object, $action, $hookmanager);
2673
			?>
2674
			<tr <?php echo $bc[$var]; $var=!$var; echo $data; ?> rel="subtotal" id="row-<?php echo $line->id ?>" style="<?php
2675
					if (!empty($conf->global->SUBTOTAL_USE_NEW_FORMAT))
2676
					{
2677
						if($line->qty==99) print 'background:#adadcf';
2678
						else if($line->qty==98) print 'background:#ddddff;';
2679
						else if($line->qty<=97 && $line->qty>=91) print 'background:#eeeeff;';
2680
						else if($line->qty==1) print 'background:#adadcf;';
2681
						else if($line->qty==2) print 'background:#ddddff;';
2682
						else if($line->qty==50) print '';
2683
						else print 'background:#eeeeff;';
2684
2685
						//A compléter si on veux plus de nuances de couleurs avec les niveau 4,5,6,7,8 et 9
2686
					}
2687
					else
2688
					{
2689
						if($line->qty==99) print 'background:#ddffdd';
2690
						else if($line->qty==98) print 'background:#ddddff;';
2691
						else if($line->qty==2) print 'background:#eeeeff; ';
2692
						else if($line->qty==50) print '';
2693
						else print 'background:#eeffee;' ;
2694
					}
2695
2696
			?>;">
2697
2698
			<?php
2699
			// #
2700
			if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER))
2701
			{
2702
				print '<td align="center">'.($i+1).'</td>';
2703
			}
2704
			?>
2705
2706
			<td style="<?php TSubtotal::isFreeText($line) ? '' : 'font-weight:bold;'; ?>  <?php echo ($line->qty>90)?'text-align:right':'' ?> "><?php
2707
2708
2709
			if ($conf->global->SUBTOTAL_USE_NEW_FORMAT)
2710
			{
2711
				if(TSubtotal::isTitle($line) || TSubtotal::isSubtotal($line))
2712
				{
2713
					echo str_repeat('&nbsp;&nbsp;&nbsp;', $line->qty-1);
2714
2715
					if (TSubtotal::isTitle($line)) print img_picto('', 'subtotal@subtotal').'<span style="font-size:9px;margin-left:-3px;">'.$line->qty.'</span>&nbsp;&nbsp;';
2716
					else print img_picto('', 'subtotal2@subtotal').'<span style="font-size:9px;margin-left:-1px;">'.(100-$line->qty).'</span>&nbsp;&nbsp;';
2717
				}
2718
			}
2719
			else
2720
			{
2721
				if($line->qty<=1) print img_picto('', 'subtotal@subtotal');
2722
				else if($line->qty==2) print img_picto('', 'subsubtotal@subtotal').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
2723
			}
2724
2725
2726
			// Get display styles and apply them
2727
			$titleStyleItalic = strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'I') === false ? '' : ' font-style: italic;';
2728
			$titleStyleBold =  strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'B') === false ? '' : ' font-weight:bold;';
2729
			$titleStyleUnderline =  strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'U') === false ? '' : ' text-decoration: underline;';
2730
2731
			if (empty($line->label)) {
2732
				if ($line->qty >= 91 && $line->qty <= 99 && $conf->global->SUBTOTAL_USE_NEW_FORMAT) print  $line->description.' '.$this->getTitle($object, $line);
2733
				else print  $line->description;
2734
			}
2735
			else {
2736
				if (! empty($conf->global->PRODUIT_DESC_IN_FORM) && !empty($line->description)) {
2737
					print '<span class="subtotal_label" style="'.$titleStyleItalic.$titleStyleBold.$titleStyleUnderline.'" >'.$line->label.'</span><br><div class="subtotal_desc">'.dol_htmlentitiesbr($line->description).'</div>';
2738
				}
2739
				else{
2740
					print '<span class="subtotal_label classfortooltip '.$titleStyleItalic.$titleStyleBold.$titleStyleUnderline.'" title="'.$line->description.'">'.$line->label.'</span>';
2741
				}
2742
			}
2743
			//if($line->qty>90) print ' : ';
2744
			if($line->info_bits > 0) echo img_picto($langs->trans('Pagebreak'), 'pagebreak@subtotal');
2745
2746
			?>
2747
				</td>
2748
				<td colspan="<?php echo $colspan; ?>">&nbsp;</td>
2749
			<?php
2750
2751
			if ($object->element == 'shipping' && $object->statut == 0 && ! empty($conf->global->SUBTOTAL_ALLOW_REMOVE_BLOCK))
2752
			{
2753
				print '<td class="linecoldelete nowrap" width="10">';
2754
				$lineid = $line->id;
2755
				if($line->element === 'commandedet') {
2756
					foreach($object->lines as $shipmentLine) {
2757
						if(!empty($shipmentLine->fk_origin_line) && $shipmentLine->fk_origin == 'orderline' && $shipmentLine->fk_origin_line == $line->id) {
2758
							$lineid = $shipmentLine->id;
2759
						}
2760
					}
2761
				}
2762
				if ($line->fk_prev_id === null)
2763
				{
2764
					echo '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=deleteline&amp;lineid='.$lineid.'">'.img_delete().'</a>';
2765
				}
2766
2767
				if(TSubtotal::isTitle($line) && ($line->fk_prev_id === null) )
2768
				{
2769
					if ((float) DOL_VERSION >= 8.0) {
2770
						$img_delete = img_delete($langs->trans('deleteWithAllLines'), ' style="color:#be3535 !important;" class="pictodelete pictodeleteallline"');
2771
					} elseif ((float) DOL_VERSION >= 3.8) {
2772
						$img_delete = img_picto($langs->trans('deleteWithAllLines'), 'delete_all.3.8@subtotal',' class="pictodelete" ');
2773
					} else {
2774
						$img_delete = img_picto($langs->trans('deleteWithAllLines'), 'delete_all@subtotal');
2775
					}
2776
2777
					echo '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=ask_deleteallline&amp;lineid='.$lineid.'">'.$img_delete.'</a>';
2778
				}
2779
2780
				print '</td>';
2781
			}
2782
2783
			print "</tr>";
2784
2785
			// Display lines extrafields
2786
			if ($object->element == 'shipping' && ! empty($conf->global->SUBTOTAL_ALLOW_EXTRAFIELDS_ON_TITLE) && is_array($extralabelslines) && count($extralabelslines)>0) {
2787
				$line = new ExpeditionLigne($db);
2788
				$line->fetch_optionals($line->id);
2789
				print '<tr class="oddeven">';
2790
				print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bc[$var], 'colspan'=>$colspan),$i);
2791
			}
2792
2793
			return 1;
2794
		}
2795
2796
		return 0;
2797
2798
	}
2799
2800
	function printOriginObjectLine($parameters, &$object, &$action, $hookmanager)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
2801
	{
2802
		global $conf,$langs,$user,$db,$bc, $restrictlist, $selectedLines;
2803
2804
		$line = &$parameters['line'];
2805
		$i = &$parameters['i'];
2806
2807
		$var = &$parameters['var'];
2808
2809
		$contexts = explode(':',$parameters['context']);
2810
2811
		if (in_array('ordercard',$contexts) || in_array('invoicecard',$contexts))
2812
		{
2813
			/** @var Commande $object */
2814
2815
			if(class_exists('TSubtotal')){ dol_include_once('/subtotal/class/subtotal.class.php'); }
2816
2817
			if (TSubtotal::isModSubtotalLine($line))
2818
			{
2819
				$object->tpl['subtotal'] = $line->id;
2820
				if (TSubtotal::isTitle($line)) $object->tpl['sub-type'] = 'title';
2821
				else if (TSubtotal::isSubtotal($line)) $object->tpl['sub-type'] = 'total';
2822
2823
				$object->tpl['sub-tr-style'] = '';
2824
				if (!empty($conf->global->SUBTOTAL_USE_NEW_FORMAT))
2825
				{
2826
					if($line->qty==99) $object->tpl['sub-tr-style'].= 'background:#adadcf';
2827
					else if($line->qty==98) $object->tpl['sub-tr-style'].= 'background:#ddddff;';
2828
					else if($line->qty<=97 && $line->qty>=91) $object->tpl['sub-tr-style'].= 'background:#eeeeff;';
2829
					else if($line->qty==1) $object->tpl['sub-tr-style'].= 'background:#adadcf;';
2830
					else if($line->qty==2) $object->tpl['sub-tr-style'].= 'background:#ddddff;';
2831
					else if($line->qty==50) $object->tpl['sub-tr-style'].= '';
2832
					else $object->tpl['sub-tr-style'].= 'background:#eeeeff;';
2833
2834
					//A compléter si on veux plus de nuances de couleurs avec les niveau 4,5,6,7,8 et 9
2835
				}
2836
				else
2837
				{
2838
					if($line->qty==99) $object->tpl['sub-tr-style'].= 'background:#ddffdd';
2839
					else if($line->qty==98) $object->tpl['sub-tr-style'].= 'background:#ddddff;';
2840
					else if($line->qty==2) $object->tpl['sub-tr-style'].= 'background:#eeeeff; ';
2841
					else if($line->qty==50) $object->tpl['sub-tr-style'].= '';
2842
					else $object->tpl['sub-tr-style'].= 'background:#eeffee;' ;
2843
				}
2844
2845
				$object->tpl['sub-td-style'] = '';
2846
				if ($line->qty>90) $object->tpl['sub-td-style'] = 'style="text-align:right"';
2847
2848
2849
				if ($conf->global->SUBTOTAL_USE_NEW_FORMAT)
2850
				{
2851
					if(TSubtotal::isTitle($line) || TSubtotal::isSubtotal($line))
2852
					{
2853
						$object->tpl["sublabel"] = str_repeat('&nbsp;&nbsp;&nbsp;', $line->qty-1);
2854
2855
						if (TSubtotal::isTitle($line)) $object->tpl["sublabel"].= img_picto('', 'subtotal@subtotal').'<span style="font-size:9px;margin-left:-3px;">'.$line->qty.'</span>&nbsp;&nbsp;';
2856
						else $object->tpl["sublabel"].= img_picto('', 'subtotal2@subtotal').'<span style="font-size:9px;margin-left:-1px;">'.(100-$line->qty).'</span>&nbsp;&nbsp;';
2857
					}
2858
				}
2859
				else
2860
				{
2861
					$object->tpl["sublabel"] = '';
2862
					if($line->qty<=1) $object->tpl["sublabel"] = img_picto('', 'subtotal@subtotal');
2863
					else if($line->qty==2) $object->tpl["sublabel"] = img_picto('', 'subsubtotal@subtotal').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
2864
				}
2865
2866
				// Get display styles and apply them
2867
				$titleStyleItalic = strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'I') === false ? '' : ' font-style: italic;';
2868
				$titleStyleBold =  strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'B') === false ? '' : ' font-weight:bold;';
2869
				$titleStyleUnderline =  strpos($conf->global->SUBTOTAL_TITLE_STYLE, 'U') === false ? '' : ' text-decoration: underline;';
2870
2871
				if (empty($line->label)) {
2872
					if ($line->qty >= 91 && $line->qty <= 99 && $conf->global->SUBTOTAL_USE_NEW_FORMAT) $object->tpl["sublabel"].=  $line->description.' '.$this->getTitle($object, $line);
2873
					else $object->tpl["sublabel"].=  $line->description;
2874
				}
2875
				else {
2876
2877
					if (! empty($conf->global->PRODUIT_DESC_IN_FORM) && !empty($line->description)) {
2878
						$object->tpl["sublabel"].= '<span class="subtotal_label" style="'.$titleStyleItalic.$titleStyleBold.$titleStyleUnderline.'" >'.$line->label.'</span><br><div class="subtotal_desc">'.dol_htmlentitiesbr($line->description).'</div>';
2879
					}
2880
					else{
2881
						$object->tpl["sublabel"].= '<span class="subtotal_label classfortooltip '.$titleStyleItalic.$titleStyleBold.$titleStyleUnderline.'" title="'.$line->description.'">'.$line->label.'</span>';
2882
					}
2883
2884
				}
2885
				if($line->qty>90)
2886
				{
2887
					$total = $this->getTotalLineFromObject($object, $line, '');
2888
					$object->tpl["sublabel"].= ' : <b>'.$total.'</b>';
2889
				}
2890
2891
2892
2893
			}
2894
2895
			$object->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
2896
2897
			unset($object->tpl["sublabel"]);
2898
			unset($object->tpl['sub-td-style']);
2899
			unset($object->tpl['sub-tr-style']);
2900
			unset($object->tpl['sub-type']);
2901
			unset($object->tpl['subtotal']);
2902
		}
2903
2904
		return 0;
2905
	}
2906
2907
2908
	function addMoreActionsButtons($parameters, &$object, &$action, $hookmanager) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
2909
		global $conf,$langs;
2910
2911
		if ($object->statut == 0 && !empty($conf->global->SUBTOTAL_MANAGE_COMPRIS_NONCOMPRIS) && $action != 'editline')
2912
		{
2913
2914
		    if($object->element == 'invoice_supplier' || $object->element == 'order_supplier')
2915
		    {
2916
		        foreach ($object->lines as $line)
2917
		        {
2918
		            // fetch optionals attributes and labels
2919
		            require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
2920
		            $extrafields=new ExtraFields($this->db);
2921
		            $extralabels=$extrafields->fetch_name_optionals_label($object->table_element_line,true);
2922
		            $line->fetch_optionals($line->id,$extralabels);
2923
		        }
2924
		    }
2925
2926
			$TSubNc = array();
2927
			foreach ($object->lines as &$l)
2928
			{
2929
				$TSubNc[$l->id] = (int) $l->array_options['options_subtotal_nc'];
2930
			}
2931
2932
			$form = new Form($db);
2933
			?>
2934
			<script type="text/javascript">
2935
				$(function() {
2936
					var subtotal_TSubNc = <?php echo json_encode($TSubNc); ?>;
2937
					$("#tablelines tr").each(function(i, item) {
2938
						if ($(item).children('.subtotal_nc').length == 0)
2939
						{
2940
							var id = $(item).attr('id');
2941
2942
							if ((typeof id != 'undefined' && id.indexOf('row-') == 0) || $(item).hasClass('liste_titre'))
2943
							{
2944
								$(item).children('td:last-child').before('<td class="subtotal_nc"></td>');
2945
2946
								if ($(item).attr('rel') != 'subtotal' && typeof $(item).attr('id') != 'undefined')
2947
								{
2948
									var idSplit = $(item).attr('id').split('-');
2949
									$(item).children('td.subtotal_nc').append($('<input type="checkbox" id="subtotal_nc-'+idSplit[1]+'" class="subtotal_nc_chkbx" data-lineid="'+idSplit[1]+'" value="1" '+(typeof subtotal_TSubNc[idSplit[1]] != 'undefined' && subtotal_TSubNc[idSplit[1]] == 1 ? 'checked="checked"' : '')+' />'));
2950
								}
2951
							}
2952
							else
2953
							{
2954
								$(item).append('<td class="subtotal_nc"></td>');
2955
							}
2956
						}
2957
					});
2958
2959
					$('#tablelines tr.liste_titre:first .subtotal_nc').html(<?php echo json_encode($form->textwithtooltip($langs->trans('subtotal_nc_title'), $langs->trans('subtotal_nc_title_help'))); ?>);
2960
2961
					function callAjaxUpdateLineNC(set, lineid, subtotal_nc)
2962
					{
2963
						$.ajax({
2964
							url: '<?php echo dol_buildpath('/subtotal/script/interface.php', 1); ?>'
2965
							,type: 'POST'
2966
							,data: {
2967
								json:1
2968
								,set: set
2969
								,element: '<?php echo $object->element; ?>'
2970
								,elementid: <?php echo (int) $object->id; ?>
2971
								,lineid: lineid
2972
								,subtotal_nc: subtotal_nc
2973
							}
2974
						}).done(function(response) {
2975
							window.location.href = window.location.pathname + '?id=<?php echo $object->id; ?>&page_y=' + window.pageYOffset;
2976
						});
2977
					}
2978
2979
					$(".subtotal_nc_chkbx").change(function(event) {
2980
						var lineid = $(this).data('lineid');
2981
						var subtotal_nc = 0 | $(this).is(':checked'); // Renvoi 0 ou 1
2982
2983
						callAjaxUpdateLineNC('updateLineNC', lineid, subtotal_nc);
2984
					});
2985
2986
				});
2987
2988
			</script>
2989
			<?php
2990
		}
2991
2992
		$this->_ajax_block_order_js($object);
2993
2994
		return 0;
2995
	}
2996
2997
	function afterPDFCreation($parameters, &$pdf, &$action, $hookmanager)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
2998
	{
2999
		global $conf;
3000
3001
		$object = $parameters['object'];
3002
3003
		if ((!empty($conf->global->SUBTOTAL_PROPAL_ADD_RECAP) && $object->element == 'propal') || (!empty($conf->global->SUBTOTAL_COMMANDE_ADD_RECAP) && $object->element == 'commande') || (!empty($conf->global->SUBTOTAL_INVOICE_ADD_RECAP) && $object->element == 'facture'))
3004
		{
3005
			if (GETPOST('subtotal_add_recap', 'none')) {
3006
				dol_include_once('/subtotal/class/subtotal.class.php');
3007
				TSubtotal::addRecapPage($parameters, $pdf);
3008
			}
3009
		}
3010
3011
		return 0;
3012
	}
3013
3014
	/** Overloading the getlinetotalremise function : replacing the parent's function with the one below
3015
	 * @param      $parameters  array           meta datas of the hook (context, etc...)
3016
	 * @param      $object      CommonObject    the object you want to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
3017
	 * @param      $action      string          current action (if set). Generally create or edit or null
3018
	 * @param      $hookmanager HookManager     current hook manager
3019
	 * @return     void
3020
	 */
3021
	function getlinetotalremise($parameters, &$object, &$action, $hookmanager)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
3022
	{
3023
	    // Les lignes NC ne sont pas censées afficher de montant total de remise, nouveau hook en v11 dans pdf_sponge
3024
	    if (! empty($object->lines[$parameters['i']]->array_options['options_subtotal_nc']))
3025
	    {
3026
            $this->resprints = '';
3027
            return 1;
3028
	    }
3029
3030
		return 0;
3031
	}
3032
3033
	// HTML 5 data for js
3034
	private function _getHtmlData($parameters, &$object, &$action, $hookmanager)
3035
	{
3036
		dol_include_once('/subtotal/class/subtotal.class.php');
3037
3038
	    $line = &$parameters['line'];
3039
3040
	    $ThtmlData['data-id']           = $line->id;
3041
	    $ThtmlData['data-product_type'] = $line->product_type;
3042
	    $ThtmlData['data-qty']          = 0; //$line->qty;
3043
	    $ThtmlData['data-level']        = TSubtotal::getNiveau($line);
3044
3045
	    if(TSubtotal::isTitle($line)){
3046
	        $ThtmlData['data-issubtotal'] = 'title';
3047
	    }elseif(TSubtotal::isSubtotal($line)){
3048
	        $ThtmlData['data-issubtotal'] = 'subtotal';
3049
	    }
3050
	    else{
3051
	        $ThtmlData['data-issubtotal'] = 'freetext';
3052
	    }
3053
3054
3055
	    // Change or add data  from hooks
3056
	    $parameters = array_replace($parameters , array(  'ThtmlData' => $ThtmlData )  );
3057
3058
	    // hook
3059
	    $reshook = $hookmanager->executeHooks('subtotalLineHtmlData',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
3060
	    if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
3061
	    if ($reshook>0)
3062
	    {
3063
	        $ThtmlData = $hookmanager->resArray;
3064
	    }
3065
3066
	    return $this->implodeHtmlData($ThtmlData);
3067
3068
	}
3069
3070
3071
	function implodeHtmlData($ThtmlData = array())
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
3072
	{
3073
	    $data = '';
3074
	    foreach($ThtmlData as $k => $h )
3075
	    {
3076
	        if(is_array($h))
3077
	        {
3078
	            $h = json_encode($h);
3079
	        }
3080
3081
	        $data .= $k . '="'.dol_htmlentities($h, ENT_QUOTES).'" ';
3082
	    }
3083
3084
	    return $data;
3085
	}
3086
3087
	function _ajax_block_order_js($object)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
3088
	{
3089
	    global $conf,$tagidfortablednd,$filepath,$langs;
3090
3091
	    /*
3092
	     * this part of js is base on dolibarr htdocs/core/tpl/ajaxrow.tpl.php
3093
	     * for compatibility reasons we don't use tableDnD but jquery sortable
3094
	     */
3095
3096
	    $id=$object->id;
3097
	    $nboflines=(isset($object->lines)?count($object->lines):0);
3098
	    $forcereloadpage=empty($conf->global->MAIN_FORCE_RELOAD_PAGE)?0:1;
3099
3100
	    $id=$object->id;
3101
	    $fk_element=$object->fk_element;
3102
	    $table_element_line=$object->table_element_line;
3103
	    $nboflines=(isset($object->lines)?count($object->lines):(empty($nboflines)?0:$nboflines));
3104
	    $tagidfortablednd=(empty($tagidfortablednd)?'tablelines':$tagidfortablednd);
3105
	    $filepath=(empty($filepath)?'':$filepath);
3106
3107
3108
	    if (GETPOST('action','aZ09') != 'editline' && $nboflines > 1)
3109
	    {
3110
3111
	        ?>
3112
3113
3114
			<script type="text/javascript">
3115
			$(document).ready(function(){
3116
3117
				// target some elements
3118
				var titleRow = $('tr[data-issubtotal="title"]');
3119
				var lastTitleCol = titleRow.find('td:last-child');
3120
				var moveBlockCol= titleRow.find('td.linecolht');
3121
3122
3123
				moveBlockCol.disableSelection(); // prevent selection
3124
<?php if ($object->statut == 0) { ?>
3125
				// apply some graphical stuff
3126
				moveBlockCol.css("background-image",'url(<?php echo dol_buildpath('subtotal/img/grip_all.png',2);  ?>)');
3127
				moveBlockCol.css("background-repeat","no-repeat");
3128
				moveBlockCol.css("background-position","center center");
3129
				moveBlockCol.css("cursor","move");
3130
				titleRow.attr('title', '<?php echo html_entity_decode($langs->trans('MoveTitleBlock')); ?>');
3131
3132
3133
 				$( "#<?php echo $tagidfortablednd; ?>" ).sortable({
3134
			    	  cursor: "move",
3135
			    	  handle: ".movetitleblock",
3136
			    	  items: 'tr:not(.nodrag,.nodrop,.noblockdrop)',
3137
			    	  delay: 150, //Needed to prevent accidental drag when trying to select
3138
			    	  opacity: 0.8,
3139
			    	  axis: "y", // limit y axis
3140
			    	  placeholder: "ui-state-highlight",
3141
			    	  start: function( event, ui ) {
3142
			    	      //console.log('X:' + e.screenX, 'Y:' + e.screenY);
3143
			    		  //console.log(ui.item);
3144
			    		  var colCount = ui.item.children().length;
3145
   						  ui.placeholder.html('<td colspan="'+colCount+'">&nbsp;</td>');
3146
3147
			    		  var TcurrentChilds = getSubtotalTitleChilds(ui.item);
3148
			    		  ui.item.data('childrens',TcurrentChilds); // store data
3149
3150
			    		  for (var key in TcurrentChilds) {
3151
			    			  $('#'+ TcurrentChilds[key]).addClass('noblockdrop');//'#row-'+
3152
			    			  $('#'+ TcurrentChilds[key]).fadeOut();//'#row-'+
3153
			    		  }
3154
3155
			    		  $(this).sortable("refresh");	// "refresh" of source sortable is required to make "disable" work!
3156
3157
			    	    },
3158
				    	stop: function (event, ui) {
3159
							// call we element is droped
3160
				    	  	$('.noblockdrop').removeClass('noblockdrop');
3161
3162
				    	  	var TcurrentChilds = ui.item.data('childrens'); // reload child list from data and not attr to prevent load error
3163
3164
							for (var i =TcurrentChilds.length ; i >= 0; i--) {
3165
				    			  $('#'+ TcurrentChilds[i]).insertAfter(ui.item); //'#row-'+
3166
				    			  $('#'+ TcurrentChilds[i]).fadeIn(); //'#row-'+
3167
							}
3168
							console.log('onstop');
3169
							console.log(cleanSerialize($(this).sortable('serialize')));
3170
3171
							$.ajax({
3172
			    	            data: {
3173
									objet_id: <?php print $object->id; ?>,
3174
							    	roworder: cleanSerialize($(this).sortable('serialize')),
3175
									table_element_line: "<?php echo $table_element_line; ?>",
3176
									fk_element: "<?php echo $fk_element; ?>",
3177
									element_id: "<?php echo $id; ?>",
3178
									filepath: "<?php echo urlencode($filepath); ?>"
3179
								},
3180
			    	            type: 'POST',
3181
			    	            url: '<?php echo DOL_URL_ROOT; ?>/core/ajax/row.php',
3182
			    	            success: function(data) {
3183
			    	                console.log(data);
3184
			    	            },
3185
			    	        });
3186
3187
			    	  },
3188
			    	  update: function (event, ui) {
3189
3190
			    	        // POST to server using $.post or $.ajax
3191
				    	  	$('.noblockdrop').removeClass('noblockdrop');
3192
							//console.log('onupdate');
3193
			    	        //console.log(cleanSerialize($(this).sortable('serialize')));
3194
			    	    }
3195
			    });
3196
 				<?php } ?>
3197
3198
				function getSubtotalTitleChilds(item)
3199
				{
3200
		    		var TcurrentChilds = []; // = JSON.parse(item.attr('data-childrens'));
3201
		    		var level = item.data('level');
3202
3203
		    		var indexOfFirstSubtotal = -1;
3204
		    		var indexOfFirstTitle = -1;
3205
3206
		    		item.nextAll('[id^="row-"]').each(function(index){
3207
3208
						var dataLevel = $(this).attr('data-level');
3209
						var dataIsSubtotal = $(this).attr('data-issubtotal');
3210
3211
						if(dataIsSubtotal != 'undefined' && dataLevel != 'undefined' )
3212
						{
3213
3214
							if(dataLevel <=  level && indexOfFirstSubtotal < 0 && dataIsSubtotal == 'subtotal' )
3215
							{
3216
								indexOfFirstSubtotal = index;
3217
								if(indexOfFirstTitle < 0)
3218
								{
3219
									TcurrentChilds.push($(this).attr('id'));
3220
								}
3221
							}
3222
3223
							if(dataLevel <=  level && indexOfFirstSubtotal < 0 && indexOfFirstTitle < 0 && dataIsSubtotal == 'title' )
3224
							{
3225
								indexOfFirstTitle = index;
3226
							}
3227
						}
3228
3229
						if(indexOfFirstTitle < 0 && indexOfFirstSubtotal < 0)
3230
						{
3231
							TcurrentChilds.push($(this).attr('id'));
3232
3233
							// Add extraffield support for dolibarr > 7
3234
							var thisId = $(this).attr('data-id');
3235
							var thisElement = $(this).attr('data-element');
3236
							if(thisId != undefined && thisElement != undefined )
3237
							{
3238
								$('[data-targetid="' + thisId + '"][data-element="extrafield"][data-targetelement="'+ thisElement +'"]').each(function(index){
3239
									TcurrentChilds.push($(this).attr('id'));
3240
								});
3241
							}
3242
3243
						}
3244
3245
		    		});
3246
		    		return TcurrentChilds;
3247
				}
3248
3249
			});
3250
			</script>
3251
			<style type="text/css" >
3252
3253
            tr.ui-state-highlight td{
3254
            	border: 1px solid #dad55e;
3255
            	background: #fffa90;
3256
            	color: #777620;
3257
            }
3258
            </style>
3259
		<?php
3260
3261
		}
3262
3263
3264
3265
	}
3266
3267
/**
3268
     * @param $parameters
3269
     * @param $object
3270
     * @param $action
3271
     * @param $hookmanager
3272
     */
3273
	function handleExpeditionTitleAndTotal($parameters, &$object, &$action, $hookmanager){
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
3274
        global $conf;
3275
        //var_dump($parameters['line']);
3276
	    dol_include_once('subtotal/class/subtotal.class.php');
3277
        $currentcontext = explode(':', $parameters['context']);
3278
3279
	    if ( in_array('shippableorderlist',$currentcontext)) {
3280
3281
            //var_dump($parameters['line']);
3282
            if(TSubtotal::isModSubtotalLine($parameters['line'])) {
3283
3284
                $confOld = $conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT;
3285
                $conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT = 0;
3286
                $res =  $parameters['shipping']->addline($parameters['TEnt_comm'][$object->order->id], $parameters['line']->id, $parameters['line']->qty);
3287
                $conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT = $confOld;
3288
            }
3289
3290
        }
3291
3292
    }
3293
3294
	/**
3295
	 * Overloading the defineColumnField function
3296
	 *
3297
	 * @param   array()         $parameters     Hook metadatas (context, etc...)
3298
	 * @param   CommonDocGenerator object      $pdfDoc         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
3299
	 * @param   string          $action         Current action (if set). Generally create or edit or null
3300
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
3301
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
3302
	 */
3303
	public function defineColumnField($parameters, &$pdfDoc, &$action, $hookmanager)
3304
	{
3305
3306
		// If this model is column field compatible it will add info to change subtotal behavior
3307
		$parameters['object']->subtotalPdfModelInfo->cols = $pdfDoc->cols;
3308
3309
		// HACK Pour passer les paramettres du model dans les hooks sans infos
3310
		$parameters['object']->subtotalPdfModelInfo->marge_droite 	= $pdfDoc->marge_droite;
3311
		$parameters['object']->subtotalPdfModelInfo->marge_gauche 	= $pdfDoc->marge_gauche;
3312
		$parameters['object']->subtotalPdfModelInfo->page_largeur 	= $pdfDoc->page_largeur;
3313
		$parameters['object']->subtotalPdfModelInfo->page_hauteur 	= $pdfDoc->page_hauteur;
3314
		$parameters['object']->subtotalPdfModelInfo->format 		= $pdfDoc->format;
3315
		$parameters['object']->subtotalPdfModelInfo->defaultTitlesFieldsStyle = $pdfDoc->subtotalPdfModelInfo->defaultTitlesFieldsStyle;
3316
		$parameters['object']->subtotalPdfModelInfo->defaultContentsFieldsStyle = $pdfDoc->subtotalPdfModelInfo->defaultContentsFieldsStyle;
3317
3318
	}
3319
}
3320