Passed
Push — master ( 0f9140...c4489d )
by Alxarafe
22:27
created

dolibarr/htdocs/compta/facture/fiche-rec.php (2 issues)

1
<?php
2
/* Copyright (C) 2002-2003  Rodolphe Quiedeville    <[email protected]>
3
 * Copyright (C) 2004-2016  Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2005-2012  Regis Houssin           <[email protected]>
5
 * Copyright (C) 2013       Florian Henry           <[email protected]>
6
 * Copyright (C) 2013       Juanjo Menent           <[email protected]>
7
 * Copyright (C) 2015       Jean-François Ferry     <[email protected]>
8
 * Copyright (C) 2012       Cedric Salvador         <[email protected]>
9
 * Copyright (C) 2015       Alexandre Spangaro      <[email protected]>
10
 * Copyright (C) 2016       Meziane Sof             <[email protected]>
11
 * Copyright (C) 2017-2018  Frédéric France         <[email protected]>
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 3 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25
 */
26
27
/**
28
 *	\file       htdocs/compta/facture/fiche-rec.php
29
 *	\ingroup    facture
30
 *	\brief      Page to show predefined invoice
31
 */
32
33
34
// Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
35
defined('BASE_PATH') or die('Single entry point through the index.php of the main folder');
36
require DOL_BASE_PATH . '/main.inc.php';
37
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
38
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
39
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
40
if (! empty($conf->projet->enabled)) {
41
	include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
42
	//include_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
43
}
44
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
45
require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
46
require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
47
require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
48
49
// Load translation files required by the page
50
$langs->loadLangs(array('bills', 'compta', 'admin', 'other', 'products'));
51
52
$action     = GETPOST('action','alpha');
53
$massaction = GETPOST('massaction','alpha');
54
$show_files = GETPOST('show_files','int');
55
$confirm    = GETPOST('confirm','alpha');
56
$cancel     = GETPOST('cancel', 'alpha');
57
$toselect   = GETPOST('toselect', 'array');
58
$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'invoicetemplatelist';   // To manage different context of search
59
60
// Security check
61
$id=(GETPOST('facid','int')?GETPOST('facid','int'):GETPOST('id','int'));
62
$lineid=GETPOST('lineid','int');
63
$ref=GETPOST('ref','alpha');
64
if ($user->societe_id) $socid=$user->societe_id;
65
$objecttype = 'facture_rec';
66
if ($action == "create" || $action == "add") $objecttype = '';
67
$result = restrictedArea($user, 'facture', $id, $objecttype);
68
$projectid = GETPOST('projectid','int');
69
70
$year_date_when=GETPOST('year_date_when');
71
$month_date_when=GETPOST('month_date_when');
72
73
$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
74
$sortfield = GETPOST("sortfield",'alpha');
75
$sortorder = GETPOST("sortorder",'alpha');
76
$page = GETPOST("page",'int');
77
if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
78
$offset = $limit * $page;
79
if (! $sortorder) $sortorder='DESC';
80
if (! $sortfield) $sortfield='f.titre';
81
$pageprev = $page - 1;
82
$pagenext = $page + 1;
83
84
$object = new FactureRec($db);
85
if (($id > 0 || $ref) && $action != 'create' && $action != 'add')
86
{
87
	$ret = $object->fetch($id, $ref);
88
	if (!$ret)
89
	{
90
		setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors');
91
	}
92
}
93
94
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
95
$hookmanager->initHooks(array('invoicereccard','globalcard'));
96
$extrafields = new ExtraFields($db);
97
98
// fetch optionals attributes and labels
99
$extralabels = $extrafields->fetch_name_optionals_label('facture_rec');
100
$search_array_options=$extrafields->getOptionalsFromPost($object->table_element,'','search_');
101
102
$permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php
103
$permissiondellink=$user->rights->facture->creer;	// Used by the include of actions_dellink.inc.php
104
$permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php
105
106
$now = dol_now();
107
108
109
/*
110
 * Actions
111
 */
112
113
if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; }
114
if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; }
115
116
$parameters = array('socid' => $socid);
117
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
118
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
119
120
if (empty($reshook))
121
{
122
	if (GETPOST('cancel','alpha')) $action='';
123
124
	// Selection of new fields
125
	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
126
127
	// Set note
128
	include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	    // Must be include, not include_once
129
130
	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';		// Must be include, not include_once
131
132
	include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php';	// Must be include, not include_once
133
134
	// Mass actions
135
	/*$objectclass='MyObject';
136
    $objectlabel='MyObject';
137
    $permtoread = $user->rights->mymodule->read;
138
    $permtodelete = $user->rights->mymodule->delete;
139
    $uploaddir = $conf->mymodule->dir_output;
140
    include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/
141
142
	// Create predefined invoice
143
	if ($action == 'add')
144
	{
145
		if (! GETPOST('titre'))
146
		{
147
			setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Title")), null, 'errors');
148
			$action = "create";
149
			$error++;
150
		}
151
152
		$frequency=GETPOST('frequency', 'int');
153
		$reyear=GETPOST('reyear');
154
		$remonth=GETPOST('remonth');
155
		$reday=GETPOST('reday');
156
		$rehour=GETPOST('rehour');
157
		$remin=GETPOST('remin');
158
		$nb_gen_max=GETPOST('nb_gen_max', 'int');
159
		//if (empty($nb_gen_max)) $nb_gen_max =0;
160
161
		if (GETPOST('frequency'))
162
		{
163
			if (empty($reyear) || empty($remonth) || empty($reday))
164
			{
165
				setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Date")), null, 'errors');
166
				$action = "create";
167
				$error++;
168
			}
169
			if ($nb_gen_max === '')
170
			{
171
				setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("MaxPeriodNumber")), null, 'errors');
172
				$action = "create";
173
				$error++;
174
			}
175
		}
176
177
		if (! $error)
178
		{
179
			$object->titre = GETPOST('titre', 'alpha');
180
			$object->note_private = GETPOST('note_private','none');
181
            $object->note_public  = GETPOST('note_public','none');
182
            $object->modelpdf = GETPOST('modelpdf', 'alpha');
183
			$object->usenewprice = GETPOST('usenewprice');
184
185
			$object->frequency = $frequency;
186
			$object->unit_frequency = GETPOST('unit_frequency', 'alpha');
187
			$object->nb_gen_max = $nb_gen_max;
188
			$object->auto_validate = GETPOST('auto_validate', 'int');
189
            $object->generate_pdf = GETPOST('generate_pdf', 'int');
190
			$object->fk_project = $projectid;
191
192
			$date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear);
193
			$object->date_when = $date_next_execution;
194
195
			// Get first contract linked to invoice used to generate template (facid is id of source invoice)
196
			if (GETPOST('facid','int') > 0)
197
			{
198
				$srcObject = new Facture($db);
199
				$srcObject->fetch(GETPOST('facid','int'));
200
201
				$srcObject->fetchObjectLinked();
202
203
				if (! empty($srcObject->linkedObjectsIds['contrat']))
204
				{
205
					$contractidid = reset($srcObject->linkedObjectsIds['contrat']);
206
207
					$object->origin = 'contrat';
208
					$object->origin_id = $contractidid;
209
					$object->linked_objects[$object->origin] = $object->origin_id;
210
				}
211
			}
212
213
			$db->begin();
214
215
			$oldinvoice = new Facture($db);
216
			$oldinvoice->fetch(GETPOST('facid','int'));
217
218
			$result = $object->create($user, $oldinvoice->id);
219
			if ($result > 0)
220
			{
221
				$result=$oldinvoice->delete($user, 1);
222
				if ($result < 0)
223
				{
224
					$error++;
225
					setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors');
226
					$action = "create";
227
				}
228
			}
229
			else
230
			{
231
				$error++;
232
				setEventMessages($object->error, $object->errors, 'errors');
233
				$action = "create";
234
			}
235
236
			if (! $error)
237
			{
238
				$db->commit();
239
240
				header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id);
241
	   			exit;
242
			}
243
			else
244
			{
245
				$db->rollback();
246
247
				$error++;
248
				setEventMessages($object->error, $object->errors, 'errors');
249
				$action = "create";
250
			}
251
		}
252
	}
253
254
	// Delete
255
	if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer)
256
	{
257
		$object->delete($user);
258
259
		header("Location: " . DOL_URL_ROOT.'/compta/facture/invoicetemplate_list.php');
260
		exit;
261
	}
262
263
264
	// Update field
265
	// Set condition
266
	if ($action == 'setconditions' && $user->rights->facture->creer)
267
	{
268
		$result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
269
	}
270
	// Set mode
271
	elseif ($action == 'setmode' && $user->rights->facture->creer)
272
	{
273
		$result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
274
	}
275
	// Set project
276
	elseif ($action == 'classin' && $user->rights->facture->creer)
277
	{
278
		$object->setProject(GETPOST('projectid', 'int'));
279
	}
280
	// Set bank account
281
	elseif ($action == 'setref' && $user->rights->facture->creer)
282
	{
283
		//var_dump(GETPOST('ref', 'alpha'));exit;
284
		$result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY');
285
		if ($result > 0)
286
		{
287
			$object->titre = GETPOST('ref', 'alpha');
288
			$object->ref = $object->titre;
289
		}
290
		else dol_print_error($db, $object->error, $object->errors);
291
	}
292
	// Set bank account
293
	elseif ($action == 'setbankaccount' && $user->rights->facture->creer)
294
	{
295
		$result=$object->setBankAccount(GETPOST('fk_account', 'int'));
296
	}
297
	// Set frequency and unit frequency
298
	elseif ($action == 'setfrequency' && $user->rights->facture->creer)
299
	{
300
		$object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha'));
301
	}
302
	// Set next date of execution
303
	elseif ($action == 'setdate_when' && $user->rights->facture->creer)
304
	{
305
		$date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear'));
306
		if (!empty($date)) $object->setNextDate($date);
307
	}
308
	// Set max period
309
	elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer)
310
	{
311
		$object->setMaxPeriod(GETPOST('nb_gen_max', 'int'));
312
	}
313
	// Set auto validate
314
	elseif ($action == 'setauto_validate' && $user->rights->facture->creer)
315
	{
316
		$object->setAutoValidate(GETPOST('auto_validate', 'int'));
317
    }
318
    // Set generate pdf
319
	elseif ($action == 'setgenerate_pdf' && $user->rights->facture->creer)
320
	{
321
		$object->setGeneratepdf(GETPOST('generate_pdf', 'int'));
322
	}
323
    // Set model pdf
324
	elseif ($action == 'setmodelpdf' && $user->rights->facture->creer)
325
	{
326
		$object->setModelpdf(GETPOST('modelpdf', 'alpha'));
327
	}
328
329
	// Set status disabled
330
	elseif ($action == 'disable' && $user->rights->facture->creer)
331
	{
332
		$db->begin();
333
334
		$object->fetch($id);
335
336
		$res = $object->setValueFrom('suspended', 1);
337
		if ($res <= 0)
338
		{
339
			$error++;
340
		}
341
342
		if (! $error)
343
		{
344
			$db->commit();
345
		}
346
		else
347
		{
348
			$db->rollback();
349
			setEventMessages($object->error, $object->errors, 'errors');
350
		}
351
	}
352
353
	// Set status enabled
354
	elseif ($action == 'enable' && $user->rights->facture->creer)
355
	{
356
		$db->begin();
357
358
		$object->fetch($id);
359
360
		$res = $object->setValueFrom('suspended', 0);
361
		if ($res <= 0)
362
		{
363
			$error++;
364
		}
365
366
		if (! $error)
367
		{
368
			$db->commit();
369
		}
370
		else
371
		{
372
			$db->rollback();
373
			setEventMessages($object->error, $object->errors, 'errors');
374
		}
375
	}
376
377
	// Delete line
378
	if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer)
379
	{
380
		$object->fetch($id);
381
		$object->fetch_thirdparty();
382
383
		$db->begin();
384
385
		$line=new FactureLigneRec($db);
386
387
		// For triggers
388
		$line->id = $lineid;
389
390
		if ($line->delete($user) > 0)
391
		{
392
			$result=$object->update_price(1);
393
394
			if ($result > 0)
395
			{
396
				$db->commit();
397
				$object->fetch($object->id);    // Reload lines
398
			}
399
			else
400
			{
401
				$db->rollback();
402
				setEventMessages($db->lasterror(), null, 'errors');
403
			}
404
		}
405
		else
406
		{
407
			$db->rollback();
408
			setEventMessages($line->error, $line->errors, 'errors');
409
		}
410
	}
411
	else if ($action == 'update_extras')
412
	{
413
		$object->oldcopy = dol_clone($object);
414
415
		// Fill array 'array_options' with data from update form
416
		$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
417
		$ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none'));
418
		if ($ret < 0) $error++;
419
420
		if (! $error)
421
		{
422
			$result = $object->insertExtraFields('BILLREC_MODIFY');
423
			if ($result < 0)
424
			{
425
				setEventMessages($object->error, $object->errors, 'errors');
426
				$error++;
427
			}
428
		}
429
	}
430
431
	// Add a new line
432
	if ($action == 'addline' && $user->rights->facture->creer)
433
	{
434
		$langs->load('errors');
435
		$error = 0;
436
437
		// Set if we used free entry or predefined product
438
		$predef='';
439
		$product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
440
		$price_ht = GETPOST('price_ht');
441
		if (GETPOST('prod_entry_mode') == 'free')
442
		{
443
			$idprod=0;
444
			$tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
445
		}
446
		else
447
		{
448
			$idprod=GETPOST('idprod', 'int');
449
			$tva_tx = '';
450
		}
451
452
		$qty = GETPOST('qty' . $predef);
453
		$remise_percent = GETPOST('remise_percent' . $predef);
454
455
		// Extrafields
456
		$extrafieldsline = new ExtraFields($db);
457
		$extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
458
		$array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
459
		// Unset extrafield
460
		if (is_array($extralabelsline))
461
		{
462
			// Get extra fields
463
			foreach ($extralabelsline as $key => $value) {
464
				unset($_POST["options_" . $key . $predef]);
465
			}
466
		}
467
468
		if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) {
469
			setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
470
			$error ++;
471
		}
472
		if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) {
473
			setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
474
			$error ++;
475
		}
476
		if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) 	// Unit price can be 0 but not ''
477
		{
478
			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
479
			$error ++;
480
		}
481
		if ($qty == '') {
482
			setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
483
			$error ++;
484
		}
485
		if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) {
486
			setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
487
			$error ++;
488
		}
489
		if ($qty < 0) {
490
			$langs->load("errors");
491
			setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
492
			$error ++;
493
		}
494
495
		if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod)))
496
		{
497
		$ret = $object->fetch($id);
498
		if ($ret < 0) {
499
			dol_print_error($db, $object->error);
500
			exit();
501
		}
502
		$ret = $object->fetch_thirdparty();
503
504
		// Clean parameters
505
		$date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year'));
506
		$date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year'));
507
		$price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
508
509
		// Define special_code for special lines
510
		$special_code = 0;
511
		// if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices
512
513
		// Ecrase $pu par celui du produit
514
		// Ecrase $desc par celui du produit
515
		// Ecrase $tva_tx par celui du produit
516
		// Ecrase $base_price_type par celui du produit
517
		// Replaces $fk_unit with the product's
518
		if (! empty($idprod))
519
			{
520
			$prod = new Product($db);
521
			$prod->fetch($idprod);
522
523
			$label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
524
525
			// Update if prices fields are defined
526
			$tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
527
			$tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
528
			if (empty($tva_tx)) $tva_npr=0;
529
530
			$pu_ht = $prod->price;
531
			$pu_ttc = $prod->price_ttc;
532
			$price_min = $prod->price_min;
533
			$price_base_type = $prod->price_base_type;
534
535
			// We define price for product
536
			if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
537
			{
538
				$pu_ht = $prod->multiprices[$object->thirdparty->price_level];
539
				$pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
540
				$price_min = $prod->multiprices_min[$object->thirdparty->price_level];
541
				$price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
542
				if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL))  // using this option is a bug. kept for backward compatibility
543
				{
544
					if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level];
545
					if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level];
546
					if (empty($tva_tx)) $tva_npr=0;
547
				}
548
			}
549
			elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
550
			{
551
				include_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
552
553
				$prodcustprice = new Productcustomerprice($db);
554
555
				$filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id);
556
557
				$result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
558
				if ($result)
559
				{
560
					if (count($prodcustprice->lines) > 0)
561
					{
562
						$pu_ht = price($prodcustprice->lines[0]->price);
563
						$pu_ttc = price($prodcustprice->lines[0]->price_ttc);
564
						$price_base_type = $prodcustprice->lines[0]->price_base_type;
565
						$tva_tx = $prodcustprice->lines[0]->tva_tx;
566
						if ($prodcustprice->lines[0]->default_vat_code && ! preg_match('/\(.*\)/', $tva_tx)) $tva_tx.= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
567
						$tva_npr = $prodcustprice->lines[0]->recuperableonly;
568
						if (empty($tva_tx)) $tva_npr=0;
569
					}
570
				}
571
			}
572
573
			$tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
574
			$tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
575
576
			// if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ?
577
			if (! empty($price_ht))
578
			{
579
				$pu_ht = price2num($price_ht, 'MU');
580
				$pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
581
			}
582
			// On reevalue prix selon taux tva car taux tva transaction peut etre different
583
			// de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
584
			elseif ($tmpvat != $tmpprodvat)
585
			{
586
				if ($price_base_type != 'HT')
587
				{
588
					$pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
589
				}
590
				else
591
				{
592
					$pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
593
				}
594
			}
595
596
			$desc = '';
597
598
			// Define output language
599
			if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE))
600
			{
601
				$outputlangs = $langs;
602
				$newlang = '';
603
				if (empty($newlang) && GETPOST('lang_id','aZ09'))
604
					$newlang = GETPOST('lang_id','aZ09');
605
				if (empty($newlang))
606
					$newlang = $object->thirdparty->default_lang;
607
				if (! empty($newlang))
608
				{
609
					$outputlangs = new Translate("", $conf);
610
					$outputlangs->setDefaultLang($newlang);
611
				}
612
613
				$desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
614
			}
615
			else
616
			{
617
				$desc = $prod->description;
618
			}
619
620
					$desc = dol_concatdesc($desc, $product_desc);
621
622
			// Add custom code and origin country into description
623
			if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code)))
624
			{
625
				$tmptxt = '(';
626
				if (! empty($prod->customcode))
627
					$tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
628
				if (! empty($prod->customcode) && ! empty($prod->country_code))
629
					$tmptxt .= ' - ';
630
				if (! empty($prod->country_code))
631
					$tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0);
632
				$tmptxt .= ')';
633
				$desc = dol_concatdesc($desc, $tmptxt);
634
			}
635
636
			$type = $prod->type;
637
			$fk_unit = $prod->fk_unit;
638
		}
639
		else
640
		{
641
			$pu_ht = price2num($price_ht, 'MU');
642
			$pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
643
			$tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
644
			$tva_tx = str_replace('*', '', $tva_tx);
645
			if (empty($tva_tx)) $tva_npr=0;
646
			$label = (GETPOST('product_label') ? GETPOST('product_label') : '');
647
			$desc = $product_desc;
648
			$type = GETPOST('type');
649
			$fk_unit= GETPOST('units', 'alpha');
650
		}
651
652
		$date_start_fill = GETPOST('date_start_fill','int');
653
		$date_end_fill = GETPOST('date_end_fill','int');
654
655
		// Margin
656
		$fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : '');
657
		$buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : '');    // If buying_price is '0', we must keep this value
658
659
		// Local Taxes
660
		$localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
661
		$localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
662
663
		$info_bits = 0;
664
		if ($tva_npr)
665
			$info_bits |= 0x01;
666
667
		if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS) )&& (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))))
0 ignored issues
show
Consider adding parentheses for clarity. Current Interpretation: (! empty($conf->global->...< price2num($price_min), Probably Intended Meaning: ! empty($conf->global->M... price2num($price_min))
Loading history...
668
		{
669
			$mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency));
670
			setEventMessages($mesg, null, 'errors');
671
		}
672
		else
673
		{
674
			// Insert line
675
			$result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit, 0, $date_start_fill, $date_end_fill);
676
677
			if ($result > 0)
678
			{
679
				/*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
680
    			{
681
    			    // Define output language
682
    			    $outputlangs = $langs;
683
    			    $newlang = '';
684
    			    if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
685
    			    if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
686
    			    if (! empty($newlang)) {
687
    				$outputlangs = new Translate("", $conf);
688
    				$outputlangs->setDefaultLang($newlang);
689
    			    }
690
    			    $model=$object->modelpdf;
691
    			    $ret = $object->fetch($id); // Reload to get new records
692
693
    			    $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
694
    			    if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
695
    			}*/
696
				$object->fetch($object->id);    // Reload lines
697
698
				unset($_POST['prod_entry_mode']);
699
700
				unset($_POST['qty']);
701
				unset($_POST['type']);
702
				unset($_POST['remise_percent']);
703
				unset($_POST['price_ht']);
704
				unset($_POST['multicurrency_price_ht']);
705
				unset($_POST['price_ttc']);
706
				unset($_POST['tva_tx']);
707
				unset($_POST['product_ref']);
708
				unset($_POST['product_label']);
709
				unset($_POST['product_desc']);
710
				unset($_POST['fournprice']);
711
				unset($_POST['buying_price']);
712
				unset($_POST['np_marginRate']);
713
				unset($_POST['np_markRate']);
714
				unset($_POST['dp_desc']);
715
				unset($_POST['idprod']);
716
				unset($_POST['units']);
717
718
				unset($_POST['date_starthour']);
719
				unset($_POST['date_startmin']);
720
				unset($_POST['date_startsec']);
721
				unset($_POST['date_startday']);
722
				unset($_POST['date_startmonth']);
723
				unset($_POST['date_startyear']);
724
				unset($_POST['date_endhour']);
725
				unset($_POST['date_endmin']);
726
				unset($_POST['date_endsec']);
727
				unset($_POST['date_endday']);
728
				unset($_POST['date_endmonth']);
729
				unset($_POST['date_endyear']);
730
731
				unset($_POST['date_start_fill']);
732
				unset($_POST['date_end_fill']);
733
734
				unset($_POST['situations']);
735
				unset($_POST['progress']);
736
			}
737
			else
738
			{
739
				setEventMessages($object->error, $object->errors, 'errors');
740
			}
741
742
			$action = '';
743
		}
744
		}
745
	}
746
747
	elseif ($action == 'updateline' && $user->rights->facture->creer && ! GETPOST('cancel','alpha'))
748
	{
749
		if (! $object->fetch($id) > 0)	dol_print_error($db);
750
		$object->fetch_thirdparty();
751
752
		// Clean parameters
753
		$date_start = '';
754
		$date_end = '';
755
		//$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
756
		//$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
757
		$description = dol_htmlcleanlastbr(GETPOST('product_desc','none') ? GETPOST('product_desc','none') : GETPOST('desc','none'));
758
		$pu_ht = GETPOST('price_ht');
759
		$vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
760
		$qty = GETPOST('qty');
761
		$pu_ht_devise = GETPOST('multicurrency_subprice');
762
763
		// Define info_bits
764
		$info_bits = 0;
765
		if (preg_match('/\*/', $vat_rate)) $info_bits |= 0x01;
766
767
		// Define vat_rate
768
		$vat_rate = str_replace('*', '', $vat_rate);
769
		$localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
770
		$localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
771
772
		// Add buying price
773
		$fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
774
		$buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : '');       // If buying_price is '0', we muste keep this value
775
776
		// Extrafields
777
		$extrafieldsline = new ExtraFields($db);
778
		$extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
779
		$array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline);
780
781
		$objectline = new FactureLigneRec($db);
782
		if ($objectline->fetch(GETPOST('lineid')))
783
		{
784
			$objectline->array_options=$array_options;
785
			$result=$objectline->insertExtraFields();
786
			if ($result < 0)
787
			{
788
				setEventMessages($langs->trans('Error').$result, null, 'errors');
789
			}
790
		}
791
792
		// Unset extrafield
793
		if (is_array($extralabelsline))
794
		{
795
			// Get extra fields
796
			foreach ($extralabelsline as $key => $value)
797
			{
798
				 unset($_POST["options_" . $key]);
799
			}
800
		}
801
802
		// Define special_code for special lines
803
		$special_code=GETPOST('special_code');
804
		if (! GETPOST('qty')) $special_code=3;
805
806
		/*$line = new FactureLigne($db);
807
        $line->fetch(GETPOST('lineid'));
808
        $percent = $line->get_prev_progress($object->id);
809
810
        if (GETPOST('progress') < $percent)
811
        {
812
                $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
813
                setEventMessages($mesg, null, 'warnings');
814
                $error++;
815
                $result = -1;
816
        }*/
817
818
		// Check minimum price
819
		$productid = GETPOST('productid', 'int');
820
		if (! empty($productid))
821
		{
822
			$product = new Product($db);
823
			$product->fetch($productid);
824
825
			$type = $product->type;
826
827
			$price_min = $product->price_min;
828
			if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
829
				$price_min = $product->multiprices_min[$object->thirdparty->price_level];
830
831
			$label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
832
833
			// Check price is not lower than minimum (check is done only for standard or replacement invoices)
834
			if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS) )&& (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))))
0 ignored issues
show
Consider adding parentheses for clarity. Current Interpretation: (! empty($conf->global->...< price2num($price_min), Probably Intended Meaning: ! empty($conf->global->M... price2num($price_min))
Loading history...
835
			{
836
				setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors');
837
				$error ++;
838
			}
839
		} else {
840
			$type = GETPOST('type');
841
			$label = (GETPOST('product_label') ? GETPOST('product_label') : '');
842
843
				// Check parameters
844
				if (GETPOST('type') < 0) {
845
					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
846
					$error ++;
847
				}
848
			}
849
		if ($qty < 0) {
850
			$langs->load("errors");
851
			setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
852
			$error ++;
853
		}
854
855
		$date_start_fill = GETPOST('date_start_fill','int');
856
		$date_end_fill = GETPOST('date_end_fill','int');
857
858
		// Update line
859
		if (! $error)
860
		{
861
			$result = $object->updateline(
862
				GETPOST('lineid'),
863
				$description,
864
				$pu_ht,
865
				$qty,
866
				$vat_rate,
867
				$localtax1_rate,
868
				$localtax1_rate,
869
				GETPOST('productid'),
870
				GETPOST('remise_percent'),
871
				'HT',
872
				$info_bits,
873
				0,
874
				0,
875
				$type,
876
				0,
877
				$special_code,
878
				$label,
879
				GETPOST('units'),
880
				$pu_ht_devise,
881
				0,
882
				$date_start_fill,
883
				$date_end_fill
884
			);
885
886
			if ($result >= 0)
887
			{
888
					/*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
889
                        // Define output language
890
                        $outputlangs = $langs;
891
                        $newlang = '';
892
                        if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09'))
893
                            $newlang = GETPOST('lang_id','aZ09');
894
                            if ($conf->global->MAIN_MULTILANGS && empty($newlang))
895
                                $newlang = $object->thirdparty->default_lang;
896
                                if (! empty($newlang)) {
897
                                    $outputlangs = new Translate("", $conf);
898
                                    $outputlangs->setDefaultLang($newlang);
899
                                }
900
901
                                $ret = $object->fetch($id); // Reload to get new records
902
                                $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
903
                    }*/
904
905
				$object->fetch($object->id);    // Reload lines
906
907
				unset($_POST['qty']);
908
				unset($_POST['type']);
909
				unset($_POST['productid']);
910
				unset($_POST['remise_percent']);
911
				unset($_POST['price_ht']);
912
				unset($_POST['multicurrency_price_ht']);
913
				unset($_POST['price_ttc']);
914
				unset($_POST['tva_tx']);
915
				unset($_POST['product_ref']);
916
				unset($_POST['product_label']);
917
				unset($_POST['product_desc']);
918
				unset($_POST['fournprice']);
919
				unset($_POST['buying_price']);
920
				unset($_POST['np_marginRate']);
921
				unset($_POST['np_markRate']);
922
923
				unset($_POST['dp_desc']);
924
				unset($_POST['idprod']);
925
				unset($_POST['units']);
926
927
				unset($_POST['date_starthour']);
928
				unset($_POST['date_startmin']);
929
				unset($_POST['date_startsec']);
930
				unset($_POST['date_startday']);
931
				unset($_POST['date_startmonth']);
932
				unset($_POST['date_startyear']);
933
				unset($_POST['date_endhour']);
934
				unset($_POST['date_endmin']);
935
				unset($_POST['date_endsec']);
936
				unset($_POST['date_endday']);
937
				unset($_POST['date_endmonth']);
938
				unset($_POST['date_endyear']);
939
940
				unset($_POST['situations']);
941
				unset($_POST['progress']);
942
			}
943
			else
944
			{
945
				setEventMessages($object->error, $object->errors, 'errors');
946
			}
947
		}
948
	}
949
}
950
951
952
/*
953
 *	View
954
 */
955
956
llxHeader('',$langs->trans("RepeatableInvoices"),'ch-facture.html#s-fac-facture-rec');
957
958
$form = new Form($db);
959
$formother = new FormOther($db);
960
if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
961
$companystatic = new Societe($db);
962
$invoicerectmp = new FactureRec($db);
963
964
$now = dol_now();
965
$tmparray=dol_getdate($now);
966
$today = dol_mktime(23,59,59,$tmparray['mon'],$tmparray['mday'],$tmparray['year']);   // Today is last second of current day
967
968
969
/*
970
 * Create mode
971
 */
972
if ($action == 'create')
973
{
974
	print load_fiche_titre($langs->trans("CreateRepeatableInvoice"),'','title_accountancy.png');
975
976
	$object = new Facture($db);   // Source invoice
977
	$product_static = new Product($db);
978
979
	if ($object->fetch($id, $ref) > 0)
980
	{
981
		$result = $object->getLinesArray();
982
983
		print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
984
		print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
985
		print '<input type="hidden" name="action" value="add">';
986
		print '<input type="hidden" name="facid" value="'.$object->id.'">';
987
988
		dol_fiche_head(null, '', '', 0);
989
990
		$rowspan=4;
991
		if (! empty($conf->projet->enabled)) $rowspan++;
992
		if ($object->fk_account > 0) $rowspan++;
993
994
		print '<table class="border" width="100%">';
995
996
		$object->fetch_thirdparty();
997
998
		// Title
999
		print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Title").'</td><td>';
1000
		print '<input class="flat quatrevingtpercent" type="text" name="titre" value="'.$_POST["titre"].'">';
1001
		print '</td></tr>';
1002
1003
		// Third party
1004
		print '<tr><td class="titlefieldcreate">'.$langs->trans("Customer").'</td><td>'.$object->thirdparty->getNomUrl(1,'customer').'</td>';
1005
		print '</tr>';
1006
1007
		$note_public=GETPOST('note_public','none')?GETPOST('note_public','none'):$object->note_public;
1008
		$note_private=GETPOST('note_private','none')?GETPOST('note_private','none'):$object->note_private;
1009
1010
		// Help of substitution key
1011
		$substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object);
1012
1013
		$substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%m').')';
1014
		$substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%m').')';
1015
		$substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'),'%m').')';
1016
		$substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%B').')';
1017
		$substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%B').')';
1018
		$substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B').')';
1019
		$substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'y'),'%Y').')';
1020
		$substitutionarray['__INVOICE_YEAR__'] =  $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%Y').')';
1021
		$substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'y'),'%Y').')';
1022
		// Only on template invoices
1023
		$substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date($object->date_when, 'dayhour').')';
1024
		$substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date_when, $object->frequency, $object->unit_frequency),'dayhour').')';
1025
1026
		$htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
1027
		foreach($substitutionarray as $key => $val)
1028
		{
1029
			$htmltext.=$key.' = '.$langs->trans($val).'<br>';
1030
		}
1031
		$htmltext.='</i>';
1032
1033
		// Public note
1034
		print '<tr>';
1035
		print '<td class="tdtop">';
1036
		print $form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic');
1037
		print '</td>';
1038
		print '<td>';
1039
		$doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
1040
		print $doleditor->Create(1);
1041
1042
		// Private note
1043
		if (empty($user->societe_id))
1044
		{
1045
			print '<tr>';
1046
			print '<td class="tdtop">';
1047
			print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate');
1048
			print '</td>';
1049
			print '<td>';
1050
			$doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
1051
			print $doleditor->Create(1);
1052
			// print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
1053
			print '</td></tr>';
1054
		}
1055
1056
		// Author
1057
		print "<tr><td>".$langs->trans("Author")."</td><td>".$user->getFullName($langs)."</td></tr>";
1058
1059
		// Payment term
1060
		print "<tr><td>".$langs->trans("PaymentConditions")."</td><td>";
1061
		$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none');
1062
		print "</td></tr>";
1063
1064
		// Payment mode
1065
		print "<tr><td>".$langs->trans("PaymentMode")."</td><td>";
1066
		$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none', '', 1);
1067
		print "</td></tr>";
1068
1069
		// Project
1070
		if (! empty($conf->projet->enabled) && is_object($object->thirdparty) && $object->thirdparty->id > 0)
1071
		{
1072
			$projectid = GETPOST('projectid')?GETPOST('projectid'):$object->fk_project;
1073
			$langs->load('projects');
1074
			print '<tr><td>' . $langs->trans('Project') . '</td><td>';
1075
			$numprojet = $formproject->select_projects($object->thirdparty->id, $projectid, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, '');
1076
			print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid=' . $object->thirdparty->id . '&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$object->thirdparty->id.(!empty($id)?'&id='.$id:'')).'">' . $langs->trans("AddProject") . '</a>';
1077
			print '</td></tr>';
1078
		}
1079
1080
		// Bank account
1081
		if ($object->fk_account > 0)
1082
		{
1083
			print "<tr><td>".$langs->trans('BankAccount')."</td><td>";
1084
			$form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
1085
			print "</td></tr>";
1086
		}
1087
1088
        // Model pdf
1089
        print "<tr><td>".$langs->trans('Model')."</td><td>";
1090
        include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
1091
        $list = ModelePDFFactures::liste_modeles($db);
1092
        print $form->selectarray('modelpdf', $list, $conf->global->FACTURE_ADDON_PDF);
1093
        print "</td></tr>";
1094
1095
		print "</table>";
1096
1097
		dol_fiche_end();
1098
1099
1100
		// Autogeneration
1101
		$title = $langs->trans("Recurrence");
1102
		print load_fiche_titre('<span class="fa fa-calendar"></span> '.$title, '', '');
1103
1104
		dol_fiche_head(null, '', '', 0);
1105
1106
		print '<table class="border" width="100%">';
1107
1108
		// Frequency + unit
1109
		print '<tr><td class="titlefieldcreate">'.$form->textwithpicto($langs->trans("Frequency"), $langs->transnoentitiesnoconv('toolTipFrequency'))."</td><td>";
1110
		print "<input type='text' name='frequency' value='".GETPOST('frequency', 'int')."' size='4' />&nbsp;".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), (GETPOST('unit_frequency')?GETPOST('unit_frequency'):'m'));
1111
		print "</td></tr>";
1112
1113
		// Date next run
1114
		print "<tr><td>".$langs->trans('NextDateToExecution')."</td><td>";
1115
		$date_next_execution = isset($date_next_execution) ? $date_next_execution : (GETPOST('remonth') ? dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')) : -1);
1116
		print $form->selectDate($date_next_execution, '', 1, 1, '', "add", 1, 1);
1117
		print "</td></tr>";
1118
1119
		// Number max of generation
1120
		print "<tr><td>".$langs->trans("MaxPeriodNumber")."</td><td>";
1121
		print '<input type="text" name="nb_gen_max" value="'.GETPOST('nb_gen_max').'" size="5" />';
1122
		print "</td></tr>";
1123
1124
		// Auto validate the invoice
1125
		print "<tr><td>".$langs->trans("StatusOfGeneratedInvoices")."</td><td>";
1126
		$select = array('0'=>$langs->trans('BillStatusDraft'),'1'=>$langs->trans('BillStatusValidated'));
1127
		print $form->selectarray('auto_validate', $select, GETPOST('auto_validate'));
1128
		print "</td></tr>";
1129
1130
		// Auto generate document
1131
		if (! empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION))
1132
		{
1133
			print "<tr><td>".$langs->trans("StatusOfGeneratedDocuments")."</td><td>";
1134
			$select = array('0'=>$langs->trans('DoNotGenerateDoc'),'1'=>$langs->trans('AutoGenerateDoc'));
1135
			print $form->selectarray('generate_pdf', $select, GETPOST('generate_pdf'));
1136
			print "</td></tr>";
1137
		}
1138
		else
1139
		{
1140
			print '<input type="hidden" name="generate_pdf" value="1">';
1141
		}
1142
1143
		print "</table>";
1144
1145
		dol_fiche_end();
1146
1147
1148
		$title = $langs->trans("ProductsAndServices");
1149
		if (empty($conf->service->enabled))
1150
			$title = $langs->trans("Products");
1151
		else if (empty($conf->product->enabled))
1152
			$title = $langs->trans("Services");
1153
1154
		print load_fiche_titre($title, '', '');
1155
1156
		/*
1157
		 * Invoice lines
1158
		 */
1159
		print '<div class="div-table-responsive-no-min">';
1160
		print '<table id="tablelines" class="noborder noshadow" width="100%">';
1161
		// Show object lines
1162
		if (! empty($object->lines))
1163
		{
1164
			$disableedit=1;
1165
			$disablemove=1;
1166
			$disableremove=1;
1167
			$object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0);      // No date selector for template invoice
1168
		}
1169
1170
		print "</table>\n";
1171
		print '<div>';
1172
1173
		print '</td></tr>';
1174
1175
		if ($flag_price_may_change)
1176
		{
1177
			print '<tr><td colspan="3" align="left">';
1178
			print '<select name="usenewprice" class="flat">';
1179
			print '<option value="0">'.$langs->trans("AlwaysUseFixedPrice").'</option>';
1180
			print '<option value="1" disabled>'.$langs->trans("AlwaysUseNewPrice").'</option>';
1181
			print '</select>';
1182
			print '</td></tr>';
1183
		}
1184
		print "</table>\n";
1185
1186
		print '<div align="center"><input type="submit" class="button" value="'.$langs->trans("Create").'">';
1187
		print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1188
		print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
1189
		print '</div>';
1190
		print "</form>\n";
1191
	}
1192
	else
1193
	{
1194
		dol_print_error('',"Error, no invoice ".$object->id);
1195
	}
1196
}
1197
else
1198
{
1199
	/*
1200
	 * View mode
1201
	 */
1202
	if ($object->id > 0)
1203
	{
1204
		$object->fetch_thirdparty();
1205
1206
		// Confirmation de la suppression d'une ligne produit
1207
		if ($action == 'ask_deleteline') {
1208
			$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
1209
		}
1210
1211
		// Confirm delete of repeatable invoice
1212
		if ($action == 'ask_deleteinvoice') {
1213
			$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteRepeatableInvoice'), $langs->trans('ConfirmDeleteRepeatableInvoice'), 'confirm_deleteinvoice', '', 'no', 1);
1214
		}
1215
1216
		print $formconfirm;
1217
1218
		$author = new User($db);
1219
		$author->fetch($object->user_author);
1220
1221
		$head=invoice_rec_prepare_head($object);
1222
1223
		dol_fiche_head($head, 'card', $langs->trans("RepeatableInvoice"), -1, 'bill');	// Add a div
1224
1225
		// Recurring invoice content
1226
1227
		$linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/invoicetemplate_list.php?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
1228
1229
		$morehtmlref='';
1230
		if ($action != 'editref') $morehtmlref.=$form->editfieldkey($object->ref, 'ref', $object->ref, $object, $user->rights->facture->creer, '', '', 0, 2);
1231
		else $morehtmlref.= $form->editfieldval('', 'ref', $object->ref, $object, $user->rights->facture->creer, 'string');
1232
1233
		$morehtmlref.='<div class="refidno">';
1234
		// Ref customer
1235
		//$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1);
1236
		//$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1);
1237
		// Thirdparty
1238
		$morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
1239
		// Project
1240
		if (! empty($conf->projet->enabled))
1241
		{
1242
			$langs->load("projects");
1243
			$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
1244
			if ($user->rights->facture->creer)
1245
			{
1246
				if ($action != 'classify')
1247
					$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
1248
					if ($action == 'classify') {
1249
						//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
1250
						$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
1251
						$morehtmlref.='<input type="hidden" name="action" value="classin">';
1252
						$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1253
						$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
1254
						$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
1255
						$morehtmlref.='</form>';
1256
					} else {
1257
						$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
1258
					}
1259
			} else {
1260
				if (! empty($object->fk_project)) {
1261
					$proj = new Project($db);
1262
					$proj->fetch($object->fk_project);
1263
					$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
1264
					$morehtmlref.=$proj->ref;
1265
					$morehtmlref.='</a>';
1266
				} else {
1267
					$morehtmlref.='';
1268
				}
1269
			}
1270
		}
1271
		$morehtmlref.='</div>';
1272
1273
		dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright);
1274
1275
		print '<div class="fichecenter">';
1276
		print '<div class="fichehalfleft">';
1277
		print '<div class="underbanner clearboth"></div>';
1278
1279
		print '<table class="border" width="100%">';
1280
1281
		print '<tr><td class="titlefield">'.$langs->trans("Author").'</td><td>'.$author->getFullName($langs)."</td></tr>";
1282
1283
		print '<tr><td>'.$langs->trans("AmountHT").'</td>';
1284
		print '<td>'.price($object->total_ht,'',$langs,1,-1,-1,$conf->currency).'</td>';
1285
		print '</tr>';
1286
1287
		print '<tr><td>'.$langs->trans("AmountVAT").'</td><td>'.price($object->total_tva,'',$langs,1,-1,-1,$conf->currency).'</td>';
1288
		print '</tr>';
1289
1290
		// Amount Local Taxes
1291
		if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) 	// Localtax1
1292
		{
1293
			print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
1294
			print '<td class="nowrap">' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
1295
		}
1296
		if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) 	// Localtax2
1297
		{
1298
			print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
1299
			print '<td class=nowrap">' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
1300
		}
1301
1302
		print '<tr><td>'.$langs->trans("AmountTTC").'</td><td colspan="3">'.price($object->total_ttc,'',$langs,1,-1,-1,$conf->currency).'</td>';
1303
		print '</tr>';
1304
1305
1306
		// Payment term
1307
		print '<tr><td>';
1308
		print '<table class="nobordernopadding" width="100%"><tr><td>';
1309
		print $langs->trans('PaymentConditionsShort');
1310
		print '</td>';
1311
		if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer)
1312
			print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editconditions&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetConditions'), 1) . '</a></td>';
1313
		print '</tr></table>';
1314
		print '</td><td>';
1315
		if ($object->type != Facture::TYPE_CREDIT_NOTE)
1316
		{
1317
			if ($action == 'editconditions')
1318
			{
1319
				$form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id');
1320
			}
1321
			else
1322
			{
1323
				$form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none');
1324
			}
1325
		} else {
1326
			print '&nbsp;';
1327
		}
1328
		print '</td></tr>';
1329
1330
		// Payment mode
1331
		print '<tr><td>';
1332
		print '<table class="nobordernopadding" width="100%"><tr><td>';
1333
		print $langs->trans('PaymentMode');
1334
		print '</td>';
1335
		if ($action != 'editmode' && ! empty($object->brouillon) && $user->rights->facture->creer)
1336
			print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmode&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetMode'), 1) . '</a></td>';
1337
		print '</tr></table>';
1338
		print '</td><td>';
1339
		if ($action == 'editmode')
1340
		{
1341
			$form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT');
1342
		}
1343
		else
1344
		{
1345
			$form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none', 'CRDT');
1346
		}
1347
		print '</td></tr>';
1348
1349
		// Help of substitution key
1350
		$dateexample=dol_now();
1351
		if (! empty($object->frequency) && ! empty($object->date_when)) $dateexample=$object->date_when;
1352
1353
		$substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object);
1354
1355
		$substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')';
1356
		$substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')';
1357
		$substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')';
1358
		$substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')';
1359
		$substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')';
1360
		$substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')';
1361
		$substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')';
1362
		$substitutionarray['__INVOICE_YEAR__'] =  $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')';
1363
		$substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')';
1364
		// Only on template invoices
1365
		$substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date(($object->date_when?$object->date_when:dol_now()), 'dayhour').')';
1366
		$substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree(($object->date_when?$object->date_when:dol_now()), $object->frequency, $object->unit_frequency),'dayhour').')';
1367
1368
		$htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
1369
		foreach($substitutionarray as $key => $val)
1370
		{
1371
			$htmltext.=$key.' = '.$langs->trans($val).'<br>';
1372
		}
1373
		$htmltext.='</i>';
1374
1375
		// Note public
1376
		print '<tr><td>';
1377
		print $form->editfieldkey($form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic'), 'note_public', $object->note_public, $object, $user->rights->facture->creer);
1378
		print '</td><td class="wordbreak">';
1379
		print $form->editfieldval($langs->trans("NotePublic"), 'note_public', $object->note_public, $object, $user->rights->facture->creer, 'textarea:'.ROWS_4.':90%', '', null, null, '', 1);
1380
		print '</td>';
1381
		print '</tr>';
1382
1383
		// Note private
1384
		print '<tr><td>';
1385
		print $form->editfieldkey($form->textwithpicto($langs->trans("NotePrivate"), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'), 'note_private', $object->note_private, $object, $user->rights->facture->creer);
1386
		print '</td><td class="wordbreak">';
1387
		print $form->editfieldval($langs->trans("NotePrivate"), 'note_private', $object->note_private, $object, $user->rights->facture->creer, 'textarea:'.ROWS_4.':90%', '', null, null, '', 1);
1388
		print '</td>';
1389
		print '</tr>';
1390
1391
		// Bank Account
1392
		$langs->load('banks');
1393
1394
		print '<tr><td class="nowrap">';
1395
		print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
1396
		print $langs->trans('RIB');
1397
		print '<td>';
1398
		if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon))
1399
			print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'),1).'</a></td>';
1400
		print '</tr></table>';
1401
		print '</td><td>';
1402
		if ($action == 'editbankaccount')
1403
		{
1404
			$form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
1405
		}
1406
		else
1407
		{
1408
			$form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
1409
		}
1410
		print "</td>";
1411
		print '</tr>';
1412
1413
        // Model pdf
1414
        $langs->load('banks');
1415
1416
        print '<tr><td class="nowrap">';
1417
        print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
1418
        print $langs->trans('Model');
1419
        print '<td>';
1420
        if (($action != 'editmodelpdf') && $user->rights->facture->creer && ! empty($object->brouillon))
1421
            print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editmodelpdf&amp;id='.$object->id.'">'.img_edit($langs->trans('SetModel'),1).'</a></td>';
1422
        print '</tr></table>';
1423
        print '</td><td>';
1424
        if ($action == 'editmodelpdf')
1425
        {
1426
            include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
1427
            $list = array();
1428
            $models = ModelePDFFactures::liste_modeles($db);
1429
            foreach ($models as $model) {
1430
                $list[] = $model . ':' . $model;
1431
            }
1432
            $select = 'select;'.implode(',', $list);
1433
            print $form->editfieldval($langs->trans("Model"), 'modelpdf', $object->modelpdf, $object, $user->rights->facture->creer, $select);
1434
        }
1435
        else
1436
        {
1437
            print $object->modelpdf;
1438
        }
1439
        print "</td>";
1440
        print '</tr>';
1441
1442
		// Other attributes
1443
		$cols = 2;
1444
		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
1445
1446
		print '</table>';
1447
1448
		print '</div>';
1449
		print '<div class="fichehalfright">';
1450
		print '<div class="ficheaddleft">';
1451
		print '<div class="underbanner clearboth"></div>';
1452
1453
1454
		/*
1455
		 * Recurrence
1456
		 */
1457
		$title = $langs->trans("Recurrence");
1458
		//print load_fiche_titre($title, '', 'calendar');
1459
1460
		print '<table class="border" width="100%">';
1461
1462
		print '<tr><td colspan="2"><span class="fa fa-calendar"></span> '.$title.'</td></tr>';
1463
1464
		// if "frequency" is empty or = 0, the reccurence is disabled
1465
		print '<tr><td style="width: 50%">';
1466
		print '<table class="nobordernopadding" width="100%"><tr><td>';
1467
		print $langs->trans('Frequency');
1468
		print '</td>';
1469
		if ($action != 'editfrequency' && ! empty($object->brouillon) && $user->rights->facture->creer)
1470
			print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editfrequency&amp;facid=' . $object->id . '">' . img_edit($langs->trans('Edit'), 1) . '</a></td>';
1471
		print '</tr></table>';
1472
		print '</td><td>';
1473
		if ($action == 'editfrequency')
1474
		{
1475
			print '<form method="post" action="'.$_SERVER["PHP_SELF"] . '?facid=' . $object->id.'">';
1476
			print '<input type="hidden" name="action" value="setfrequency">';
1477
			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1478
			print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
1479
			print '<tr><td>';
1480
			print "<input type='text' name='frequency' value='".$object->frequency."' size='5' />&nbsp;".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), ($object->unit_frequency?$object->unit_frequency:'m'));
1481
			print '</td>';
1482
			print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
1483
			print '</tr></table></form>';
1484
		}
1485
		else
1486
		{
1487
				if ($object->frequency > 0)
1488
				{
1489
					print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency);
1490
				}
1491
				else
1492
				{
1493
					print $langs->trans("NotARecurringInvoiceTemplate");
1494
			}
1495
		}
1496
		print '</td></tr>';
1497
1498
		// Date when (next invoice generation)
1499
		print '<tr><td>';
1500
		if ($action == 'date_when' || $object->frequency > 0)
1501
		{
1502
			print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day');
1503
		}
1504
		else
1505
		{
1506
			print $langs->trans("NextDateToExecution");
1507
		}
1508
		print '</td><td>';
1509
		if ($action == 'date_when' || $object->frequency > 0)
1510
		{
1511
			print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached');
1512
		}
1513
		//var_dump(dol_print_date($object->date_when+60, 'dayhour').' - '.dol_print_date($now, 'dayhour'));
1514
		if (! $object->isMaxNbGenReached())
1515
		{
1516
			if (! $object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) print img_warning($langs->trans("Late"));
1517
		}
1518
		else
1519
		{
1520
			print img_info($langs->trans("MaxNumberOfGenerationReached"));
1521
		}
1522
		print '</td>';
1523
		print '</tr>';
1524
1525
		// Max period / Rest period
1526
		print '<tr><td>';
1527
		if ($action == 'nb_gen_max' || $object->frequency > 0)
1528
		{
1529
			print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer);
1530
		}
1531
		else
1532
		{
1533
			print $langs->trans("MaxPeriodNumber");
1534
		}
1535
		print '</td><td>';
1536
		if ($action == 'nb_gen_max' || $object->frequency > 0)
1537
		{
1538
			  print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max?$object->nb_gen_max:'', $object, $user->rights->facture->creer);
1539
		}
1540
		else
1541
		{
1542
			print '';
1543
		}
1544
		print '</td>';
1545
		print '</tr>';
1546
1547
		// Status of generated invoices
1548
		print '<tr><td>';
1549
		if ($action == 'auto_validate' || $object->frequency > 0)
1550
			print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer);
1551
		else
1552
			print $langs->trans("StatusOfGeneratedInvoices");
1553
		print '</td><td>';
1554
		$select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated');
1555
		if ($action == 'auto_validate' || $object->frequency > 0)
1556
		{
1557
			print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select);
1558
		}
1559
		print '</td>';
1560
		// Auto generate documents
1561
		if (! empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION))
1562
		{
1563
			print '<tr>';
1564
			print '<td>';
1565
			if ($action == 'generate_pdf' || $object->frequency > 0)
1566
				print $form->editfieldkey($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', $object->generate_pdf, $object, $user->rights->facture->creer);
1567
			else
1568
				print $langs->trans("StatusOfGeneratedDocuments");
1569
			print '</td>';
1570
			print '<td>';
1571
			$select = 'select;0:'.$langs->trans('DoNotGenerateDoc').',1:'.$langs->trans('AutogenerateDoc');
1572
			if ($action == 'generate_pdf' || $object->frequency > 0)
1573
			{
1574
				print $form->editfieldval($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', $object->generate_pdf, $object, $user->rights->facture->creer, $select);
1575
			}
1576
			print '</td>';
1577
			print '</tr>';
1578
		}
1579
		else
1580
		{
1581
			print '<input type="hidden" name="generate_pdf" value="1">';
1582
		}
1583
1584
		print '</table>';
1585
1586
		// Frequencry/Recurring section
1587
		if ($object->frequency > 0)
1588
		{
1589
			print '<br>';
1590
1591
			if (empty($conf->cron->enabled))
1592
			{
1593
				print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name")));
1594
			}
1595
1596
			print '<div class="underbanner clearboth"></div>';
1597
			print '<table class="border centpercent">';
1598
1599
			// Nb of generation already done
1600
			print '<tr><td style="width: 50%">'.$langs->trans("NbOfGenerationDone").'</td>';
1601
			print '<td>';
1602
			print $object->nb_gen_done?$object->nb_gen_done:'0';
1603
			print '</td>';
1604
			print '</tr>';
1605
1606
			// Date last
1607
			print '<tr><td>';
1608
			print $langs->trans("DateLastGeneration");
1609
			print '</td><td>';
1610
			print dol_print_date($object->date_last_gen, 'dayhour');
1611
			print '</td>';
1612
			print '</tr>';
1613
1614
			print '</table>';
1615
1616
			print '<br>';
1617
		}
1618
1619
		print '</div>';
1620
		print '</div>';
1621
		print '</div>';
1622
1623
		print '<div class="clearboth"></div><br>';
1624
1625
1626
		// Lines
1627
		print '	<form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . (($action != 'editline') ? '#add' : '#line_' . GETPOST('lineid')) . '" method="POST">
1628
        	<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">
1629
        	<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline') . '">
1630
        	<input type="hidden" name="mode" value="">
1631
        	<input type="hidden" name="id" value="' . $object->id . '">
1632
        	';
1633
1634
		if (! empty($conf->use_javascript_ajax) && $object->statut == 0) {
1635
			include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
1636
		}
1637
1638
		print '<div class="div-table-responsive-no-min">';
1639
		print '<table id="tablelines" class="noborder noshadow" width="100%">';
1640
		// Show object lines
1641
		if (! empty($object->lines))
1642
		{
1643
			//$disableedit=1;
1644
			//$disablemove=1;
1645
			$ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0);      // No date selector for template invoice
1646
		}
1647
1648
		// Form to add new line
1649
		if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline')
1650
		{
1651
			if ($action != 'editline')
1652
			{
1653
				// Add free products/services
1654
				$object->formAddObjectLine(0, $mysoc, $object->thirdparty);                          // No date selector for template invoice
1655
1656
				$parameters = array();
1657
				$reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1658
			}
1659
		}
1660
1661
		print "</table>\n";
1662
		print '</div>';
1663
1664
		print "</form>\n";
1665
1666
		dol_fiche_end();
1667
1668
1669
		/**
1670
		 * Barre d'actions
1671
		 */
1672
		print '<div class="tabsAction">';
1673
1674
		if (empty($object->suspended))
1675
		{
1676
			if ($user->rights->facture->creer)
1677
			{
1678
				if (! empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max))
1679
				{
1680
					print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("MaxGenerationReached")).'">'.$langs->trans("CreateBill").'</a></div>';
1681
				}
1682
				else
1683
				{
1684
					if (empty($object->frequency) || $object->date_when <= $today)
1685
					{
1686
						print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&socid='.$object->thirdparty->id.'&fac_rec='.$object->id.'">'.$langs->trans("CreateBill").'</a></div>';
1687
					}
1688
					else
1689
					{
1690
						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("DateIsNotEnough")).'">'.$langs->trans("CreateBill").'</a></div>';
1691
					}
1692
				}
1693
			}
1694
			else
1695
			{
1696
				print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("CreateBill").'</a></div>';
1697
			}
1698
		}
1699
1700
		if ($user->rights->facture->creer)
1701
		{
1702
			if (empty($object->suspended))
1703
			{
1704
				print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.DOL_URL_ROOT.'/compta/facture/fiche-rec.php?action=disable&id='.$object->id.'">'.$langs->trans("Disable").'</a></div>';
1705
			}
1706
			else
1707
			{
1708
				print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/fiche-rec.php?action=enable&id='.$object->id.'">'.$langs->trans("Enable").'</a></div>';
1709
			}
1710
		}
1711
1712
		//if ($object->statut == Facture::STATUS_DRAFT && $user->rights->facture->supprimer)
1713
		if ($user->rights->facture->supprimer)
1714
		{
1715
			print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=ask_deleteinvoice&id='.$object->id.'">'.$langs->trans('Delete').'</a></div>';
1716
		}
1717
1718
		print '</div>';
1719
1720
1721
1722
		print '<div class="fichecenter"><div class="fichehalfleft">';
1723
		print '<a name="builddoc"></a>'; // ancre
1724
1725
1726
		// Show links to link elements
1727
		$linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
1728
1729
		$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
1730
1731
1732
		print '</div></div>';
1733
	}
1734
}
1735
1736
// End of page
1737
llxFooter();
1738
$db->close();
1739