dolibarr 25.0.0-alpha
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-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
10 * Copyright (C) 2016 Meziane Sof <virtualsof@yahoo.fr>
11 * Copyright (C) 2017-2026 Frédéric France <frederic.france@free.fr>
12 * Copyright (C) 2023-2024 Nick Fragoulis
13 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27 */
28
35// Load Dolibarr environment
36require '../../main.inc.php';
37
47require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture-rec.class.php';
48require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
49require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
50require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
51if (isModEnabled('project')) {
52 include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
53}
54require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
55require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
56require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
57require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
58
59// Load translation files required by the page
60$langs->loadLangs(array('bills', 'companies', 'compta', 'admin', 'other', 'products', 'banks', 'suppliers'));
61
62$action = GETPOST('action', 'alpha');
63$massaction = GETPOST('massaction', 'alpha');
64$show_files = GETPOSTINT('show_files');
65$confirm = GETPOST('confirm', 'alpha');
66$cancel = GETPOST('cancel', 'alpha');
67$toselect = GETPOST('toselect', 'array:int');
68$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'supplierinvoicetemplatelist'; // To manage different context of search
69$backtopage = GETPOST('backtopage', 'alpha'); // if not set, a default page will be used
70$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); // if not set, $backtopage will be used
71
72
73$id = (GETPOSTINT('facid') ? GETPOSTINT('facid') : GETPOSTINT('id'));
74$lineid = GETPOSTINT('lineid');
75$ref = GETPOST('title', 'alphanohtml') ? GETPOST('title', 'alphanohtml') : GETPOST('ref', 'alphanohtml');
76$label = GETPOST('label', 'alphanohtml');
77$ref_supplier = GETPOST('ref_supplier', 'alphanohtml');
78$projectid = GETPOSTINT('projectid');
79$year_date_when = GETPOST('year_date_when');
80$month_date_when = GETPOST('month_date_when');
81// Security check
82$socid = GETPOSTINT('socid');
83if ($user->socid) {
84 $socid = $user->socid;
85}
86$objecttype = 'facture_fourn_rec';
87if ($action == "create" || $action == "add") {
88 $objecttype = '';
89}
90
91$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
92$sortfield = GETPOST("sortfield", 'aZ09comma');
93$sortorder = GETPOST("sortorder", 'aZ09comma');
94$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
95if (empty($page) || $page == -1) {
96 $page = 0;
97} // If $page is not defined, or '' or -1
98$offset = $limit * $page;
99if (! $sortorder) {
100 $sortorder = 'DESC';
101}
102if (! $sortfield) {
103 $sortfield = 'f.titre';
104}
105$pageprev = $page - 1;
106$pagenext = $page + 1;
107
109if (($id > 0 || $ref) && $action != 'create' && $action != 'add') {
110 $ret = $object->fetch($id, $ref);
111 if (! $ret) {
112 setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors');
113 }
114}
115
116// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
117$hookmanager->initHooks(array('supplierinvoicereccard', 'globalcard'));
118$extrafields = new ExtraFields($db);
119
120// fetch optionals attributes and labels
121$extrafields->fetch_name_optionals_label($object->table_element);
122
123$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
124
125$permissionnote = $user->hasRight("fournisseur", "facture", "creer") || $user->hasRight("supplier_invoice", "creer"); // Used by the include of actions_setnotes.inc.php
126$permissiondellink = $user->hasRight("fournisseur", "facture", "creer") || $user->hasRight("supplier_invoice", "creer"); // Used by the include of actions_dellink.inc.php
127$permissiontoedit = $user->hasRight("fournisseur", "facture", "creer") || $user->hasRight("supplier_invoice", "creer"); // Used by the include of actions_lineupdonw.inc.php
128$permissiontoadd = $user->hasRight("fournisseur", "facture", "creer") || $user->hasRight("supplier_invoice", "creer");
129$permissiontodelete = ($user->hasRight("fournisseur", "facture", "supprimer") || $user->hasRight("supplier_invoice", "supprimer"));
130$permissiontoeditextra = $permissiontoadd;
131if (GETPOST('attribute', 'aZ09') && isset($extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')])) {
132 // For action 'update_extras', is there a specific permission set for the attribute to update
133 $permissiontoeditextra = dol_eval((string) $extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')]);
134}
135
136$usercanread = $user->hasRight("fournisseur", "facture", "lire") || $user->hasRight("supplier_invoice", "lire");
137$usercancreate = $user->hasRight("fournisseur", "facture", "creer") || $user->hasRight("supplier_invoice", "creer");
138$usercandelete = $user->hasRight("fournisseur", "facture", "supprimer") || $user->hasRight("supplier_invoice", "supprimer");
139$usercanvalidate = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !empty($usercancreate)) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight("fournisseur", "supplier_invoice_advance", "validate")));
140$usercansend = (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || $user->hasRight("fournisseur", "supplier_invoice_advance", "send"));
141
142$usercanproductignorepricemin = ((getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight("produit", "ignore_price_min_advance")) || !getDolGlobalString('MAIN_USE_ADVANCED_PERMS'));
143$usercancreatemargin = $user->hasRight("margins", "creer");
144$usercanreadallmargin = $user->hasRight("margins", "liretous");
145$usercancreatewithdrarequest = $user->hasRight("prelevement", "bons", "creer");
146
147$now = dol_now();
148
149$error = 0;
150$predef = ''; // Legacy? Used in several cards, always ''
151
152// Security check
153$result = restrictedArea($user, 'supplier_invoicerec', $object->id, $objecttype);
154
155
156/*
157 * Actions
158 */
159
160if (GETPOST('cancel', 'alpha')) {
161 if ($action != 'updateline') {
162 $action = 'list';
163 $massaction = '';
164 } else {
165 $action = '';
166 $cancel = '';
167 }
168}
169if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
170 $massaction = '';
171}
172
173$parameters = array('socid' => $socid);
174$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
175if ($reshook < 0) {
176 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
177}
178
179if (empty($reshook)) {
180 if (GETPOST('cancel', 'alpha')) {
181 $action = '';
182 }
183
184 // Selection of new fields
185 include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php';
186
187 // Set note
188 include DOL_DOCUMENT_ROOT . '/core/actions_setnotes.inc.php'; // Must be 'include', not 'include_once'
189
190 include DOL_DOCUMENT_ROOT . '/core/actions_dellink.inc.php'; // Must be 'include', not 'include_once'
191
192 include DOL_DOCUMENT_ROOT . '/core/actions_lineupdown.inc.php'; // Must be 'include', not 'include_once'
193
194 // Create predefined invoice
195 if ($action == 'add' && $permissiontoadd) {
196 if (! GETPOST('title', 'alphanohtml')) {
197 setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Title")), null, 'errors');
198 $action = "create";
199 $error++;
200 }
201
202 $frequency = GETPOSTINT('frequency');
203 $reyear = GETPOSTINT('reyear');
204 $remonth = GETPOSTINT('remonth');
205 $reday = GETPOSTINT('reday');
206 $rehour = GETPOSTINT('rehour');
207 $remin = GETPOSTINT('remin');
208 $nb_gen_max = GETPOSTINT('nb_gen_max');
209 //if (empty($nb_gen_max)) $nb_gen_max =0;
210
211 if (GETPOSTINT('frequency')) {
212 if (empty($reyear) || empty($remonth) || empty($reday)) {
213 setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Date")), null, 'errors');
214 $action = "create";
215 $error++;
216 }
217 }
218
219 if (! $error) {
220 $object->subtype = GETPOSTINT('subtype');
221 $object->title = GETPOST('title', 'alphanohtml');
222 $object->ref = GETPOST('title', 'alphanohtml');
223 $object->label = GETPOST('label', 'alpha');
224 $object->ref_supplier = GETPOST('ref_supplier', 'alphanohtml');
225
226 $object->note_private = GETPOST('note_private', 'restricthtml');
227 $object->note_public = GETPOST('note_public', 'restricthtml');
228 $object->model_pdf = GETPOST('modelpdf', 'alpha');
229 $object->usenewprice = GETPOSTINT('usenewprice');
230
231 $object->frequency = $frequency;
232 $object->unit_frequency = GETPOST('unit_frequency', 'alpha');
233 $object->nb_gen_max = $nb_gen_max;
234 $object->auto_validate = GETPOSTINT('auto_validate');
235 $object->generate_pdf = GETPOSTINT('generate_pdf');
236 $object->fk_project = GETPOSTINT('projectid');
237
238 $date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear);
239 $object->date_when = $date_next_execution;
240
241 $ret = $extrafields->setOptionalsFromPost(null, $object);
242 if ($ret < 0) {
243 setEventMessages($extrafields->error, $extrafields->errors, 'errors');
244 $error++;
245 }
246
247
248 $db->begin();
249
250 $oldinvoice = new FactureFournisseur($db);
251 $oldinvoice->fetch(GETPOSTINT('facid'));
252
253 $onlylines = GETPOST('toselect', 'array:int');
254
255 $result = $object->create($user, $oldinvoice->id, 0, $onlylines);
256
257 if ($result > 0) {
258 $result = $oldinvoice->delete($user, 1);
259 if ($result < 0) {
260 $error++;
261 setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors');
262 $action = "create";
263 }
264 } else {
265 $error++;
266 setEventMessages($object->error, $object->errors, 'errors');
267 $action = "create";
268 }
269
270 if (! $error) {
271 $db->commit();
272
273 header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id);
274 exit;
275 } else {
276 $db->rollback();
277
278 $action = "create";
279 }
280 }
281 }
282
283 // Delete
284 if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $permissiontodelete) {
285 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
286 $result = $object->delete($user);
287 if ($result > 0) {
288 header('Location: ' . DOL_URL_ROOT . '/fourn/facture/list-rec.php');
289 exit;
290 } else {
291 setEventMessages($object->error, $object->errors, 'errors');
292 }
293 }
294
295 // Update field
296 // Set condition
297 if ($action == 'setconditions' && $usercancreate) {
298 $result = $object->setPaymentTerms(GETPOSTINT('cond_reglement_id'));
299 } elseif ($action == 'setmode' && $usercancreate) {
300 // Set mode
301 $result = $object->setPaymentMethods(GETPOSTINT('mode_reglement_id'));
302 } elseif ($action == 'classin' && $usercancreate) {
303 // Set project
304 $object->setProject(GETPOSTINT('projectid'));
305 } elseif ($action == 'setref_supplier' && $usercancreate) {
306 $result = $object->setValueFrom('ref_supplier', $ref_supplier, '', null, 'text', '', $user);
307
308 if ($result <= 0) {
309 $error++;
310 if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
311 $langs->load("errors");
312 setEventMessages($langs->trans('ErrorRefAlreadyExists', $ref_supplier), null, 'errors');
313 } else {
314 setEventMessages($object->error, $object->errors, 'errors');
315 }
316 }
317 } elseif ($action == 'settitle' && $permissiontoadd) {
318 $result = $object->setValueFrom('titre', $ref, '', null, 'text', '', $user);
319
320 if ($result > 0) {
321 $object->title = $ref;
322 $object->ref = $ref;
323 } else {
324 $error++;
325 if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
326 $langs->load("errors");
327 setEventMessages($langs->trans('ErrorTitreAlreadyExists', $ref), null, 'errors');
328 } else {
329 setEventMessages($object->error, $object->errors, 'errors');
330 }
331 }
332 } elseif ($action == 'setbankaccount' && $permissiontoadd) {
333 // Set bank account
334 $result = $object->setBankAccount(GETPOSTINT('fk_account'));
335 } elseif ($action == 'setfrequency' && $permissiontoadd) {
336 // Set frequency and unit frequency
337 $object->setFrequencyAndUnit((GETPOST('frequency') != '' ? GETPOSTINT('frequency') : null), GETPOST('unit_frequency', 'alpha'));
338 } elseif ($action == 'setdate_when' && $permissiontoadd) {
339 // Set next date of execution
340 $date = dol_mktime(GETPOSTINT('date_whenhour'), GETPOSTINT('date_whenmin'), 0, GETPOSTINT('date_whenmonth'), GETPOSTINT('date_whenday'), GETPOSTINT('date_whenyear'));
341 if (!empty($date)) {
342 $object->setNextDate($date);
343 }
344 } elseif ($action == 'setnb_gen_max' && $permissiontoadd) {
345 // Set max period
346 $object->setMaxPeriod(GETPOSTINT('nb_gen_max'));
347 } elseif ($action == 'setauto_validate' && $permissiontoadd) {
348 // Set auto validate
349 $object->setAutoValidate(GETPOSTINT('auto_validate'));
350 } elseif ($action == 'setgenerate_pdf' && $permissiontoadd) {
351 // Set generate pdf
352 $object->setGeneratepdf(GETPOSTINT('generate_pdf'));
353 } elseif ($action == 'setmodelpdf' && $permissiontoadd) {
354 // Set model pdf
355 $object->setModelpdf(GETPOST('modelpdf', 'alpha'));
356 } elseif ($action == 'disable' && $permissiontoadd) {
357 // Set status disabled
358 $db->begin();
359
360 $object->fetch($id);
361
362 $res = $object->setValueFrom('suspended', 1);
363 if ($res <= 0) {
364 $error++;
365 }
366
367 if (! $error) {
368 $db->commit();
369 } else {
370 $db->rollback();
371 setEventMessages($object->error, $object->errors, 'errors');
372 }
373 } elseif ($action == 'enable' && $permissiontoadd) {
374 // Set status enabled
375 $db->begin();
376
377 $object->context['actionmsg'] = $langs->trans("RecordEnabled");
378
379 $object->fetch($id);
380
381 $res = $object->setValueFrom('suspended', 0);
382 if ($res <= 0) {
383 $error++;
384 }
385
386 if (! $error) {
387 $db->commit();
388 } else {
389 $db->rollback();
390 setEventMessages($object->error, $object->errors, 'errors');
391 }
392 } elseif ($action == 'setmulticurrencycode' && $permissiontoadd) {
393 // Multicurrency Code
394 $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
395 } elseif ($action == 'setmulticurrencyrate' && $permissiontoadd) {
396 // Multicurrency rate
397 if (!in_array(GETPOSTINT('calculation_mode'), array(1, 2))) {
398 $langs->load("compta");
399 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CalculationMode")), null, 'errors');
400 $action = 'editmulticurrencyrate';
401 } else {
402 $result = $object->setMulticurrencyRate((float) price2num(GETPOST('multicurrency_tx')), GETPOSTINT('calculation_mode'));
403 }
404 } elseif ($action == 'setlabel' && $permissiontoadd) {
405 // Set bank account
406 $result = $object->setValueFrom('libelle', $label, '', null, 'text', '', $user);
407 }
408
409 // Delete line
410 if ($action == 'confirm_deleteline' && $confirm == 'yes' && $permissiontoadd) {
411 $object->fetch($id);
412 $object->fetch_thirdparty();
413
414 $db->begin();
415
416 $line = new FactureFournisseurLigneRec($db);
417
418 // For triggers
419 $line->id = $lineid;
420
421 if ($line->delete($user) > 0) {
422 $result = $object->update_price(1);
423
424 if ($result > 0) {
425 $db->commit();
426 $object->fetch($object->id); // Reload lines
427 } else {
428 $db->rollback();
429 setEventMessages($db->lasterror(), null, 'errors');
430 }
431 } else {
432 $db->rollback();
433 setEventMessages($line->error, $line->errors, 'errors');
434 }
435 } elseif ($action == 'update_extras' && $permissiontoeditextra) {
436 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
437
438 $attribute_name = GETPOST('attribute', 'aZ09');
439
440 // Fill array 'array_options' with data from update form
441 $ret = $extrafields->setOptionalsFromPost(null, $object, $attribute_name);
442 if ($ret < 0) {
443 $error++;
444 }
445
446 if (!$error) {
447 $result = $object->updateExtraField($attribute_name, 'BILLREC_MODIFY');
448 if ($result < 0) {
449 setEventMessages($object->error, $object->errors, 'errors');
450 $error++;
451 }
452 }
453
454 if ($error) {
455 $action = 'edit_extras';
456 }
457 }
458
459 // Add a new line
460 if ($action == 'addline' && $permissiontoadd) {
461 $langs->load('errors');
462 $error = 0;
463
464 // Set if we used free entry or predefined product
465 $predef = '';
466 $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
467 $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
468 $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
469 $prod_entry_mode = GETPOST('prod_entry_mode', 'alpha');
470 if ($prod_entry_mode == 'free') {
471 $idprod = 0;
472 $tva_tx = (GETPOST('tva_tx', 'alpha') ? (string) GETPOST('tva_tx', 'alpha') : 0);
473 $ref_fournisseur = (GETPOSTISSET('fourn_ref') ? GETPOST('fourn_ref', 'restricthtml') : '');
474 } else {
475 $idprod = GETPOSTINT('idprod');
476 $tva_tx = '';
477 }
478
479 $qty = GETPOST('qty' . $predef, 'alpha');
480 $qty = ($qty === '') ? '' : (float) price2num(GETPOST('qty' . $predef, 'alpha'), 'MS', 2);
481 $remise_percent = price2num(GETPOST('remise_percent' . $predef), '', 2);
482
483 // Extrafields
484 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
485 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
486 // Unset extrafield
487 if (is_array($extralabelsline)) {
488 // Get extra fields
489 foreach ($extralabelsline as $key => $value) {
490 unset($_POST["options_" . $key . $predef]);
491 }
492 }
493
494 if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ((float) $qty < 0)) {
495 setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
496 $error++;
497 }
498 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
499 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
500 $error++;
501 }
502 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && (! ($price_ht >= 0) || $price_ht == '')) { // Unit price can be 0 but not ''
503 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
504 $error++;
505 }
506 if ($qty == '') {
507 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
508 $error++;
509 }
510 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && empty($product_desc)) {
511 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
512 $error++;
513 }
514 if ($qty < 0) {
515 $langs->load("errors");
516 setEventMessages($langs->trans('ErrorQtyForSupplierInvoiceCantBeNegative'), null, 'errors');
517 $error++;
518 }
519
520 $ref_fournisseur = null;
521 if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
522 $productsupplier = new ProductFournisseur($db);
523
524 $idprod = 0;
525 if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') {
526 $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...)
527 }
528 $reg = array();
529 if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) {
530 $idprod = (int) $reg[1];
531 $res = $productsupplier->fetch($idprod); // Load product from its id
532 // Call to init some price properties of $productsupplier
533 // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price
534 if (getDolGlobalString('SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER')) {
535 $fksoctosearch = 0;
536 $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
537 if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price
538 $productsupplier->ref_supplier = '';
539 }
540 } else {
541 $fksoctosearch = $object->thirdparty->id;
542 $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
543 }
544 } elseif (GETPOSTINT('idprodfournprice') > 0) { // Not a string here
545 $qtytosearch = $qty; // Just to see if a price exists for the quantity. Not used to found vat.
546 $idprod = $productsupplier->get_buyprice(GETPOSTINT('idprodfournprice'), $qtytosearch);
547 $res = $productsupplier->fetch($idprod);
548 $ref_fournisseur = $productsupplier->ref_supplier;
549 }
550 }
551
552 if (! $error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
553 $ret = $object->fetch($id);
554 if ($ret < 0) {
555 dol_print_error($db, $object->error);
556 exit();
557 }
558 $ret = $object->fetch_thirdparty();
559
560 // Clean parameters
561 $date_start = dol_mktime(GETPOSTINT('date_start' . $predef . 'hour'), GETPOSTINT('date_start' . $predef . 'min'), GETPOSTINT('date_start' . $predef . 'sec'), GETPOSTINT('date_start' . $predef . 'month'), GETPOSTINT('date_start' . $predef . 'day'), GETPOSTINT('date_start' . $predef . 'year'));
562 $date_end = dol_mktime(GETPOSTINT('date_end' . $predef . 'hour'), GETPOSTINT('date_end' . $predef . 'min'), GETPOSTINT('date_end' . $predef . 'sec'), GETPOSTINT('date_end' . $predef . 'month'), GETPOSTINT('date_end' . $predef . 'day'), GETPOSTINT('date_end' . $predef . 'year'));
563 $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
564
565 // Define special_code for special lines
566 $special_code = 0;
567 $price_min = 0;
568 // if (!GETPOST('qty')) $special_code=3; // Options should not exists on invoices
569
570 // Ecrase $pu par celui du produit
571 // Ecrase $desc par celui du produit
572 // Ecrase $tva_tx par celui du produit
573 // Ecrase $base_price_type par celui du produit
574 // Replaces $fk_unit with the product's
575 if (!empty($idprod) && $idprod > 0) {
576 $prod = new Product($db);
577 $prod->fetch($idprod);
578
579 $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
580
581 // Update if prices fields are defined
582 $tva_tx = get_default_tva($object->thirdparty, $mysoc, $prod->id);
583 $tva_npr = get_default_npr($object->thirdparty, $mysoc, $prod->id);
584 if (empty($tva_tx)) {
585 $tva_npr = 0;
586 }
587
588 // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
589 $pqp = (GETPOSTINT('pbq') ? GETPOSTINT('pbq') : 0);
590
591 $datapriceofproduct = $prod->getSellPrice($object->thirdparty, $mysoc, $pqp);
592
593 $pu_ht = $datapriceofproduct['pu_ht'];
594 $pu_ttc = $datapriceofproduct['pu_ttc'];
595 $price_min = $datapriceofproduct['price_min'];
596 $price_base_type = empty($datapriceofproduct['price_base_type']) ? 'HT' : $datapriceofproduct['price_base_type'];
597 $tva_tx = $datapriceofproduct['tva_tx'];
598 $tva_npr = $datapriceofproduct['tva_npr'];
599
600 $tmpvat = price2num(preg_replace('/\s*\‍(.*\‍)/', '', (string) $tva_tx));
601 $tmpprodvat = price2num(preg_replace('/\s*\‍(.*\‍)/', '', (string) $prod->tva_tx));
602
603 // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ?
604 if (!empty($price_ht)) {
605 $pu_ht = price2num($price_ht, 'MU');
606 $pu_ttc = price2num((float) $pu_ht * (1 + ((float) $tmpvat / 100)), 'MU');
607 } elseif ($tmpvat != $tmpprodvat) {
608 // We reevaluate the price according to the var rate because vat of transaction can be different of
609 // the one of the product by default (for example when country is different between seller and buyer).
610 if ($price_base_type != 'HT') {
611 $pu_ht = price2num($pu_ttc / (1 + ((float) $tmpvat / 100)), 'MU');
612 } else {
613 $pu_ttc = price2num($pu_ht * (1 + ((float) $tmpvat / 100)), 'MU');
614 }
615 }
616
617 $outputlangs = $langs;
618 $newlang = '';
619 $desc = '';
620
621 // Define output language
622 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
623 if (/* empty($newlang) && */ GETPOST('lang_id', 'aZ09')) {
624 $newlang = GETPOST('lang_id', 'aZ09');
625 }
626 if (empty($newlang)) {
627 $newlang = $object->thirdparty->default_lang;
628 }
629 if (!empty($newlang)) {
630 $outputlangs = new Translate("", $conf);
631 $outputlangs->setDefaultLang($newlang);
632 $outputlangs->load('products');
633 }
634
635 $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
636 } else {
637 $desc = $prod->description;
638 }
639
640 $desc = dol_concatdesc($desc, $product_desc);
641
642 // Add custom code and origin country into description
643 if (!getDolGlobalString('MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE') && (!empty($prod->customcode) || !empty($prod->country_code))) {
644 $tmptxt = '(';
645 // Define output language
646 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
647 if (!empty($prod->customcode)) {
648 $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomsCode") . ': ' . $prod->customcode;
649 }
650 if (!empty($prod->customcode) && !empty($prod->country_code)) {
651 $tmptxt .= ' - ';
652 }
653 if (!empty($prod->country_code)) {
654 $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, '', $db, $outputlangs, 0);
655 }
656 } else {
657 if (!empty($prod->customcode)) {
658 $tmptxt .= $langs->transnoentitiesnoconv("CustomsCode") . ': ' . $prod->customcode;
659 }
660 if (!empty($prod->customcode) && !empty($prod->country_code)) {
661 $tmptxt .= ' - ';
662 }
663 if (!empty($prod->country_code)) {
664 $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, '', $db, $langs, 0);
665 }
666 }
667 $tmptxt .= ')';
668 $desc = dol_concatdesc($desc, $tmptxt);
669 }
670
671 $type = $prod->type;
672 $fk_unit = $prod->fk_unit;
673 } else {
674 $pu_ht = price2num($price_ht, 'MU');
675 $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
676 $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
677 $tva_tx = str_replace('*', '', $tva_tx);
678 if (empty($tva_tx)) {
679 $tva_npr = 0;
680 }
681 $desc = $product_desc;
682 $type = GETPOST('type');
683 $fk_unit = GETPOSTINT('units');
684 }
685
686 $date_start_fill = GETPOSTINT('date_start_fill');
687 $date_end_fill = GETPOSTINT('date_end_fill');
688
689 // Margin
690 $fournprice = (int) (GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); // This can be id of supplier price, or 'pmpprice' or 'costprice', or 'inputprice', we force to keep ID only
691 $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value
692
693 // Local Taxes
694 $localtax1_tx = get_localtax((string) $tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr);
695 $localtax2_tx = get_localtax((string) $tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr);
696 $info_bits = 0;
697 if ($tva_npr) {
698 $info_bits |= 0x01;
699 }
700
701 // To set vars in float type to avoid non-numeric warnings
702 $pu_ht = (float) price2num($pu_ht);
703 $remise_percent = (float) price2num($remise_percent);
704
705 $price_min = (float) price2num((float) $price_min);
706 if ($usercanproductignorepricemin && (!empty($price_min) && ($pu_ht * (1 - $remise_percent / 100) < $price_min))) {
707 $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
708 setEventMessages($mesg, null, 'errors');
709 } else {
710 // Insert line
711 $result = $object->addline($idprod, (string) $ref_fournisseur, $label, $desc, $pu_ht, $pu_ttc, (float) $qty, $remise_percent, (string) $tva_tx, $localtax1_tx, $localtax2_tx, $price_base_type, $type, $date_start_fill, $date_end_fill, $info_bits, $special_code, -1, $fk_unit);
712
713 if ($result > 0) {
714 $object->fetch($object->id); // Reload lines
715
716 unset($_POST['prod_entry_mode']);
717 unset($_POST['qty']);
718 unset($_POST['type']);
719 unset($_POST['remise_percent']);
720 unset($_POST['price_ht']);
721 unset($_POST['multicurrency_price_ht']);
722 unset($_POST['price_ttc']);
723 unset($_POST['tva_tx']);
724 unset($_POST['product_ref']);
725 unset($_POST['product_label']);
726 unset($_POST['product_desc']);
727 unset($_POST['fournprice']);
728 unset($_POST['buying_price']);
729 unset($_POST['np_marginRate']);
730 unset($_POST['np_markRate']);
731 unset($_POST['dp_desc']);
732 unset($_POST['idprod']);
733 unset($_POST['units']);
734 unset($_POST['date_starthour']);
735 unset($_POST['date_startmin']);
736 unset($_POST['date_startsec']);
737 unset($_POST['date_startday']);
738 unset($_POST['date_startmonth']);
739 unset($_POST['date_startyear']);
740 unset($_POST['date_endhour']);
741 unset($_POST['date_endmin']);
742 unset($_POST['date_endsec']);
743 unset($_POST['date_endday']);
744 unset($_POST['date_endmonth']);
745 unset($_POST['date_endyear']);
746 unset($_POST['date_start_fill']);
747 unset($_POST['date_end_fill']);
748 unset($_POST['situations']);
749 unset($_POST['progress']);
750 unset($_POST['fourn_ref']);
751 } else {
752 setEventMessages($object->error, $object->errors, 'errors');
753 }
754
755 $action = '';
756 }
757 }
758 } elseif ($action == 'updateline' && $permissiontoadd && ! GETPOST('cancel', 'alpha')) {
759 if (! $object->fetch($id) > 0) {
760 dol_print_error($db);
761 }
762 $object->fetch_thirdparty();
763
764 // Clean parameters
765 $date_start = '';
766 $date_end = '';
767 $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml'));
768 $ref_fourn = GETPOST('fourn_ref', 'alpha');
769 $pu_ht = price2num(GETPOST('price_ht'), '', 2);
770 $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
771 $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
772
773 $qty = (float) price2num(GETPOST('qty', 'alpha'), 'MS');
774
775 // Define info_bits
776 $info_bits = 0;
777 if (preg_match('/\*/', $vat_rate)) {
778 $info_bits |= 0x01;
779 }
780
781 // Define vat_rate
782 $vat_rate = str_replace('*', '', $vat_rate);
783 $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
784 $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
785
786 // Extrafields
787 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
788 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
789
790 $objectline = new FactureFournisseurLigneRec($db);
791 if ($objectline->fetch(GETPOSTINT('lineid'))) {
792 $objectline->array_options = $array_options;
793 $result = $objectline->insertExtraFields();
794 if ($result < 0) {
795 setEventMessages($langs->trans('Error') . $result, null, 'errors');
796 }
797 }
798
799 $position = ($objectline->rang >= 0 ? $objectline->rang : 0);
800
801 // Unset extrafield
802 if (is_array($extralabelsline)) {
803 // Get extra fields
804 foreach ($extralabelsline as $key => $value) {
805 unset($_POST["options_" . $key]);
806 }
807 }
808
809 // Define special_code for special lines
810 $special_code = GETPOSTINT('special_code');
811 if (! GETPOST('qty', 'alpha')) {
812 $special_code = 3;
813 }
814
815 $remise_percent = price2num(GETPOST('remise_percent'), '', 2) ?: 0;
816
817 // Check minimum price
818 $productid = GETPOSTINT('productid');
819 if (!empty($productid)) {
820 $product = new Product($db);
821 $product->fetch($productid);
822
823 $type = $product->type;
824
825 $price_min = $product->price_min;
826 if (getDolGlobalString('PRODUIT_MULTIPRICES') && !empty($object->thirdparty->price_level)) {
827 $price_min = $product->multiprices_min[$object->thirdparty->price_level];
828 }
829
830 $label = $product->label;
831
832 // Check price is not lower than minimum (check is done only for standard or replacement invoices)
833 if (((getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight("produit", "ignore_price_min_advance")) || !getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) && $price_min && ((float) price2num($pu_ht) * (1 - (float) $remise_percent / 100) < (float) price2num($price_min))) {
834 setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency)), null, 'errors');
835 $error++;
836 }
837 } else {
838 $type = GETPOSTINT('type');
839 $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
840
841 // Check parameters
842 if (GETPOSTINT('type') < 0) {
843 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
844 $error++;
845 }
846 }
847 if ($qty < 0) {
848 $langs->load("errors");
849 setEventMessages($langs->trans('ErrorQtyForSupplierInvoiceCantBeNegative'), null, 'errors');
850 $error++;
851 }
852
853 $date_start_fill = GETPOSTINT('date_start_fill');
854 $date_end_fill = GETPOSTINT('date_end_fill');
855
856 // Update line
857 if (! $error) {
858 $result = $object->updateline(GETPOSTINT('lineid'), GETPOSTINT('productid'), $ref_fourn, $label, $description, (float) $pu_ht, (float) $qty, (float) $remise_percent, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $type, $date_start_fill, $date_end_fill, $info_bits, $special_code, -1);
859 if ($result >= 0) {
860 $object->fetch($object->id); // Reload lines
861
862 unset($_POST['qty']);
863 unset($_POST['type']);
864 unset($_POST['productid']);
865 unset($_POST['remise_percent']);
866 unset($_POST['price_ht']);
867 unset($_POST['multicurrency_price_ht']);
868 unset($_POST['price_ttc']);
869 unset($_POST['tva_tx']);
870 unset($_POST['product_ref']);
871 unset($_POST['product_label']);
872 unset($_POST['product_desc']);
873 unset($_POST['fournprice']);
874 unset($_POST['buying_price']);
875 unset($_POST['np_marginRate']);
876 unset($_POST['np_markRate']);
877 unset($_POST['dp_desc']);
878 unset($_POST['idprod']);
879 unset($_POST['units']);
880 unset($_POST['date_starthour']);
881 unset($_POST['date_startmin']);
882 unset($_POST['date_startsec']);
883 unset($_POST['date_startday']);
884 unset($_POST['date_startmonth']);
885 unset($_POST['date_startyear']);
886 unset($_POST['date_endhour']);
887 unset($_POST['date_endmin']);
888 unset($_POST['date_endsec']);
889 unset($_POST['date_endday']);
890 unset($_POST['date_endmonth']);
891 unset($_POST['date_endyear']);
892 unset($_POST['situations']);
893 unset($_POST['progress']);
894 unset($_POST['fourn_ref']);
895 } else {
896 setEventMessages($object->error, $object->errors, 'errors');
897 }
898 }
899 }
900}
901
902
903/*
904 * View
905 */
906
907$title = $langs->trans("RepeatableSupplierInvoice");
908$help_url = '';
909llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-fourn-facture page-card-rec');
910
911$form = new Form($db);
912$formother = new FormOther($db);
913if (isModEnabled('project')) {
914 $formproject = new FormProjets($db);
915} else {
916 $formproject = null;
917}
918$companystatic = new Societe($db);
919$invoicerectmp = new FactureFournisseurRec($db);
920
921$now = dol_now();
922$nowlasthour = dol_get_last_hour($now);
923
924// Create mode
925if ($action == 'create') {
926 print load_fiche_titre($langs->trans("CreateRepeatableInvoice"), '', 'bill');
927
928 $object = new FactureFournisseur($db); // Source invoice
929 $product_static = new Product($db);
930
931 if ($object->fetch($id, $ref) > 0) {
932 $result = $object->fetch_lines();
933
934 print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
935 print '<input type="hidden" name="token" value="' . newToken() . '">';
936 print '<input type="hidden" name="action" value="add">';
937 print '<input type="hidden" name="facid" value="' . $object->id . '">';
938
939 print dol_get_fiche_head([], '', '', 0);
940
941 $rowspan = 4;
942 if (isModEnabled('project')) {
943 $rowspan++;
944 }
945 if ($object->fk_account > 0) {
946 $rowspan++;
947 }
948
949 print '<table class="border centpercent">';
950
951 $object->fetch_thirdparty();
952
953 // Title
954 print '<tr><td class="titlefieldcreate fieldrequired">' . $langs->trans("Title") . '</td><td>';
955 print '<input class="flat quatrevingtpercent" type="text" name="title" value="' . dol_escape_htmltag(GETPOST("title", 'alphanohtml')) . '" autofocus>';
956 print '</td></tr>';
957
958 // Ref supplier
959 print '<tr><td class="titlefieldcreate fieldrequired">' . $langs->trans("RefSupplier") . '</td><td>';
960 print '<input class="flat maxwidth500" type="text" name="ref_supplier" value="' . $object->ref_supplier . '">';
961 print '</td></tr>';
962
963 // Third party
964 print '<tr><td class="titlefieldcreate">' . $langs->trans("Supplier") . '</td><td>' . $object->thirdparty->getNomUrl(1, 'supplier') . '</td>';
965 print '</tr>';
966
967 // Invoice subtype
968 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED')) {
969 print "<tr><td>".$langs->trans("InvoiceSubtype")."</td><td>";
970 print $form->getSelectInvoiceSubtype(GETPOSTISSET('subtype') ? GETPOST('subtype') : $object->subtype, 'subtype', 0, 0, '');
971 print "</td></tr>";
972 }
973
974 $note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $object->note_public;
975 $note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $object->note_private;
976
977 // Help for substitution key
978 $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object);
979
980 $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($object->date, -1, 'm'), '%m') . ')';
981 $substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date($object->date, '%m') . ')';
982 $substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%m') . ')';
983 $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($object->date, -1, 'm'), '%B') . ')';
984 $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date($object->date, '%B') . ')';
985 $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B') . ')';
986 $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("PreviousYearOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($object->date, -1, 'y'), '%Y') . ')';
987 $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("YearOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date($object->date, '%Y') . ')';
988 $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($object->date, 1, 'y'), '%Y') . ')';
989 // Only on template invoices
990 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen");
991 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen");
992 $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $langs->trans("Count");
993 $substitutionarray['__INVOICE_COUNTER_MAX__'] = $langs->trans("MaxPeriodNumber");
994
995 $htmltext = '<i>' . $langs->trans("FollowingConstantsWillBeSubstituted") . ':<br>';
996 foreach ($substitutionarray as $key => $val) {
997 $htmltext .= $key . ' = ' . $langs->trans($val) . '<br>';
998 }
999 $htmltext .= '</i>';
1000
1001 // Label
1002 print '<tr><td class="titlefieldcreate">' . $langs->trans("Label") . '</td><td>';
1003 print '<input class="flat quatrevingtpercent" type="text" name="label" value="' . $object->label . '">';
1004 print '</td></tr>';
1005
1006 // Author
1007 print "<tr><td>" . $langs->trans("Author") . "</td><td>" . $user->getFullName($langs) . "</td></tr>";
1008
1009 // Payment term
1010 print "<tr><td>" . $langs->trans("PaymentConditions") . "</td><td>";
1011 print $form->getSelectConditionsPaiements(GETPOSTISSET('cond_reglement_id') ? GETPOST('cond_reglement_id', 'int') : $object->cond_reglement_id, 'cond_reglement_id', -1, 0, 0, '');
1012 print "</td></tr>";
1013
1014 // Payment mode
1015 print "<tr><td>" . $langs->trans("PaymentMode") . "</td><td>";
1016 print img_picto('', 'payment', 'class="pictofixedwidth"');
1017 print $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ? GETPOST('mode_reglement_id', 'int') : $object->mode_reglement_id, 'mode_reglement_id', '', 0, 1, 0, 0, 1, '', 1);
1018 print "</td></tr>";
1019
1020 // Project
1021 if (isModEnabled('project') && $formproject !== null && is_object($object->thirdparty) && $object->thirdparty->id > 0) {
1022 $projectid = GETPOST('projectid') ? GETPOST('projectid') : $object->fk_project;
1023 $langs->load('projects');
1024 print '<tr><td>' . $langs->trans('Project') . '</td><td>';
1025 $numprojet = $formproject->select_projects((!getDolGlobalString('PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS') ? $object->thirdparty->id : -1), $projectid, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, '');
1026 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>';
1027 print '</td></tr>';
1028 }
1029
1030 // Bank account
1031 if ($object->fk_account > 0) {
1032 print "<tr><td>" . $langs->trans('BankAccount') . "</td><td>";
1033 $form->formSelectAccount($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->fk_account, 'none');
1034 print "</td></tr>";
1035 }
1036
1037 // Extrafields
1038 $draft = new FactureFournisseur($db);
1039 $draft->fetch(GETPOSTINT('facid'));
1040
1041 $extralabels = $extrafields->fetch_name_optionals_label($draft->table_element);
1042 if ($draft->fetch_optionals() > 0) {
1043 $object->array_options = array_merge($object->array_options, $draft->array_options);
1044 }
1045
1046 print $object->showOptionals($extrafields, 'create', $parameters);
1047
1048 // Model pdf
1049 print "<tr><td>" . $langs->trans('Model') . "</td><td>";
1050 include_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_invoice/modules_facturefournisseur.php';
1052 print $form->selectarray('modelpdf', $list, getDolGlobalString('INVOICE_SUPPLIER_ADDON_PDF'));
1053 print "</td></tr>";
1054
1055 // Public note
1056 print '<tr>';
1057 print '<td class="tdtop">';
1058 print $form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic');
1059 print '</td>';
1060 print '<td>';
1061 $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', false, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PUBLIC') ? 0 : 1, ROWS_3, '90%');
1062 print $doleditor->Create(1);
1063
1064 // Private note
1065 if (empty($user->socid)) {
1066 print '<tr>';
1067 print '<td class="tdtop">';
1068 print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate');
1069 print '</td>';
1070 print '<td>';
1071 $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', false, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PRIVATE') ? 0 : 1, ROWS_3, '90%');
1072 print $doleditor->Create(1);
1073 print '</td></tr>';
1074 }
1075
1076 print "</table>";
1077
1078 print dol_get_fiche_end();
1079
1080 // Autogeneration
1081 $title = $langs->trans("Recurrence");
1082 print load_fiche_titre(img_picto('', 'recurring', 'class="pictofixedwidth"') . $title, '', '');
1083
1084 print '<span class="opacitymedium">'.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')).'</span><br><br>';
1085
1086 print dol_get_fiche_head([], '', '', 0);
1087
1088 print '<table class="border centpercent">';
1089
1090 // Frequency + unit
1091 print '<tr><td class="titlefieldcreate">' . $form->textwithpicto($langs->trans("Frequency"), $langs->transnoentitiesnoconv('toolTipFrequency')) . "</td><td>";
1092 print "<input type='text' class='width50' name='frequency' value='" . GETPOSTINT('frequency') . "' 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'));
1093 print "</td></tr>";
1094
1095 // Date next run
1096 print "<tr><td>" . $langs->trans('NextDateToExecution') . "</td><td>";
1097 $date_next_execution = isset($date_next_execution) ? $date_next_execution : (GETPOSTINT('remonth') ? dol_mktime(12, 0, 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear')) : -1);
1098 print $form->selectDate($date_next_execution, '', 1, 1, 0, "add", 1, 1);
1099 print "</td></tr>";
1100
1101 // Number max of generation
1102 print "<tr><td>" . $langs->trans("MaxPeriodNumber") . "</td><td>";
1103 print '<input type="text" class="width50" name="nb_gen_max" value="' . GETPOSTINT('nb_gen_max') . '">';
1104 print "</td></tr>";
1105
1106 // Auto validate the invoice
1107 print "<tr><td>" . $langs->trans("StatusOfAutoGeneratedInvoices") . "</td><td>";
1108 $select = array('0' => $langs->trans('BillStatusDraft'), '1' => $langs->trans('BillStatusValidated'));
1109 print $form->selectarray('auto_validate', $select, GETPOSTINT('auto_validate'));
1110 print "</td></tr>";
1111
1112 // Auto generate document
1113 if (getDolGlobalString('INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION')) {
1114 print "<tr><td>" . $langs->trans("StatusOfGeneratedDocuments") . "</td><td>";
1115 $select = array('0' => $langs->trans('DoNotGenerateDoc'), '1' => $langs->trans('AutoGenerateDoc'));
1116 print $form->selectarray('generate_pdf', $select, GETPOSTINT('generate_pdf'));
1117 print "</td></tr>";
1118 } else {
1119 print '<input type="hidden" name="generate_pdf" value="1">';
1120 }
1121
1122 print "</table>";
1123
1124 print dol_get_fiche_end();
1125
1126 $title = $langs->trans("ProductsAndServices");
1127 if (!isModEnabled("service")) {
1128 $title = $langs->trans("Products");
1129 } elseif (!isModEnabled("product")) {
1130 $title = $langs->trans("Services");
1131 }
1132
1133 print load_fiche_titre($title, '', '');
1134
1135 /*
1136 * Invoice lines
1137 */
1138 print '<div class="div-table-responsive-no-min">';
1139 print '<table id="tablelines" class="noborder noshadow" width="100%">';
1140 // Show object lines
1141 if (!empty($object->lines)) {
1142 $disableedit = 1;
1143 $disablemove = 1;
1144 $disableremove = 1;
1145 $object->printObjectLines('', $object->thirdparty, $mysoc, $lineid, 0); // No date selector for template invoice
1146 }
1147
1148 print "</table>\n";
1149 print '<div>';
1150 print '</td></tr>';
1151 print "</table>\n";
1152
1153 print $form->buttonsSaveCancel("Create");
1154
1155 print "</form>\n";
1156 } else {
1157 dol_print_error(null, "Error, no invoice " . $object->id);
1158 }
1159} else {
1160 // View mode
1161 if ($object->id > 0) {
1162 $object->fetch($object->id);
1163 $object->fetch_thirdparty();
1164
1165 $formconfirm = '';
1166
1167 // Confirmation of deletion of product line
1168 if ($action == 'ask_deleteline') {
1169 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
1170 }
1171
1172 // Confirm delete of repeatable invoice
1173 if ($action == 'ask_deleteinvoice') {
1174 $formconfirm = $form->formconfirm(dolBuildUrl($_SERVER["PHP_SELF"], ['id' => $object->id]), $langs->trans('DeleteRepeatableInvoice'), $langs->trans('ConfirmDeleteRepeatableInvoice'), 'confirm_deleteinvoice', '', 'no', 1);
1175 }
1176
1177 print $formconfirm;
1178
1179 $author = new User($db);
1180 $author->fetch($object->user_creation_id);
1181
1182 $head = supplier_invoice_rec_prepare_head($object);
1183
1184 print dol_get_fiche_head($head, 'card', $langs->trans('RepeatableInvoice'), -1, $object->picto); // Add a div
1185
1186 // Recurring invoice content
1187
1188 $linkback = '<a href="' . DOL_URL_ROOT . '/fourn/facture/list-rec.php?restore_lastsearch_values=1' . (!empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans('BackToList') . '</a>';
1189
1190 $morehtmlref = '';
1191 if ($action != 'edittitle') {
1192 $morehtmlref .= $form->editfieldkey($object->title, 'title', $object->title, $object, (int) $usercancreate, '', '', 0, 2);
1193 } else {
1194 $morehtmlref .= $form->editfieldval('', 'title', $object->title, $object, $usercancreate, 'string');
1195 }
1196 $morehtmlref .= '<div class="refidno">';
1197 //Ref supplier
1198 $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, (int) $usercancreate, 'string', '', 0, 1);
1199 $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1);
1200 // Thirdparty
1201 $morehtmlref .= '<br>' . $langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
1202
1203 // Project
1204 if (isModEnabled('project') && $formproject !== null) {
1205 $langs->load('projects');
1206 $morehtmlref .= '<br>' . $langs->trans('Project') . ' ';
1207 if ($usercancreate) {
1208 if ($action != 'classify') {
1209 $morehtmlref .= '<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
1210 }
1211 if ($action == 'classify') {
1212 $morehtmlref .= '<form method="post" action="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '">';
1213 $morehtmlref .= '<input type="hidden" name="action" value="classin">';
1214 $morehtmlref .= '<input type="hidden" name="token" value="' . newToken() . '">';
1215 $morehtmlref .= $formproject->select_projects((!getDolGlobalString('PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS') ? $object->socid : -1), (string) $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1);
1216 $morehtmlref .= '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
1217 $morehtmlref .= '</form>';
1218 } else {
1219 $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, (getDolGlobalString('PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS') ? $object->socid : -1), $object->fk_project, 'none', 0, 0, 0, 1, '', 'maxwidth300');
1220 }
1221 } else {
1222 if (!empty($object->fk_project)) {
1223 $project = new Project($db);
1224 $project->fetch($object->fk_project);
1225 $morehtmlref .= ' : ' . $project->getNomUrl(1);
1226 if ($project->title) {
1227 $morehtmlref .= ' - ' . $project->title;
1228 }
1229 } else {
1230 $morehtmlref .= '';
1231 }
1232 }
1233 }
1234 $morehtmlref .= '</div>';
1235
1236 $morehtmlstatus = '';
1237
1238 dol_banner_tab($object, 'ref', $linkback, 1, 'title', 'none', $morehtmlref, '', 0, '', $morehtmlstatus);
1239
1240 print '<div class="fichecenter">';
1241 print '<div class="fichehalfleft">';
1242 print '<div class="underbanner clearboth"></div>';
1243
1244 print '<table class="border centpercent tableforfield">';
1245
1246 // Invoice subtype
1247 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED')) {
1248 print "<tr><td>".$langs->trans("InvoiceSubtype")."</td><td>";
1249 print $object->getSubtypeLabel('facture_fourn_rec');
1250 print "</td></tr>";
1251 }
1252
1253 // Author
1254 print '<tr><td class="titlefield">' . $langs->trans('Author') . '</td><td>';
1255 print $author->getNomUrl(-1);
1256 print "</td></tr>";
1257
1258 // Label
1259 print '<tr>';
1260 print '<td>' . $form->editfieldkey("Label", 'label', $object->label, $object, (int) $usercancreate) . '</td>';
1261 print '<td>' . $form->editfieldval("Label", 'label', $object->label, $object, $usercancreate) . '</td>';
1262 print '</tr>';
1263
1264 // Payment term
1265 print '<tr><td>';
1266 print '<table class="nobordernopadding centpercent"><tr><td>';
1267 print $langs->trans('PaymentConditionsShort');
1268 print '</td>';
1269 if ($action != 'editconditions' && $usercancreate) {
1270 print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editconditions&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetConditions'), 1) . '</a></td>';
1271 }
1272 print '</tr></table>';
1273 print '</td><td>';
1274 if ($action == 'editconditions') {
1275 $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, (string) $object->cond_reglement_id, 'cond_reglement_id');
1276 } else {
1277 $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, (string) $object->cond_reglement_id, 'none');
1278 }
1279
1280 print '</td></tr>';
1281
1282 // Payment mode
1283 print '<tr><td>';
1284 print '<table class="nobordernopadding" width="100%"><tr><td>';
1285 print $langs->trans('PaymentMode');
1286 print '</td>';
1287 if ($action != 'editmode' && $usercancreate) {
1288 print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editmode&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetMode'), 1) . '</a></td>';
1289 }
1290 print '</tr></table>';
1291 print '</td><td>';
1292 if ($action == 'editmode') {
1293 $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, (string) $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
1294 } else {
1295 $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, (string) $object->mode_reglement_id, 'none');
1296 }
1297 print '</td></tr>';
1298
1299 // Bank Account
1300 print '<tr><td class="nowrap">';
1301 print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
1302 print $langs->trans('BankAccount');
1303 print '<td>';
1304 if ($action != 'editbankaccount' && $usercancreate && $object->status == FactureFournisseurRec::STATUS_NOTSUSPENDED) {
1305 print '<td class="right"><a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=editbankaccount&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->trans('SetBankAccount'), 1) . '</a></td>';
1306 }
1307 print '</tr></table>';
1308 print '</td><td>';
1309 if ($action == 'editbankaccount') {
1310 $form->formSelectAccount($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->fk_account, 'fk_account', 1);
1311 } else {
1312 $form->formSelectAccount($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->fk_account, 'none');
1313 }
1314 print "</td>";
1315 print '</tr>';
1316
1317 // Extrafields
1318 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
1319
1320 // Model pdf
1321 print '<tr><td class="nowrap">';
1322 print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
1323 print $langs->trans('Model');
1324 print '<td>';
1325 if ($action != 'editmodelpdf' && $usercancreate && $object->status == FactureFournisseurRec::STATUS_NOTSUSPENDED) {
1326 print '<td class="right"><a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=editmodelpdf&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->trans('SetModel'), 1) . '</a></td>';
1327 }
1328 print '</tr></table>';
1329 print '</td><td>';
1330 if ($action == 'editmodelpdf') {
1331 include_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_invoice/modules_facturefournisseur.php';
1332 $list = array();
1334 foreach ($models as $k => $model) {
1335 $list[] = str_replace(':', '|', $k) . ':' . $model;
1336 }
1337 $select = 'select;' . implode(',', $list);
1338 //TODO : Droits
1339 print $form->editfieldval($langs->trans('Model'), 'modelpdf', $object->model_pdf, $object, $usercancreate, $select);
1340 } else {
1341 print $object->model_pdf;
1342 }
1343 print "</td>";
1344 print '</tr>';
1345
1346 // Other attributes
1347 $cols = 2;
1348
1349 print '</table>';
1350
1351 print '</div>';
1352 print '<div class="fichehalfright">';
1353 print '<div class="underbanner clearboth"></div>';
1354
1355 /*
1356 * Recurrence
1357 */
1358 $title = $langs->trans("Recurrence");
1359 //print load_fiche_titre($title, '', 'calendar');
1360
1361 print '<table class="border centpercent tableforfield">';
1362
1363 include DOL_DOCUMENT_ROOT.'/core/tpl/object_currency_amount.tpl.php';
1364
1365 // Amount (excl. tax)
1366 print '<tr><td>' . $langs->trans('AmountHT') . '</td>';
1367 print '<td>' . price($object->total_ht, 0, $langs, 1, -1, -1, $conf->currency) . '</td>';
1368 print '</tr>';
1369
1370 print '<tr><td>' . $langs->trans("AmountVAT") . '</td><td>' . price($object->total_tva, 0, $langs, 1, -1, -1, $conf->currency) . '</td>';
1371 print '</tr>';
1372
1373 // Amount Local Taxes
1374 if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) { // Localtax1
1375 print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
1376 print '<td class="nowrap">' . price($object->total_localtax1, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
1377 }
1378 if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) { // Localtax2
1379 print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
1380 print '<td class=nowrap">' . price($object->total_localtax2, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
1381 }
1382
1383 print '<tr><td>' . $langs->trans("AmountTTC") . '</td><td colspan="3">' . price($object->total_ttc, 0, $langs, 1, -1, -1, $conf->currency) . '</td>';
1384 print '</tr>';
1385
1386
1387 print '<tr class="liste_titre"><td colspan="2" class="liste_titre">' . img_picto('', 'recurring', 'class="pictofixedwidth"') . $title . '</td></tr>';
1388
1389 // if "frequency" is empty or = 0, the recurrence is disabled
1390 print '<tr><td style="width: 50%">';
1391 print '<table class="nobordernopadding" width="100%"><tr><td>';
1392 print $langs->trans('Frequency');
1393 print '</td>';
1394 if ($action != 'editfrequency' && $usercancreate) {
1395 print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editfrequency&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('Edit'), 1) . '</a></td>';
1396 }
1397 print '</tr></table>';
1398 print '</td><td>';
1399 if ($action == 'editfrequency') {
1400 print '<form method="post" action="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '">';
1401 print '<input type="hidden" name="action" value="setfrequency">';
1402 print '<input type="hidden" name="token" value="' . newToken() . '">';
1403 print '<table class="nobordernopadding">';
1404 print '<tr><td>';
1405 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'));
1406 print '</td>';
1407 print '<td class="left"><input type="submit" class="button button-edit" value="' . $langs->trans("Modify") . '"></td>';
1408 print '</tr></table></form>';
1409 } else {
1410 if ($object->frequency > 0) {
1411 print $langs->trans('FrequencyPer_' . $object->unit_frequency, $object->frequency);
1412 } else {
1413 print '<span class="opacitymedium">'.$langs->trans("NotARecurringInvoiceTemplate").'</span>';
1414 }
1415 }
1416 print '</td></tr>';
1417
1418 if ($object->frequency > 0) {
1419 // Date when (next invoice generation)
1420 print '<tr><td>';
1421 if ($action == 'date_when' || $object->frequency > 0) {
1422 print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', (string) $object->date_when, $object, (int) $usercancreate, 'day');
1423 } else {
1424 print $langs->trans("NextDateToExecution");
1425 }
1426 print '</td><td>';
1427 if ($action == 'date_when' || $object->frequency > 0) {
1428 print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $usercancreate, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached');
1429 }
1430 //var_dump(dol_print_date($object->date_when+60, 'dayhour').' - '.dol_print_date($now, 'dayhour'));
1431 if (! $object->isMaxNbGenReached()) {
1432 if (! $object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) {
1433 print img_warning($langs->trans("Late"));
1434 }
1435 } else {
1436 print img_info($langs->trans("MaxNumberOfGenerationReached"));
1437 }
1438 print '</td>';
1439 print '</tr>';
1440
1441 // Max period / Rest period
1442 print '<tr><td>';
1443 if ($action == 'nb_gen_max' || $object->frequency > 0) {
1444 print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', (string) $object->nb_gen_max, $object, (int) $usercancreate);
1445 } else {
1446 print $langs->trans("MaxPeriodNumber");
1447 }
1448 print '</td><td>';
1449 if ($action == 'nb_gen_max' || $object->frequency > 0) {
1450 print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max ? $object->nb_gen_max : '', $object, $usercancreate);
1451 } else {
1452 print '';
1453 }
1454 print '</td>';
1455 print '</tr>';
1456
1457 // Status of generated invoices
1458 print '<tr><td>';
1459 if ($action == 'auto_validate' || $object->frequency > 0) {
1460 print $form->editfieldkey($langs->trans("StatusOfAutoGeneratedInvoices"), 'auto_validate', (string) $object->auto_validate, $object, (int) $usercancreate);
1461 } else {
1462 print $langs->trans("StatusOfAutoGeneratedInvoices");
1463 }
1464 print '</td><td>';
1465 $select = 'select;0:' . $langs->trans('BillStatusDraft') . ',1:' . $langs->trans('BillStatusValidated');
1466 if ($action == 'auto_validate' || $object->frequency > 0) {
1467 print $form->editfieldval($langs->trans("StatusOfAutoGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $usercancreate, $select);
1468 }
1469 print '</td>';
1470 // Auto generate documents
1471 if (getDolGlobalString('INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION')) {
1472 print '<tr>';
1473 print '<td>';
1474 if ($action == 'generate_pdf' || $object->frequency > 0) {
1475 print $form->editfieldkey($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', (string) $object->generate_pdf, $object, (int) $usercancreate);
1476 } else {
1477 print $langs->trans("StatusOfGeneratedDocuments");
1478 }
1479 print '</td>';
1480 print '<td>';
1481 $select = 'select;0:' . $langs->trans('DoNotGenerateDoc') . ',1:' . $langs->trans('AutogenerateDoc');
1482 if ($action == 'generate_pdf' || $object->frequency > 0) {
1483 print $form->editfieldval($langs->trans("StatusOfGeneratedDocuments"), 'generate_pdf', $object->generate_pdf, $object, $usercancreate, $select);
1484 }
1485 print '</td>';
1486 print '</tr>';
1487 } else {
1488 print '<input type="hidden" name="generate_pdf" value="1">';
1489 }
1490 }
1491
1492 print '</table>';
1493
1494 // Frequencry/Recurring section
1495 if ($object->frequency > 0) {
1496 print '<br>';
1497
1498 if (!isModEnabled('cron')) {
1499 print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name")));
1500 }
1501
1502 print '<div class="underbanner clearboth"></div>';
1503 print '<table class="border centpercent tableforfield">';
1504
1505 // Nb of generation already done
1506 print '<tr><td style="width: 50%">' . $langs->trans("NbOfGenerationDone") . '</td>';
1507 print '<td>';
1508 print $object->nb_gen_done ? $object->nb_gen_done : '0';
1509 print '</td>';
1510 print '</tr>';
1511
1512 // Date last
1513 print '<tr><td>';
1514 print $langs->trans("DateLastGeneration");
1515 print '</td><td>';
1516 print dol_print_date($object->date_last_gen, 'dayhour');
1517 print '</td>';
1518 print '</tr>';
1519
1520 print '</table>';
1521
1522 print '<br>';
1523 }
1524
1525 print '</div>';
1526 print '</div>';
1527
1528 print '<div class="clearboth"></div><br>';
1529
1530 // Lines
1531 print ' <form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . (($action != 'editline') ? '#add' : '#line_' . GETPOSTINT('lineid')) . '" method="POST">
1532 <input type="hidden" name="token" value="' . newToken() . '">
1533 <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline') . '">
1534 <input type="hidden" name="mode" value="">
1535 <input type="hidden" name="id" value="' . $object->id . '">
1536 ';
1537
1538 if (!empty($conf->use_javascript_ajax) && $object->status == FactureFournisseurRec::STATUS_NOTSUSPENDED) {
1539 include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
1540 }
1541
1542 print '<div class="div-table-responsive-no-min">';
1543 print '<table id="tablelines" class="noborder noshadow" width="100%">';
1544 $object->fetch_lines();
1545 // Show object lines
1546 if (!empty($object->lines)) {
1547 global $canchangeproduct;
1548 $canchangeproduct = 0;
1549
1550 $object->statut = $object->suspended;
1551 $object->status = $object->suspended;
1552 $object->printObjectLines($action, $object->thirdparty, $mysoc, $lineid, 0); // No date selector for template invoice
1553 }
1554
1555 // Form to add new line
1556 //TODO : Droits
1557 if ($object->status == FactureFournisseurRec::STATUS_NOTSUSPENDED && $usercancreate && $action != 'valid' && $action != 'editline') {
1558 if ($action != 'editline') {
1559 // Add free products/services
1560
1561 $parameters = array();
1562 $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1563 if ($reshook < 0) {
1564 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1565 }
1566 if (empty($reshook)) {
1567 global $senderissupplier;
1568 }
1569 $senderissupplier = 2;
1570 $object->formAddObjectLine(0, $object->thirdparty, $mysoc); // No date selector for template invoice
1571 }
1572 }
1573
1574 print "</table>\n";
1575 print '</div>';
1576
1577 print "</form>\n";
1578
1579 print dol_get_fiche_end();
1580
1581 /*
1582 * Action bar
1583 */
1584 print '<div class="tabsAction">';
1585
1586 if (empty($object->suspended)) {
1587 if ($usercancreate) {
1588 if (!empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max)) {
1589 print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="' . dol_escape_htmltag($langs->trans("MaxGenerationReached")) . '">' . $langs->trans("CreateBill") . '</a></div>';
1590 } else {
1591 if (empty($object->frequency) || $object->date_when <= $nowlasthour) {
1592 print '<div class="inline-block divButAction"><a class="butAction" href="' . DOL_URL_ROOT . '/fourn/facture/card.php?action=create&socid=' . $object->thirdparty->id . '&fac_rec=' . $object->id . '">' . $langs->trans("CreateBill") . '</a></div>';
1593 } else {
1594 print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="' . dol_escape_htmltag($langs->trans("DateIsNotEnough")) . '">' . $langs->trans("CreateBill") . '</a></div>';
1595 }
1596 }
1597 } else {
1598 print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">' . $langs->trans("CreateBill") . '</a></div>';
1599 }
1600 }
1601
1602 if ($usercancreate) {
1603 if (empty($object->suspended)) {
1604 print '<div class="inline-block divButAction"><a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?action=disable&id=' . $object->id . '&token=' . newToken() . '">' . $langs->trans("Disable") . '</a></div>';
1605 } else {
1606 print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?action=enable&id=' . $object->id . '&token=' . newToken() . '">' . $langs->trans("Enable") . '</a></div>';
1607 }
1608 }
1609
1610 // Delete
1611 print dolGetButtonAction($langs->trans("Delete"), $langs->trans("Delete"), 'delete', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=ask_deleteinvoice&token='.newToken(), 'delete', ($user->hasRight("fournisseur", "facture", "supprimer") || $user->hasRight("supplier_invoice", "supprimer")), array('attr' => array('class' => 'reposition')))."\n";
1612
1613 print '</div>';
1614
1615 print '<div class="fichecenter"><div class="fichehalfleft">';
1616 print '<a name="builddoc"></a>'; // ancre
1617
1618 // Show links to link elements
1619 $tmparray = $form->showLinkToObjectBlock($object, array(), array('invoice'), 1);
1620 $linktoelem = $tmparray['linktoelem'];
1621 $htmltoenteralink = $tmparray['htmltoenteralink'];
1622 print $htmltoenteralink;
1623
1624 $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
1625
1626 print '</div></div>';
1627 }
1628}
1629
1630// End of page
1631llxFooter();
1632$db->close();
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage a WYSIWYG editor.
Class to manage standard extra fields.
Class to manage suppliers invoices.
Class to manage supplier invoice lines of templates.
Class to manage invoice templates.
Class to manage generation of HTML components Only common components must be here.
Class to help generate other html components Only common components are here.
Class to manage building of HTML components.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
Class to manage predefined suppliers products.
Class to manage products or services.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
global $mysoc
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition date.lib.php:672
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
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.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
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...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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) VAT...
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
supplier_invoice_rec_prepare_head($object)
Return array head with list of tabs to view object information.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.