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