dolibarr 24.0.3
card.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
5 * Copyright (C) 2005 Marc Barilley <marc@ocebo.fr>
6 * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
7 * Copyright (C) 2010-2023 Juanjo Menent <jmenent@simnandez.es>
8 * Copyright (C) 2013-2022 Philippe Grand <philippe.grand@atoo-net.com>
9 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
10 * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
11 * Copyright (C) 2016-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
12 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
13 * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
14 * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
15 * Copyright (C) 2023 Nick Fragoulis
16 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
17 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
18 * Copyright (C) 2026 Lionel Vessiller <lvessiller@open-dsi.fr>
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <https://www.gnu.org/licenses/>.
32 */
33
40// Load Dolibarr environment
41require '../../main.inc.php';
50require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
51require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
52require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
53require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
54require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
55require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture-rec.class.php';
56require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
57require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
58require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
59require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
60require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
61require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
62if (isModEnabled("product")) {
63 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
64 require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
65}
66if (isModEnabled('project')) {
67 require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
68 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
69}
70
71if (isModEnabled('variants')) {
72 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
73}
74if (isModEnabled('accounting')) {
75 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
76}
77
78$langs->loadLangs(array('bills', 'compta', 'suppliers', 'companies', 'products', 'banks', 'admin'));
79if (isModEnabled('incoterm')) {
80 $langs->load('incoterm');
81}
82
83$id = (GETPOSTINT('facid') ? GETPOSTINT('facid') : GETPOSTINT('id'));
84
85$action = GETPOST('action', 'aZ09');
86$confirm = GETPOST("confirm");
87$ref = GETPOST('ref', 'alpha');
88$cancel = GETPOST('cancel', 'alpha');
89$backtopage = GETPOST('backtopage', 'alpha');
90$backtopageforcancel = '';
91
92$lineid = GETPOSTINT('lineid');
93$projectid = GETPOSTINT('projectid');
94$origin = GETPOST('origin', 'alpha');
95$originid = GETPOSTINT('originid');
96$fac_recid = GETPOSTINT('fac_rec');
97$rank = (GETPOSTINT('rank') > 0) ? GETPOSTINT('rank') : -1;
98
99$date_pointoftax = dol_mktime(12, 0, 0, GETPOSTINT('date_pointoftaxmonth'), GETPOSTINT('date_pointoftaxday'), GETPOSTINT('date_pointoftaxyear'), 'tzserver');
100
101// PDF
102$hidedetails = (GETPOSTINT('hidedetails') ? GETPOSTINT('hidedetails') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0));
103$hidedesc = (GETPOSTINT('hidedesc') ? GETPOSTINT('hidedesc') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0));
104$hideref = (GETPOSTINT('hideref') ? GETPOSTINT('hideref') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0));
105
106// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
107$hookmanager->initHooks(array('invoicesuppliercard', 'globalcard'));
108
110$extrafields = new ExtraFields($db);
111
112// fetch optionals attributes and labels
113$extrafields->fetch_name_optionals_label($object->table_element);
114
115// Load object
116if ($id > 0 || !empty($ref)) {
117 $ret = $object->fetch($id, $ref);
118 if ($ret < 0) {
119 dol_print_error($db, $object->error);
120 }
121 if ($object->id > 0) {
122 $id = $object->id; // The page may be called with the ref only: the security check must be done on the object found
123 }
124 $ret = $object->fetch_thirdparty();
125 if ($ret < 0) {
126 dol_print_error($db, $object->error);
127 }
128}
129
130// Security check
131$socid = GETPOSTINT('socid');
132if (!empty($user->socid)) {
133 $socid = $user->socid;
134}
135
136$isdraft = (($object->status == FactureFournisseur::STATUS_DRAFT) ? 1 : 0);
137$result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture', 'fk_soc', 'rowid', $isdraft);
138
139// Common permissions
140$usercanread = ($user->hasRight("fournisseur", "facture", "lire") || $user->hasRight("supplier_invoice", "lire"));
141$usercancreate = ($user->hasRight("fournisseur", "facture", "creer") || $user->hasRight("supplier_invoice", "creer"));
142$usercandelete = (($user->hasRight("fournisseur", "facture", "supprimer") || $user->hasRight("supplier_invoice", "supprimer")) || ($usercancreate && $object->is_erasable() == 1));
143$usercancreatecontract = $user->hasRight("contrat", "creer");
144
145// Advanced permissions
146$usercanvalidate = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !empty($usercancreate)) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight("fournisseur", "supplier_invoice_advance", "validate")));
147$usercansend = (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || $user->hasRight("fournisseur", "supplier_invoice_advance", "send"));
148$usercancreatecreditransfer = $user->hasRight('paymentbybanktransfer', 'create');
149
150// Permissions for includes
151$permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
152$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
153$permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php
154$permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
155$permissiontodelete = $usercandelete;
156$permissiontoeditextra = $permissiontoadd;
157if (GETPOST('attribute', 'aZ09') && isset($extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')])) {
158 // For action 'update_extras', is there a specific permission set for the attribute to update
159 $permissiontoeditextra = dol_eval((string) $extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')]);
160}
161
162$error = 0;
163$classname = null;
164
165
166/*
167 * Actions
168 */
169
170$parameters = array('socid' => $socid);
171$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
172if ($reshook < 0) {
173 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
174}
175
176if (empty($reshook)) {
177 $backurlforlist = dolBuildUrl(DOL_URL_ROOT.'/fourn/facture/list.php');
178
179 if (empty($backtopage) || ($cancel && empty($id))) {
180 if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
181 if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
182 $backtopage = $backurlforlist;
183 } else {
184 $backtopage = dolBuildUrl(DOL_URL_ROOT.'/fourn/facture/card.php', ['id' => ((!empty($id) && $id > 0) ? $id : '__ID__')]);
185 }
186 }
187 }
188
189 if ($cancel) {
190 if (!empty($backtopageforcancel)) {
191 header("Location: ".$backtopageforcancel);
192 exit;
193 } elseif (!empty($backtopage)) {
194 header("Location: ".$backtopage);
195 exit;
196 }
197 $action = '';
198 }
199
200 include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be 'include', not 'include_once'
201
202 include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be 'include', not 'include_once'
203
204 include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be 'include', not 'include_once'
205
206 // Link invoice to order
207 if (GETPOST('linkedOrder') && empty($cancel) && $id > 0 && $permissiontoadd) {
208 $object->fetch($id);
209 $object->fetch_thirdparty();
210 $result = $object->add_object_linked('order_supplier', GETPOSTINT('linkedOrder'));
211 }
212
213 // Action clone object
214 if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) {
215 $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid.
216 '@phan-var-force FactureFournisseur $objectutil'; // Same object type for cloned object
217
218 if (GETPOST('newsupplierref', 'alphanohtml')) {
219 $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml');
220 }
221 $objectutil->date = dol_mktime(12, 0, 0, GETPOSTINT('newdatemonth'), GETPOSTINT('newdateday'), GETPOSTINT('newdateyear'));
222
223 $result = $objectutil->createFromClone($user, $id);
224 if ($result > 0) {
225 header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
226 exit;
227 } else {
228 $langs->load("errors");
229 setEventMessages($objectutil->error, $objectutil->errors, 'errors');
230 $action = '';
231 }
232 } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
233 $idwarehouse = GETPOST('idwarehouse');
234
235 $object->fetch($id);
236 $object->fetch_thirdparty();
237
238 $qualified_for_stock_change = 0;
239 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
240 $qualified_for_stock_change = $object->hasProductsOrServices(2);
241 } else {
242 $qualified_for_stock_change = $object->hasProductsOrServices(1);
243 }
244
245 // Check parameters
246 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $qualified_for_stock_change) {
247 $langs->load("stocks");
248 if (!$idwarehouse || $idwarehouse == -1) {
249 $error++;
250 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
251 $action = '';
252 }
253 }
254
255 if (!$error) {
256 $db->begin();
257
258 $result = $object->validate($user, '', $idwarehouse);
259 if ($result < 0) {
260 $db->rollback();
261
262 setEventMessages($object->error, $object->errors, 'errors');
263 } else {
264 $db->commit();
265
266 // Define output language
267 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
268 $outputlangs = $langs;
269 $newlang = '';
270 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
271 $newlang = GETPOST('lang_id', 'aZ09');
272 }
273 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
274 $newlang = $object->thirdparty->default_lang;
275 }
276 if (!empty($newlang)) {
277 $outputlangs = new Translate("", $conf);
278 $outputlangs->setDefaultLang($newlang);
279 }
280 $model = $object->model_pdf;
281 $ret = $object->fetch($id); // Reload to get new records
282
283 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
284 if ($result < 0) {
285 setEventMessages($object->error, $object->errors, 'errors');
286 }
287 }
288 }
289 }
290 } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $permissiontodelete) {
291 $object->fetch($id);
292 $object->fetch_thirdparty();
293
294 $isErasable = $object->is_erasable();
295
296 if ($usercandelete && $isErasable > 0) {
297 $revertstock = GETPOST('revertstock');
298
299 if ($revertstock) {
300 $idwarehouse = GETPOSTINT('idwarehouse');
301
302 $qualified_for_stock_change = 0;
303 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
304 $qualified_for_stock_change = $object->hasProductsOrServices(2);
305 } else {
306 $qualified_for_stock_change = $object->hasProductsOrServices(1);
307 }
308
309 // Check parameters
310 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $qualified_for_stock_change) {
311 $langs->load("stocks");
312 if (!$idwarehouse || $idwarehouse == -1) {
313 $error++;
314 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
315 $action = 'delete';
316 } else {
317 $result = $object->setDraft($user, $idwarehouse);
318 if ($result < 0) {
319 $error++;
320 }
321 }
322 }
323 }
324
325 if (!$error) {
326 $result = $object->delete($user);
327 if ($result > 0) {
328 header('Location: list.php?restore_lastsearch_values=1');
329 exit;
330 } else {
331 setEventMessages($object->error, $object->errors, 'errors');
332 }
333 }
334 }
335 } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
336 // Remove a product line
337 $result = $object->deleteLine($lineid);
338 if ($result > 0) {
339 // reorder lines
340 $object->line_order(true);
341 // Define output language
342 /*$outputlangs = $langs;
343 $newlang = '';
344 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id','aZ09'))
345 $newlang = GETPOST('lang_id','aZ09');
346 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang))
347 $newlang = $object->thirdparty->default_lang;
348 if (!empty($newlang)) {
349 $outputlangs = new Translate("", $conf);
350 $outputlangs->setDefaultLang($newlang);
351 }
352 if (!getDolGlobalStringempty('MAIN_DISABLE_PDF_AUTOUPDATE')) {
353 $ret = $object->fetch($object->id); // Reload to get new records
354 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
355 }*/
356
357 header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
358 exit;
359 } else {
360 setEventMessages($object->error, $object->errors, 'errors');
361 /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */
362 $action = '';
363 }
364 } elseif ($action == 'unlinkdiscount' && $usercancreate) {
365 // Delete link of credit note to invoice
366 $discount = new DiscountAbsolute($db);
367 $result = $discount->fetch(GETPOSTINT("discountid"));
368 if ($result > 0 && $object->id > 0 && $discount->fk_invoice_supplier == $object->id) { // The credit note must be linked to this invoice
369 $discount->unlink_invoice();
370 } else {
371 setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors');
372 }
373 } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercancreate) {
374 $object->fetch($id);
375 $result = $object->setPaid($user);
376 if ($result < 0) {
377 setEventMessages($object->error, $object->errors, 'errors');
378 }
379 } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercancreate) {
380 // Classif "paid partially"
381 $object->fetch($id);
382 $close_code = GETPOST("close_code", 'restricthtml');
383 $close_note = GETPOST("close_note", 'restricthtml');
384 if ($close_code) {
385 $result = $object->setPaid($user, $close_code, $close_note);
386 if ($result < 0) {
387 setEventMessages($object->error, $object->errors, 'errors');
388 }
389 } else {
390 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
391 }
392 } elseif ($action == 'confirm_canceled' && $confirm == 'yes' && $usercancreate) {
393 // Classify "abandoned"
394 $object->fetch($id);
395 $close_code = GETPOST("close_code", 'restricthtml');
396 $close_note = GETPOST("close_note", 'restricthtml');
397 if ($close_code) {
398 $result = $object->setCanceled($user, $close_code, $close_note);
399 if ($result < 0) {
400 setEventMessages($object->error, $object->errors, 'errors');
401 }
402 } else {
403 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
404 }
405 }
406
407 // Set supplier ref
408 if ($action == 'setref_supplier' && $usercancreate) {
409 $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
410
411 if ($object->update($user) < 0) {
412 setEventMessages($object->error, $object->errors, 'errors');
413 } else {
414 // Define output language
415 $outputlangs = $langs;
416 $newlang = '';
417 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
418 $newlang = GETPOST('lang_id', 'aZ09');
419 }
420 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
421 $newlang = $object->thirdparty->default_lang;
422 }
423 if (!empty($newlang)) {
424 $outputlangs = new Translate("", $conf);
425 $outputlangs->setDefaultLang($newlang);
426 }
427 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
428 $ret = $object->fetch($object->id); // Reload to get new records
429 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
430 }
431 }
432 }
433
434 // payments conditions
435 if ($action == 'setconditions' && $usercancreate) {
436 $object->fetch($id);
437 $object->cond_reglement_code = 0; // To clean property
438 $object->cond_reglement_id = 0; // To clean property
439
440 $error = 0;
441
442 $db->begin();
443
444 if (!$error) {
445 $result = $object->setPaymentTerms(GETPOSTINT('cond_reglement_id'));
446 if ($result < 0) {
447 $error++;
448 setEventMessages($object->error, $object->errors, 'errors');
449 }
450 }
451
452 if (!$error) {
453 $new_date_echeance = $object->calculate_date_lim_reglement();
454 if ($new_date_echeance) {
455 $object->date_echeance = $new_date_echeance;
456 }
457 if ($object->date_echeance < $object->date) {
458 $object->date_echeance = $object->date;
459 }
460 $result = $object->update($user);
461 if ($result < 0) {
462 $error++;
463 setEventMessages($object->error, $object->errors, 'errors');
464 }
465 }
466
467 if ($error) {
468 $db->rollback();
469 } else {
470 $db->commit();
471 }
472 } elseif ($action == 'set_incoterms' && isModEnabled('incoterm') && $usercancreate) {
473 // Set incoterm
474 $result = $object->setIncoterms(GETPOSTINT('incoterm_id'), GETPOST('location_incoterms'));
475 } elseif ($action == 'settags' && isModEnabled('category') && $usercancreate) {
476 // Set tags
477 $result = $object->setCategories(GETPOST('categories', 'array'));
478 } elseif ($action == 'setmode' && $usercancreate) {
479 // payment mode
480 $result = $object->setPaymentMethods(GETPOSTINT('mode_reglement_id'));
481 } elseif ($action == 'setmulticurrencycode' && $usercancreate) {
482 // Multicurrency Code
483 $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
484 } elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
485 // Multicurrency rate
486 $result = $object->setMulticurrencyRate((float) price2num(GETPOST('multicurrency_tx', 'alpha')), GETPOSTINT('calculation_mode'));
487 } elseif ($action == 'setbankaccount' && $usercancreate) {
488 // bank account
489 $result = $object->setBankAccount(GETPOSTINT('fk_account'));
490 } elseif ($action == 'setvatreversecharge' && $usercancreate) {
491 // vat reverse charge
492 $vatreversecharge = GETPOST('vat_reverse_charge') == 'on' ? 1 : 0;
493 $result = $object->setVATReverseCharge($vatreversecharge);
494 }
495
496 if ($action == 'settransportmode' && $usercancreate) {
497 // transport mode
498 $result = $object->setTransportMode(GETPOSTINT('transport_mode_id'));
499 } elseif ($action == 'setlabel' && $usercancreate) {
500 // Set label
501 $object->fetch($id);
502 $object->label = GETPOST('label');
503 $result = $object->update($user);
504 if ($result < 0) {
505 setEventMessages($object->error, $object->errors, 'errors');
506 }
507 } elseif ($action == 'setdatef' && $usercancreate) {
508 $newdate = dol_mktime(0, 0, 0, GETPOSTINT('datefmonth'), GETPOSTINT('datefday'), GETPOSTINT('datefyear'), 'tzserver');
509 if ($newdate > (dol_now('tzuserrel') + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
510 if (!getDolGlobalString('INVOICE_MAX_FUTURE_DELAY')) {
511 setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
512 } else {
513 setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
514 }
515 }
516
517 $object->fetch($id);
518
519 $object->date = $newdate;
520 $date_echence_calc = $object->calculate_date_lim_reglement();
521 if (!empty($object->date_echeance)) {
522 $object->date_echeance = $date_echence_calc;
523 }
524 if ($object->date_echeance && $object->date_echeance < $object->date) {
525 $object->date_echeance = $object->date;
526 }
527
528 $result = $object->update($user);
529 if ($result < 0) {
530 setEventMessages($object->error, $object->errors, 'errors');
531 }
532 } elseif ($action == 'setdate_pointoftax' && $usercancreate) {
533 $object->fetch($id);
534
535 $date_pointoftax = dol_mktime(0, 0, 0, GETPOSTINT('date_pointoftaxmonth'), GETPOSTINT('date_pointoftaxday'), GETPOSTINT('date_pointoftaxyear'), 'tzserver');
536 $object->date_pointoftax = $date_pointoftax;
537
538 $result = $object->update($user);
539 if ($result < 0) {
540 setEventMessages($object->error, $object->errors, 'errors');
541 $action = 'editdate_pointoftax';
542 }
543 } elseif ($action == 'setdate_lim_reglement' && $usercancreate) {
544 $object->fetch($id);
545 $object->date_echeance = dol_mktime(12, 0, 0, GETPOSTINT('date_lim_reglementmonth'), GETPOSTINT('date_lim_reglementday'), GETPOSTINT('date_lim_reglementyear'));
546 if (!empty($object->date_echeance) && $object->date_echeance < $object->date) {
547 $object->date_echeance = $object->date;
548 setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
549 }
550 $result = $object->update($user);
551 if ($result < 0) {
552 setEventMessages($object->error, $object->errors, 'errors');
553 }
554 } elseif ($action == "setabsolutediscount" && $usercancreate) {
555 $db->begin();
556 // We use the credit to reduce amount of invoice
557 if (GETPOSTINT("remise_id")) {
558 $ret = $object->fetch($id);
559 if ($ret > 0) {
560 $result = $object->insert_discount(GETPOSTINT("remise_id"));
561 if ($result < 0) {
562 setEventMessages($object->error, $object->errors, 'errors');
563 }
564 } else {
565 dol_print_error($db, $object->error);
566 }
567 }
568 // We use the credit to reduce remain to pay
569 if (GETPOSTINT("remise_id_for_payment")) {
570 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
571 $discount = new DiscountAbsolute($db);
572 $discount->fetch(GETPOSTINT("remise_id_for_payment"));
573
574 //var_dump($object->getRemainToPay(0));
575 //var_dump($discount->amount_ttc);exit;
576 $remaintopay = $object->getRemainToPay(0);
577 if (price2num($discount->amount_ttc) > price2num($remaintopay)) {
578 // TODO Split the discount in 2 automatically
579 $error++;
580 setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors');
581 }
582
583 if (!$error) {
584 $result = $discount->link_to_invoice(0, $id);
585 if ($result < 0) {
586 $error++;
587 setEventMessages($discount->error, $discount->errors, 'errors');
588 }
589 }
590 if (!$error) {
591 $newremaintopay = $object->getRemainToPay(0);
592 if ($newremaintopay == 0) {
593 $object->setPaid($user);
594 }
595 }
596 }
597 if (!$error) {
598 $db->commit();
599 } else {
600 $db->rollback();
601 }
602 if (empty($error) && !getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
603 $outputlangs = $langs;
604 $newlang = '';
605 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
606 $newlang = GETPOST('lang_id', 'aZ09');
607 }
608 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
609 $newlang = $object->thirdparty->default_lang;
610 }
611 if (!empty($newlang)) {
612 $outputlangs = new Translate("", $conf);
613 $outputlangs->setDefaultLang($newlang);
614 }
615 $ret = $object->fetch($id); // Reload to get new records
616
617 $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
618 if ($result < 0) {
619 setEventMessages($object->error, $object->errors, 'errors');
620 }
621 }
622 } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) {
623 // Convertir en reduc
624 $object->fetch($id);
625 $object->fetch_thirdparty();
626 //$object->fetch_lines(); // Already done into fetch
627
628 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
629 $discountcheck = new DiscountAbsolute($db);
630 $result = $discountcheck->fetch(0, 0, $object->id);
631
632 $canconvert = 0;
633 if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) {
634 $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
635 }
636 if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paid == 0 && empty($discountcheck->id)) {
637 $canconvert = 1; // we can convert credit note into discount if credit note is not refunded completely and not already converted and amount of payment is 0 (see also the real condition used as the condition to show button converttoreduc)
638 }
639 if ($canconvert) {
640 $db->begin();
641
642 $amount_ht = $amount_tva = $amount_ttc = array();
643 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
644
645 // Loop on each vat rate
646 $i = 0;
647 foreach ($object->lines as $line) {
648 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 and no need to create discount if amount is null
649 $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
650
651 $amount_ht[$keyforvatrate] += $line->total_ht;
652 $amount_tva[$keyforvatrate] += $line->total_tva;
653 $amount_ttc[$keyforvatrate] += $line->total_ttc;
654 $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
655 $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
656 $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
657 $i++;
658 }
659 }
660 '@phan-var-force array<string,float> $amount_ht
661 @phan-var-force array<string,float> $amount_tva
662 @phan-var-force array<string,float> $amount_ttc
663 @phan-var-force array<string,float> $multicurrency_amount_ht
664 @phan-var-force array<string,float> $multicurrency_amount_tva
665 @phan-var-force array<string,float> $multicurrency_amount_ttc';
666
667 // If some payments were already done, we change the amount to pay using same prorate
668 if (getDolGlobalString('SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED') && $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
669 $alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
670 if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
671 $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
672 foreach ($amount_ht as $vatrate => $val) {
673 $amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
674 $amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
675 $amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
676 $multicurrency_amount_ht[$vatrate] = price2num($multicurrency_amount_ht[$vatrate] * $ratio, 'MU');
677 $multicurrency_amount_tva[$vatrate] = price2num($multicurrency_amount_tva[$vatrate] * $ratio, 'MU');
678 $multicurrency_amount_ttc[$vatrate] = price2num($multicurrency_amount_ttc[$vatrate] * $ratio, 'MU');
679 }
680 }
681 }
682 //var_dump($amount_ht);var_dump($amount_tva);var_dump($amount_ttc);exit;
683
684 // Insert one discount by VAT rate category
685 $discount = new DiscountAbsolute($db);
687 $discount->description = '(CREDIT_NOTE)';
688 } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) {
689 $discount->description = '(DEPOSIT)';
691 $discount->description = '(EXCESS PAID)';
692 } else {
693 setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
694 }
695 $discount->discount_type = 1; // Supplier discount
696 $discount->fk_soc = $object->socid;
697 $discount->socid = $object->socid;
698 $discount->fk_invoice_supplier_source = $object->id;
699
700 $error = 0;
701
703 // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT
704
705 // Total payments
706 $sql = 'SELECT SUM(pf.amount) as total_paiements';
707 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p';
708 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN ('.getEntity('c_paiement').')';
709 $sql .= ' WHERE pf.fk_facturefourn = '.((int) $object->id);
710 $sql .= ' AND pf.fk_paiementfourn = p.rowid';
711 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
712
713 $resql = $db->query($sql);
714 if (!$resql) {
716 }
717
718 $res = $db->fetch_object($resql);
719 $total_paiements = $res->total_paiements;
720
721 // Total credit note and deposit
722 $total_creditnote_and_deposit = 0;
723 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
724 $sql .= " re.description, re.fk_invoice_supplier_source";
725 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
726 $sql .= " WHERE fk_invoice_supplier = ".((int) $object->id);
727 $resql = $db->query($sql);
728 if (!empty($resql)) {
729 while ($obj = $db->fetch_object($resql)) {
730 $total_creditnote_and_deposit += $obj->amount_ttc;
731 }
732 } else {
734 }
735
736 $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
737 $discount->amount_tva = 0;
738 $discount->tva_tx = 0;
739 $discount->vat_src_code = '';
740
741 // multi-currency
742 $discount->multicurrency_code = $object->multicurrency_code;
743 $discount->multicurrency_tx = $object->multicurrency_tx;
744 $discount->multicurrency_total_ht = $discount->multicurrency_total_ttc = (float) price2num((float) $discount->amount_ttc * (float) $object->multicurrency_tx, 'MT');
745 $discount->multicurrency_total_tva = 0;
746 // keep compatibility
747 $discount->multicurrency_amount_ht = $discount->multicurrency_amount_ttc = $discount->multicurrency_total_ttc;
748 $discount->multicurrency_amount_tva = 0;
749
750 $result = $discount->create($user);
751 if ($result < 0) {
752 $error++;
753 }
754 }
756 foreach ($amount_ht as $tva_tx => $xxx) {
757 // multi-currency
758 $discount->multicurrency_code = $object->multicurrency_code;
759 $discount->multicurrency_tx = $object->multicurrency_tx;
761 // A credit note can mix lines of both signs: each VAT rate keeps its own sign
762 $discount->amount_ht = -((float) $amount_ht[$tva_tx]);
763 $discount->amount_tva = -((float) $amount_tva[$tva_tx]);
764 $discount->amount_ttc = -((float) $amount_ttc[$tva_tx]);
765 $discount->multicurrency_total_ht = -((float) $multicurrency_amount_ht[$tva_tx]);
766 $discount->multicurrency_total_tva = -((float) $multicurrency_amount_tva[$tva_tx]);
767 $discount->multicurrency_total_ttc = -((float) $multicurrency_amount_ttc[$tva_tx]);
768 } else {
769 $discount->amount_ht = abs((float) $amount_ht[$tva_tx]);
770 $discount->amount_tva = abs((float) $amount_tva[$tva_tx]);
771 $discount->amount_ttc = abs((float) $amount_ttc[$tva_tx]);
772 $discount->multicurrency_total_ht = abs((float) $multicurrency_amount_ht[$tva_tx]);
773 $discount->multicurrency_total_tva = abs((float) $multicurrency_amount_tva[$tva_tx]);
774 $discount->multicurrency_total_ttc = abs((float) $multicurrency_amount_ttc[$tva_tx]);
775 }
776 // keep compatibility
777 $discount->multicurrency_amount_ht = $discount->multicurrency_total_ht;
778 $discount->multicurrency_amount_tva = $discount->multicurrency_total_tva;
779 $discount->multicurrency_amount_ttc = $discount->multicurrency_total_ttc;
780
781 // Clean vat code
782 $reg = array();
783 $vat_src_code = '';
784 if (preg_match('/\‍((.*)\‍)/', $tva_tx, $reg)) {
785 $vat_src_code = $reg[1];
786 $tva_tx = preg_replace('/\s*\‍(.*\‍)/', '', $tva_tx); // Remove code into vatrate.
787 }
788
789 $discount->tva_tx = abs((float) $tva_tx);
790 $discount->vat_src_code = $vat_src_code;
791
792 $result = $discount->create($user);
793 if ($result < 0) {
794 $error++;
795 break;
796 }
797 }
798 }
799
800 if (empty($error)) {
802 // Set invoice as paid
803 $result = $object->setPaid($user);
804 if ($result >= 0) {
805 $db->commit();
806 } else {
807 setEventMessages($object->error, $object->errors, 'errors');
808 $db->rollback();
809 }
810 } else {
811 $db->commit();
812 }
813 } else {
814 setEventMessages($discount->error, $discount->errors, 'errors');
815 $db->rollback();
816 }
817 }
818 } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) {
819 // Delete payment
820 $object->fetch($id);
821 if ($object->status == FactureFournisseur::STATUS_VALIDATED && $object->paid == 0) {
822 $paiementfourn = new PaiementFourn($db);
823 $result = $paiementfourn->fetch(GETPOSTINT('paiement_id'));
824 if ($result > 0) {
825 $result = $paiementfourn->delete($user);
826 if ($result > 0) {
827 header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
828 exit;
829 }
830 }
831 if ($result < 0) {
832 setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors');
833 }
834 }
835 } elseif ($action == 'add' && $usercancreate) {
836 // Insert new invoice in database
837 if ($socid > 0) {
838 $object->socid = GETPOSTINT('socid');
839 }
840 $selectedLines = GETPOST('toselect', 'array:int');
841
842 $db->begin();
843
844 $error = 0;
845 $tmpproject = 0; // Ensure a value
846
847 // Fill array 'array_options' with data from add form
848 $ret = $extrafields->setOptionalsFromPost(null, $object);
849 if ($ret < 0) {
850 $error++;
851 }
852
853 $dateinvoice = dol_mktime(0, 0, 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'), 'tzserver'); // If we enter the 02 january, we need to save the 02 january for server
854 $datedue = dol_mktime(0, 0, 0, GETPOSTINT('echmonth'), GETPOSTINT('echday'), GETPOSTINT('echyear'), 'tzserver');
855 //var_dump($dateinvoice.' '.dol_print_date($dateinvoice, 'dayhour'));
856 //var_dump(dol_now('tzuserrel').' '.dol_get_last_hour(dol_now('tzuserrel')).' '.dol_print_date(dol_now('tzuserrel'),'dayhour').' '.dol_print_date(dol_get_last_hour(dol_now('tzuserrel')), 'dayhour'));
857 //var_dump($db->idate($dateinvoice));
858 //exit;
859
860 // Replacement invoice
861 if (GETPOST('type') === '') {
862 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
863 $error++;
864 }
865
867 if (empty($dateinvoice)) {
868 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
869 $action = 'create';
870 //$_GET['socid'] = $_POST['socid'];
871 $error++;
872 } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
873 $error++;
874 setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
875 $action = 'create';
876 }
877
878 if (!(GETPOSTINT('fac_replacement') > 0)) {
879 $error++;
880 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
881 }
882
883 if (!$error) {
884 // This is a replacement invoice
885 $result = $object->fetch(GETPOSTINT('fac_replacement'));
886 $object->fetch_thirdparty();
887
888 $tmpproject = GETPOSTINT('projectid');
889
890 $object->ref = GETPOST('ref', 'alphanohtml');
891 $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
892 $object->socid = GETPOSTINT('socid');
893 $object->label = GETPOST('label', 'alphanohtml');
894 $object->libelle = $object->label; // deprecated
895 $object->date = $dateinvoice;
896 $object->date_pointoftax = $date_pointoftax;
897 $object->date_echeance = $datedue;
898 $object->note_public = GETPOST('note_public', 'restricthtml');
899 $object->note_private = GETPOST('note_private', 'restricthtml');
900 $object->cond_reglement_id = GETPOSTINT('cond_reglement_id');
901 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
902 $object->fk_account = GETPOSTINT('fk_account');
903 $object->vat_reverse_charge = GETPOST('vat_reverse_charge') == 'on' ? 1 : 0;
904 $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
905 $object->fk_incoterms = GETPOSTINT('incoterm_id');
906 $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
907 $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
908 $object->multicurrency_tx = GETPOSTFLOAT('originmulticurrency_tx');
909 $object->transport_mode_id = GETPOSTINT('transport_mode_id');
910
911 // Proprietes particulieres a facture de replacement
912 $object->fk_facture_source = GETPOSTINT('fac_replacement');
914
915 $id = $object->createFromCurrent($user);
916 if ($id <= 0) {
917 $error++;
918 setEventMessages($object->error, $object->errors, 'errors');
919 }
920 }
921 }
922
923 // Credit note invoice
925 $sourceinvoice = GETPOSTINT('fac_avoir');
926 if (!($sourceinvoice > 0) && !getDolGlobalString('INVOICE_CREDIT_NOTE_STANDALONE')) {
927 $error++;
928 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
929 }
930 if (GETPOSTINT('socid') < 1) {
931 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
932 $action = 'create';
933 $error++;
934 }
935
936 if (empty($dateinvoice)) {
937 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
938 $action = 'create';
939 //$_GET['socid'] = $_POST['socid'];
940 $error++;
941 } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
942 $error++;
943 setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
944 $action = 'create';
945 }
946
947 if (!GETPOST('ref_supplier')) {
948 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplierBill')), null, 'errors');
949 $action = 'create';
950 //$_GET['socid'] = $_POST['socid'];
951 $error++;
952 }
953
954 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED') && empty(GETPOST("subtype"))) {
955 $error++;
956 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSubtype")), null, 'errors');
957 $action = 'create';
958 }
959
960 if (!$error) {
961 $tmpproject = GETPOSTINT('projectid');
962
963 // Create Supplier Invoice
964 $object->ref = GETPOST('ref', 'alphanohtml');
965 $object->ref_supplier = GETPOST('ref_supplier', 'alphanohtml');
966 $object->subtype = GETPOSTINT('subtype');
967 $object->socid = GETPOSTINT('socid');
968 $object->label = GETPOST('label', 'alphanohtml');
969 $object->libelle = $object->label; // Deprecated
970 $object->date = $dateinvoice;
971 $object->date_pointoftax = $date_pointoftax;
972 $object->date_echeance = $datedue;
973 $object->note_public = GETPOST('note_public', 'restricthtml');
974 $object->note_private = GETPOST('note_private', 'restricthtml');
975 $object->cond_reglement_id = GETPOSTINT('cond_reglement_id');
976 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
977 $object->fk_account = GETPOSTINT('fk_account');
978 $object->vat_reverse_charge = GETPOST('vat_reverse_charge') == 'on' ? 1 : 0;
979 $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
980 $object->fk_incoterms = GETPOSTINT('incoterm_id');
981 $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
982 $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
983 $object->multicurrency_tx = GETPOSTFLOAT('originmulticurrency_tx');
984 $object->transport_mode_id = GETPOSTINT('transport_mode_id');
985
986 // Proprietes particulieres a facture avoir
987 $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
989
990 $id = $object->create($user);
991
992 if ($id <= 0) {
993 $error++;
994 }
995
996 if (GETPOSTINT('invoiceAvoirWithLines') == 1 && $id > 0) {
997 $facture_source = new FactureFournisseur($db); // fetch origin object
998 if ($facture_source->fetch($object->fk_facture_source) > 0) {
999 $fk_parent_line = 0;
1000
1001 foreach ($facture_source->lines as $line) {
1002 // Extrafields
1003 if (method_exists($line, 'fetch_optionals')) {
1004 $line->fetch_optionals();
1005 }
1006
1007 // Reset fk_parent_line for no child products and special product
1008 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1009 $fk_parent_line = 0;
1010 }
1011
1012 $line->fk_facture_fourn = $object->id;
1013 $line->fk_parent_line = $fk_parent_line;
1014
1015 $line->subprice = -$line->subprice; // invert price for object
1016 $line->pa_ht = -((float) $line->pa_ht);
1017 $line->total_ht = -$line->total_ht;
1018 $line->total_tva = -$line->total_tva;
1019 $line->total_ttc = -$line->total_ttc;
1020 $line->total_localtax1 = -$line->total_localtax1;
1021 $line->total_localtax2 = -$line->total_localtax2;
1022 $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
1023 $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
1024 $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
1025
1026 $result = $line->insert();
1027
1028 $object->lines[] = $line; // insert new line in current object
1029
1030 // Defined the new fk_parent_line
1031 if ($result > 0 && $line->product_type == 9) {
1032 $fk_parent_line = $result;
1033 }
1034 }
1035
1036 $object->update_price(1);
1037 }
1038 }
1039
1040 if (GETPOSTINT('invoiceAvoirWithPaymentRestAmount') == 1 && $id > 0) {
1041 $facture_source = new FactureFournisseur($db); // fetch origin object if not previously defined
1042 if ($facture_source->fetch($object->fk_facture_source) > 0) {
1043 $totalpaid = $facture_source->getSommePaiement();
1044 $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
1045 $totaldeposits = $facture_source->getSumDepositsUsed();
1046 $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
1047 $desc = $langs->trans('invoiceAvoirLineWithPaymentRestAmount');
1048
1049 // Pass the amount already signed: addline() forces -abs() on credit notes with the default setup, so this
1050 // changes nothing there, but it keeps the line negative when that forcing is relaxed (see addline()).
1051 $retAddLine = $object->addline($desc, -$remain_to_pay, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 'TTC');
1052
1053 if ($retAddLine < 0) {
1054 $error++;
1055 }
1056 }
1057 }
1058
1059 // Add link between credit note and origin objects
1060 if (!empty($object->fk_facture_source) && $id > 0) {
1061 $facture_source_link = new FactureFournisseur($db);
1062 if ($facture_source_link->fetch($object->fk_facture_source) > 0) {
1063 $facture_source_link->fetchObjectLinked();
1064 if (!empty($facture_source_link->linkedObjectsIds)) {
1065 foreach ($facture_source_link->linkedObjectsIds as $sourcetype => $TIds) {
1066 $object->add_object_linked($sourcetype, current($TIds));
1067 }
1068 }
1069 }
1070 }
1071 }
1072 } elseif ($fac_recid > 0 && (GETPOSTINT('type') == FactureFournisseur::TYPE_STANDARD || GETPOSTINT('type') == FactureFournisseur::TYPE_DEPOSIT)) {
1073 // Standard invoice or Deposit invoice, created from a Predefined template invoice
1074 if (empty($dateinvoice)) {
1075 $error++;
1076 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1077 $action = 'create';
1078 } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1079 $error++;
1080 setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1081 $action = 'create';
1082 }
1083
1084 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED') && empty(GETPOST("subtype"))) {
1085 $error++;
1086 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSubtype")), null, 'errors');
1087 $action = 'create';
1088 }
1089
1090 if (!$error) {
1091 $object->socid = GETPOSTINT('socid');
1092 $object->type = GETPOSTINT('type');
1093 $object->subtype = GETPOSTINT('subtype');
1094 $object->ref = GETPOST('ref', 'alphanohtml');
1095 $object->date = $dateinvoice;
1096 $object->date_pointoftax = $date_pointoftax;
1097 $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1098 $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
1099 $object->ref_supplier = GETPOST('ref_supplier', 'alphanohtml');
1100 $object->model_pdf = GETPOST('model', 'alphanohtml');
1101 $object->fk_project = GETPOSTINT('projectid');
1102 $object->cond_reglement_id = (GETPOSTINT('type') == 3 ? 1 : GETPOSTINT('cond_reglement_id'));
1103 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
1104 $object->fk_account = GETPOSTINT('fk_account');
1105 $object->amount = (float) price2num(GETPOST('amount')); // FIXME: FactureFournisseur::$amount is deprecated and not used?
1106 $object->fk_incoterms = GETPOSTINT('incoterm_id');
1107 $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1108 $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1109 $object->multicurrency_tx = GETPOSTFLOAT('originmulticurrency_tx');
1110
1111 // Source facture
1112 $object->fac_rec = $fac_recid;
1113 $fac_rec = new FactureFournisseurRec($db);
1114 $fac_rec->fetch($object->fac_rec);
1115 $fac_rec->fetch_lines();
1116 $object->lines = $fac_rec->lines;
1117
1118 $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines
1119 }
1120 } elseif ($fac_recid <= 0 && (GETPOSTINT('type') == FactureFournisseur::TYPE_STANDARD || GETPOSTINT('type') == FactureFournisseur::TYPE_DEPOSIT)) {
1121 // Standard invoice or Deposit invoice, not from a Predefined template invoice
1122 if (GETPOSTINT('socid') < 1) {
1123 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
1124 $action = 'create';
1125 $error++;
1126 }
1127
1128 if (empty($dateinvoice)) {
1129 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
1130 $action = 'create';
1131 //$_GET['socid'] = $_POST['socid'];
1132 $error++;
1133 } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1134 $error++;
1135 setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1136 $action = 'create';
1137 }
1138
1139 if (!GETPOST('ref_supplier')) {
1140 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplierBill')), null, 'errors');
1141 $action = 'create';
1142 //$_GET['socid'] = $_POST['socid'];
1143 $error++;
1144 }
1145
1146 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED') && empty(GETPOST("subtype"))) {
1147 $error++;
1148 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSubtype")), null, 'errors');
1149 $action = 'create';
1150 }
1151
1152 if (!$error) {
1153 $tmpproject = GETPOSTINT('projectid');
1154
1155 // Creation invoice
1156 $object->socid = GETPOSTINT('socid');
1157 $object->type = GETPOSTINT('type');
1158 $object->subtype = GETPOSTINT('subtype');
1159 $object->ref = GETPOST('ref', 'alphanohtml');
1160 $object->ref_supplier = GETPOST('ref_supplier', 'alphanohtml');
1161 $object->socid = GETPOSTINT('socid');
1162 $object->label = GETPOST('label', 'alphanohtml');
1163 $object->libelle = $object->label; // deprecated
1164 $object->date = $dateinvoice;
1165 $object->date_pointoftax = $date_pointoftax;
1166 $object->date_echeance = $datedue;
1167 $object->note_public = GETPOST('note_public', 'restricthtml');
1168 $object->note_private = GETPOST('note_private', 'restricthtml');
1169 $object->cond_reglement_id = GETPOSTINT('cond_reglement_id');
1170 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
1171 $object->fk_account = GETPOSTINT('fk_account');
1172 $object->vat_reverse_charge = GETPOST('vat_reverse_charge') == 'on' ? 1 : 0;
1173 $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
1174 $object->fk_incoterms = GETPOSTINT('incoterm_id');
1175 $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1176 $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1177 $object->multicurrency_tx = GETPOSTFLOAT('originmulticurrency_tx');
1178 $object->transport_mode_id = GETPOSTINT('transport_mode_id');
1179
1180 // Auto calculation of date due if not filled by user
1181 if (empty($object->date_echeance)) {
1182 $object->date_echeance = $object->calculate_date_lim_reglement();
1183 }
1184
1185 $object->fetch_thirdparty();
1186
1187 // If creation from another object of another module
1188 if (!$error && GETPOST('origin', 'alpha') && GETPOST('originid')) {
1189 // Parse element/subelement (ex: project_task)
1190 $element = $subelement = GETPOST('origin', 'alpha');
1191 /*if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'),$regs))
1192 {
1193 $element = $regs[1];
1194 $subelement = $regs[2];
1195 }*/
1196
1197 // For compatibility
1198 if ($element == 'order') {
1199 $element = $subelement = 'commande';
1200 }
1201 if ($element == 'propal') {
1202 $element = 'comm/propal';
1203 $subelement = 'propal';
1204 }
1205 if ($element == 'contract') {
1206 $element = $subelement = 'contrat';
1207 }
1208 if ($element == 'order_supplier') {
1209 $element = 'fourn';
1210 $subelement = 'fournisseur.commande';
1211 }
1212 if ($element == 'project') {
1213 $element = 'projet';
1214 }
1215 $object->origin_type = GETPOST('origin', 'alpha');
1216 $object->origin = $object->origin_type;
1217 $object->origin_id = GETPOSTINT('originid');
1218
1219
1220 dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1221 $classname = ucfirst($subelement);
1222 if ($classname == 'Fournisseur.commande') {
1223 $classname = 'CommandeFournisseur';
1224 }
1225 $objectsrc = new $classname($db);
1226 $objectsrc->fetch($originid);
1227 $objectsrc->fetch_thirdparty();
1228
1229 if (!empty($object->origin_type) && !empty($object->origin_id)) {
1230 $object->linkedObjectsIds[$object->origin_type][-1] = $object->origin_id;
1231 }
1232
1233 // Add also link with order if object is reception
1234 if ($object->origin_type == 'reception') {
1235 $objectsrc->fetchObjectLinked();
1236
1237 if (count($objectsrc->linkedObjectsIds['order_supplier']) > 0) {
1238 foreach ($objectsrc->linkedObjectsIds['order_supplier'] as $key => $value) {
1239 $object->linkedObjectsIds['order_supplier'][-1] = $value;
1240 }
1241 }
1242 }
1243
1244 $id = $object->create($user);
1245
1246 // Add lines
1247 if ($id > 0) {
1248 dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1249 $classname = ucfirst($subelement);
1250 if ($classname == 'Fournisseur.commande') {
1251 $classname = 'CommandeFournisseur';
1252 }
1253 $srcobject = new $classname($db);
1254
1255 $result = $srcobject->fetch(GETPOSTINT('originid'));
1256
1257 // If deposit invoice - down payment with 1 line (fixed amount or percent)
1258 $typeamount = GETPOST('typedeposit', 'alpha');
1259 if (GETPOSTINT('type') == FactureFournisseur::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) {
1260 $valuedeposit = price2num(GETPOST('valuedeposit', 'alpha'), 'MU');
1261
1262 // Define the array $amountdeposit
1263 $amountdeposit = array();
1264 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA')) {
1265 if ($typeamount == 'amount') {
1266 $amount = $valuedeposit;
1267 } else {
1268 $amount = $srcobject->total_ttc * ((float) $valuedeposit / 100);
1269 }
1270
1271 $TTotalByTva = array();
1272 foreach ($srcobject->lines as &$line) {
1273 if (!empty($line->special_code)) {
1274 continue;
1275 }
1276 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1277 }
1278 '@phan-var-force array<string,float> $TTotalByTva';
1279
1280 $amount_ttc_diff = 0.;
1281 foreach ($TTotalByTva as $tva => &$total) {
1282 $coef = $total / $srcobject->total_ttc; // Calc coef
1283 $am = $amount * $coef;
1284 $amount_ttc_diff += $am;
1285 $amountdeposit[$tva] += $am / (1 + (float) $tva / 100); // Convert into HT for the addline
1286 }
1287 } else {
1288 if ($typeamount == 'amount') {
1289 $amountdeposit[0] = $valuedeposit;
1290 } elseif ($typeamount == 'variable') {
1291 if ($result > 0) {
1292 $totalamount = 0;
1293 $lines = $srcobject->lines;
1294 $numlines = count($lines);
1295 for ($i = 0; $i < $numlines; $i++) {
1296 $qualified = 1;
1297 if (empty($lines[$i]->qty)) {
1298 $qualified = 0; // We discard qty=0, it is an option
1299 }
1300 if (!empty($lines[$i]->special_code)) {
1301 $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...)
1302 }
1303 if ($qualified) {
1304 $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1305 $tva_tx = $lines[$i]->tva_tx;
1306 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * (float) $valuedeposit) / 100;
1307 }
1308 }
1309
1310 if ($totalamount == 0) {
1311 $amountdeposit[0] = 0;
1312 }
1313 } else {
1314 setEventMessages($srcobject->error, $srcobject->errors, 'errors');
1315 $error++;
1316 $amountdeposit[0] = 0;
1317 }
1318 }
1319
1320 $amount_ttc_diff = array_key_exists(0, $amountdeposit) ? $amountdeposit[0] : 0;
1321 }
1322
1323 foreach ($amountdeposit as $tva => $amount) {
1324 if (empty($amount)) {
1325 continue;
1326 }
1327
1328 $arraylist = array(
1329 'amount' => 'FixAmount',
1330 'variable' => 'VarAmount'
1331 );
1332 $descline = '(DEPOSIT)';
1333 //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
1334 if ($typeamount == 'amount') {
1335 $descline .= ' ('.price($valuedeposit, 0, $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')';
1336 } elseif ($typeamount == 'variable') {
1337 $descline .= ' ('.$valuedeposit.'%)';
1338 }
1339
1340 $descline .= ' - '.$srcobject->ref;
1341 $result = $object->addline(
1342 $descline,
1343 (float) $amount, // subprice
1344 $tva, // vat rate
1345 0, // localtax1_tx
1346 0, // localtax2_tx
1347 1, // quantity
1348 getDolGlobalInt('SUPPLIER_INVOICE_PRODUCTID_DEPOSIT', getDolGlobalInt('INVOICE_PRODUCTID_DEPOSIT')), // fk_product
1349 0, // remise_percent
1350 0, // date_start
1351 0, // date_end
1352 0,
1353 0, // info_bits
1354 'HT',
1355 0, // product_type
1356 1,
1357 0,
1358 array(), // array_options
1359 null,
1360 $object->origin_id,
1361 0,
1362 '',
1363 0, // special_code
1364 0,
1365 0,
1366 $object->origin_type
1367 );
1368 }
1369
1370 $diff = $object->total_ttc - $amount_ttc_diff;
1371
1372 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA') && $diff != 0) {
1373 $object->fetch_lines();
1374 $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
1375 $object->updateline(
1376 $object->lines[0]->id,
1377 $object->lines[0]->desc,
1378 $subprice_diff,
1379 $object->lines[0]->tva_tx,
1380 $object->lines[0]->localtax1_tx,
1381 $object->lines[0]->localtax2_tx,
1382 $object->lines[0]->qty,
1383 $object->lines[0]->fk_product,
1384 'HT',
1385 $object->lines[0]->info_bits,
1386 $object->lines[0]->product_type,
1387 $object->lines[0]->remise_percent,
1388 0,
1389 $object->lines[0]->date_start,
1390 $object->lines[0]->date_end,
1391 array(), // array_options
1392 0,
1393 0,
1394 '',
1395 100
1396 );
1397 }
1398 } elseif ($result > 0) {
1399 $lines = $srcobject->lines;
1400 if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
1401 $srcobject->fetch_lines();
1402 $lines = $srcobject->lines;
1403 }
1404
1405 $num = count($lines);
1406 for ($i = 0; $i < $num; $i++) { // TODO handle subprice < 0
1407 if (!in_array($lines[$i]->id, $selectedLines)) {
1408 continue; // Skip unselected lines
1409 }
1410
1411 $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->product_label);
1412 $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
1413
1414 // Extrafields
1415 if (method_exists($lines[$i], 'fetch_optionals')) {
1416 $lines[$i]->fetch_optionals();
1417 }
1418
1419 // Dates
1420 // TODO mutualiser
1421 $date_start = $lines[$i]->date_debut_prevue;
1422 if ($lines[$i]->date_debut_reel) {
1423 $date_start = $lines[$i]->date_debut_reel;
1424 }
1425 if ($lines[$i]->date_start) {
1426 $date_start = $lines[$i]->date_start;
1427 }
1428 $date_end = $lines[$i]->date_fin_prevue;
1429 if ($lines[$i]->date_fin_reel) {
1430 $date_end = $lines[$i]->date_fin_reel;
1431 }
1432 if ($lines[$i]->date_end) {
1433 $date_end = $lines[$i]->date_end;
1434 }
1435
1436 $tva_tx = $lines[$i]->tva_tx;
1437 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
1438 if (!empty($lines[$i]->vat_src_code) && !preg_match('/\‍(/', (string) $tva_tx)) {
1439 $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
1440 }
1441
1442 // FIXME Missing special_code into addline and updateline methods
1443 $object->special_code = $lines[$i]->special_code;
1444
1445 // FIXME If currency different from main currency, take multicurrency price
1446 if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
1447 $pu = 0;
1448 $pu_currency = $lines[$i]->multicurrency_subprice;
1449 } else {
1450 $pu = $lines[$i]->subprice;
1451 $pu_currency = 0;
1452 }
1453
1454 // FIXME Missing $lines[$i]->ref_supplier and $lines[$i]->label into addline and updateline methods. They are filled when coming from order for example.
1455 $result = $object->addline(
1456 $desc,
1457 $pu,
1458 $tva_tx,
1459 $lines[$i]->localtax1_tx,
1460 $lines[$i]->localtax2_tx,
1461 $lines[$i]->qty,
1462 $lines[$i]->fk_product,
1463 $lines[$i]->remise_percent,
1464 (int) $date_start,
1465 (int) $date_end,
1466 0,
1467 $lines[$i]->info_bits,
1468 'HT',
1469 $product_type,
1470 $lines[$i]->rang,
1471 0,
1472 $lines[$i]->array_options,
1473 $lines[$i]->fk_unit,
1474 $lines[$i]->id,
1475 $pu_currency,
1476 $lines[$i]->ref_supplier,
1477 $lines[$i]->special_code
1478 );
1479
1480 if ($result < 0) {
1481 $error++;
1482 break;
1483 }
1484
1485 // Keep the extra parameters of the source line (for example the options of subtotal lines)
1486 if ($result > 0 && !empty($lines[$i]->extraparams)) {
1487 $newline = new SupplierInvoiceLine($db);
1488 $newline->id = $result;
1489 $newline->extraparams = $lines[$i]->extraparams;
1490 $newline->setExtraParameters();
1491 }
1492 }
1493
1494 // Now reload line
1495 $object->fetch_lines();
1496 } else {
1497 $error++;
1498 }
1499
1500 if (!$error) {
1501 // Hooks
1502 $parameters = array('objFrom' => $srcobject);
1503 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
1504 // modified by hook
1505 if ($reshook < 0) {
1506 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1507 $error++;
1508 }
1509 }
1510 } else {
1511 $error++;
1512 }
1513 } elseif (!$error) {
1514 $id = $object->create($user);
1515 if ($id < 0) {
1516 $error++;
1517 }
1518 }
1519 }
1520 }
1521
1522 if ($error) {
1523 $langs->load("errors");
1524 $db->rollback();
1525
1526 setEventMessages($object->error, $object->errors, 'errors');
1527 $action = 'create';
1528 //$_GET['socid'] = $_POST['socid'];
1529 } else {
1530 if (isModEnabled('category')) {
1531 $categories = GETPOST('categories', 'array:int');
1532 if (method_exists($object, 'setCategories')) {
1533 $object->setCategories($categories);
1534 }
1535 }
1536
1537 $db->commit();
1538
1539 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1540 $outputlangs = $langs;
1541 $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1542 if ($result < 0) {
1543 dol_print_error($db, $object->error, $object->errors);
1544 exit;
1545 }
1546 }
1547
1548 header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
1549 exit;
1550 }
1551 } elseif ($action == 'updateline' && $usercancreate) {
1552 // Edit line
1553 $db->begin();
1554
1555 if (! $object->fetch($id) > 0) {
1557 }
1558 $object->fetch_thirdparty();
1559
1560 $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
1561 $tva_tx = str_replace('*', '', $tva_tx);
1562
1563 if (GETPOST('price_ht') != '' || GETPOST('multicurrency_subprice') != '') {
1564 $up = price2num(GETPOST('price_ht'), '', 2);
1565 $price_base_type = 'HT';
1566 } else {
1567 $up = price2num(GETPOST('price_ttc'), '', 2);
1568 $price_base_type = 'TTC';
1569 }
1570
1571 if (GETPOST('productid') > 0) {
1572 $productsupplier = new ProductFournisseur($db);
1573 if (getDolGlobalInt('SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY') == 1) { // Not the common case
1574 if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, (float) price2num(GETPOST('qty')), GETPOSTINT('productid'), 'restricthtml', GETPOSTINT('socid')) < 0) {
1575 setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings');
1576 }
1577 }
1578
1579 $prod = new Product($db);
1580 $prod->fetch(GETPOSTINT('productid'));
1581 $label = $prod->description;
1582 if (trim(GETPOST('product_desc', 'restricthtml')) != trim($label)) {
1583 $label = GETPOST('product_desc', 'restricthtml');
1584 }
1585
1586 $type = $prod->type;
1587 } else {
1588 $label = GETPOST('product_desc', 'restricthtml');
1589 $type = GETPOSTINT("type");
1590 }
1591
1592 $date_start = dol_mktime(GETPOSTINT('date_starthour'), GETPOSTINT('date_startmin'), GETPOSTINT('date_startsec'), GETPOSTINT('date_startmonth'), GETPOSTINT('date_startday'), GETPOSTINT('date_startyear'));
1593 $date_end = dol_mktime(GETPOSTINT('date_endhour'), GETPOSTINT('date_endmin'), GETPOSTINT('date_endsec'), GETPOSTINT('date_endmonth'), GETPOSTINT('date_endday'), GETPOSTINT('date_endyear'));
1594
1595 // Define info_bits
1596 $info_bits = 0;
1597 if (preg_match('/\*/', $tva_tx)) {
1598 $info_bits |= 0x01;
1599 }
1600
1601 // Define vat_rate
1602 $tva_tx = str_replace('*', '', $tva_tx);
1603 $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
1604 $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
1605
1606 $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
1607 $pu_devise = price2num(GETPOST('multicurrency_subprice'), 'MU', 2);
1608
1609 // Extrafields Lines
1610 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
1611 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
1612 // Unset extrafield POST Data
1613 if (is_array($extralabelsline)) {
1614 foreach ($extralabelsline as $key => $value) {
1615 unset($_POST["options_".$key]);
1616 }
1617 }
1618
1619 $result = $object->updateline(
1620 GETPOSTINT('lineid'),
1621 $label,
1622 (float) $up,
1623 $tva_tx,
1624 $localtax1_tx,
1625 $localtax2_tx,
1626 (float) price2num(GETPOST('qty'), 'MS'),
1627 GETPOSTINT('productid'),
1628 $price_base_type,
1629 $info_bits,
1630 $type,
1631 (float) $remise_percent,
1632 0,
1634 $date_end,
1635 $array_options,
1636 GETPOST('units') != '' ? GETPOSTINT('units') : null,
1637 (float) $pu_devise,
1638 GETPOST('fourn_ref', 'alpha')
1639 );
1640 if ($result >= 0) {
1641 unset($_POST['label']);
1642 unset($_POST['fourn_ref']);
1643 unset($_POST['date_starthour']);
1644 unset($_POST['date_startmin']);
1645 unset($_POST['date_startsec']);
1646 unset($_POST['date_startday']);
1647 unset($_POST['date_startmonth']);
1648 unset($_POST['date_startyear']);
1649 unset($_POST['date_endhour']);
1650 unset($_POST['date_endmin']);
1651 unset($_POST['date_endsec']);
1652 unset($_POST['date_endday']);
1653 unset($_POST['date_endmonth']);
1654 unset($_POST['date_endyear']);
1655 unset($_POST['price_ttc']);
1656 unset($_POST['price_ht']);
1657
1658 $db->commit();
1659 } else {
1660 $db->rollback();
1661 setEventMessages($object->error, $object->errors, 'errors');
1662 }
1663 } elseif ($action == 'addline' && GETPOST('submitforalllines', 'aZ09') && (GETPOST('alldate_start', 'alpha') || GETPOST('alldate_end', 'alpha')) && $usercancreate) {
1664 // Define date start and date end for all line
1665 $alldate_start = dol_mktime(GETPOSTINT('alldate_starthour'), GETPOSTINT('alldate_startmin'), 0, GETPOSTINT('alldate_startmonth'), GETPOSTINT('alldate_startday'), GETPOSTINT('alldate_startyear'));
1666 $alldate_end = dol_mktime(GETPOSTINT('alldate_endhour'), GETPOSTINT('alldate_endmin'), 0, GETPOSTINT('alldate_endmonth'), GETPOSTINT('alldate_endday'), GETPOSTINT('alldate_endyear'));
1667 foreach ($object->lines as $line) {
1668 if ($line->product_type == 1) { // only service line
1669 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->qty, $line->fk_product, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, 0, $alldate_start, $alldate_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice, $line->ref_supplier, $line->rang);
1670 }
1671 }
1672 } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('remiseforalllines', 'alpha') !== '' && $usercancreate) {
1673 // Define vat_rate
1674 $remise_percent = (GETPOST('remiseforalllines') ? GETPOST('remiseforalllines') : 0);
1675 $remise_percent = (float) str_replace('*', '', $remise_percent);
1676 foreach ($object->lines as $line) {
1677 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->qty, $line->fk_product, 'HT', $line->info_bits, $line->product_type, $remise_percent, 0, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice, $line->ref_supplier, $line->rang);
1678 }
1679 } elseif ($action == 'addline' && GETPOST('submitforalllines', 'aZ09') && GETPOST('vatforalllines', 'alpha') != '' && $usercancreate) {
1680 // Define vat_rate
1681 $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
1682 $vat_rate = str_replace('*', '', $vat_rate);
1683 $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
1684 $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
1685 foreach ($object->lines as $line) {
1686 $result = $object->updateline($line->id, $line->desc, $line->subprice, $vat_rate, $localtax1_rate, $localtax2_rate, $line->qty, $line->fk_product, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, 0, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice, $line->ref_supplier, $line->rang);
1687 }
1688 } elseif ($action == 'addline' && $usercancreate) {
1689 // Add a product line
1690 $db->begin();
1691
1692 $ret = $object->fetch($id);
1693 if ($ret < 0) {
1694 dol_print_error($db, $object->error);
1695 exit;
1696 }
1697 $ret = $object->fetch_thirdparty();
1698
1699 $langs->load('errors');
1700 $error = 0;
1701
1702 // Set if we used free entry or predefined product
1703 $predef = '';
1704 $line_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
1705 $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'));
1706 $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'));
1707
1708 $prod_entry_mode = GETPOST('prod_entry_mode');
1709 if ($prod_entry_mode == 'free') {
1710 $idprod = 0;
1711 } else {
1712 $idprod = GETPOSTINT('idprod');
1713 }
1714
1715 $price_ht = '';
1716 $price_ht_devise = '';
1717 $price_ttc = '';
1718 $price_ttc_devise = '';
1719
1720 if (GETPOST('price_ht') !== '') {
1721 $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
1722 }
1723 if (GETPOST('multicurrency_price_ht') !== '') {
1724 $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
1725 }
1726 if (GETPOST('price_ttc') !== '') {
1727 $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
1728 }
1729 if (GETPOST('multicurrency_price_ttc') !== '') {
1730 $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
1731 }
1732
1733 $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); // Can be '1.2' or '1.2 (CODE)'
1734
1735 $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
1736
1737 $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef, 'alpha'), '', 2) : 0);
1738 if (empty($remise_percent)) {
1739 $remise_percent = 0;
1740 }
1741
1742 // Extrafields
1743 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
1744 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
1745 // Unset extrafield
1746 if (is_array($extralabelsline)) {
1747 // Get extra fields
1748 foreach ($extralabelsline as $key => $value) {
1749 unset($_POST["options_".$key]);
1750 }
1751 }
1752
1753 if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) {
1754 setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
1755 $error++;
1756 }
1757 if ($prod_entry_mode == 'free' && (!GETPOST('idprodfournprice') || GETPOST('idprodfournprice') == '-1') && GETPOSTINT('type') < 0) {
1758 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
1759 $error++;
1760 }
1761
1762 // Do not allow negative lines for free products (invite to enter a discount instead)
1763 if ($prod_entry_mode == 'free' && (!GETPOST('idprodfournprice') || GETPOST('idprodfournprice') == '-1')
1764 && (((float) $price_ht < 0 && !getDolGlobalString('SUPPLIER_INVOICE_ENABLE_NEGATIVE_LINES')) || $price_ht === '')
1765 && (((float) $price_ht_devise < 0 && !getDolGlobalString('SUPPLIER_INVOICE_ENABLE_NEGATIVE_LINES')) || $price_ht_devise === '')
1766 && ((float) $price_ttc < 0 && !getDolGlobalString('SUPPLIER_INVOICE_ENABLE_NEGATIVE_LINES') || $price_ttc === '')
1767 && ((float) $price_ttc_devise < 0 && !getDolGlobalString('SUPPLIER_INVOICE_ENABLE_NEGATIVE_LINES') || $price_ttc_devise === '')
1768 && $object->type != $object::TYPE_CREDIT_NOTE) { // Unit price can be 0 but not ''
1769 if (((float) $price_ht < 0 || (float) $price_ttc < 0) && !getDolGlobalString('SUPPLIER_INVOICE_ENABLE_NEGATIVE_LINES')) {
1770 $langs->load("errors");
1771 if ($object->type == $object::TYPE_DEPOSIT) {
1772 // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
1773 setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
1774 } else {
1775 setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPrice"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
1776 }
1777 $error++;
1778 }
1779 }
1780 if ($prod_entry_mode == 'free' && (!GETPOST('idprodfournprice') || GETPOST('idprodfournprice') == '-1') && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not ''
1781 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors');
1782 $error++;
1783 }
1784
1785 if ($prod_entry_mode == 'free' && (!GETPOST('idprodfournprice') || GETPOST('idprodfournprice') == '-1') && !GETPOST('dp_desc')) {
1786 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
1787 $error++;
1788 }
1789 if (!GETPOST('qty', 'alpha')) { // 0 is NOT allowed for invoices
1790 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
1791 $error++;
1792 }
1793
1794 if (!$error && isModEnabled('variants') && $prod_entry_mode != 'free') {
1795 if ($combinations = GETPOST('combinations', 'array:alphanohtml')) {
1796 //Check if there is a product with the given combination
1797 $prodcomb = new ProductCombination($db);
1798
1799 if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
1800 $idprod = $res->fk_product_child;
1801 } else {
1802 setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
1803 $error++;
1804 }
1805 }
1806 }
1807
1808 if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
1809 $productsupplier = new ProductFournisseur($db);
1810
1811 $idprod = 0;
1812 if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') {
1813 $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, ...)
1814 }
1815
1816 $reg = array();
1817 if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) {
1818 $idprod = (int) $reg[1];
1819 $res = $productsupplier->fetch($idprod); // Load product from its id
1820 // Call to init some price properties of $productsupplier
1821 // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price
1822 if (getDolGlobalString('SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER')) {
1823 $fksoctosearch = 0;
1824 $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
1825 if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price
1826 $productsupplier->ref_supplier = '';
1827 }
1828 } else {
1829 $fksoctosearch = $object->thirdparty->id;
1830 $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
1831 }
1832 } elseif (GETPOSTINT('idprodfournprice') > 0) { // Should be an int at this point
1833 $qtytosearch = (float) $qty; // Just to see if a price exists for the quantity. Not used to found vat.
1834 //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist
1835 $idprod = $productsupplier->get_buyprice(GETPOSTINT('idprodfournprice'), $qtytosearch);
1836 $res = $productsupplier->fetch($idprod);
1837 }
1838
1839 if ($idprod > 0) {
1840 $label = $productsupplier->label;
1841 // Define output language
1842 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
1843 $outputlangs = $langs;
1844 $newlang = '';
1845 if (/* empty($newlang) && */ GETPOST('lang_id', 'aZ09')) {
1846 $newlang = GETPOST('lang_id', 'aZ09');
1847 }
1848 if (empty($newlang)) {
1849 $newlang = $object->thirdparty->default_lang;
1850 }
1851 if (!empty($newlang)) {
1852 $outputlangs = new Translate("", $conf);
1853 $outputlangs->setDefaultLang($newlang);
1854 }
1855 $desc = (!empty($productsupplier->multilangs[$outputlangs->defaultlang]["description"])) ? $productsupplier->multilangs[$outputlangs->defaultlang]["description"] : $productsupplier->description;
1856 } else {
1857 $desc = $productsupplier->description;
1858 }
1859 // if we use supplier description of the products
1860 if (!empty($productsupplier->desc_supplier) && getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
1861 $desc = $productsupplier->desc_supplier;
1862 }
1863
1864 if (getDolGlobalInt('PRODUIT_AUTOFILL_DESC') == 0) {
1865 // 'DoNotAutofillButAutoConcat'
1866 $desc = dol_concatdesc($desc, $line_desc, false, getDolGlobalString('MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION') ? true : false);
1867 } else {
1868 //'AutoFillFormFieldBeforeSubmit' or 'DoNotUseDescriptionOfProdut' => User has already done the modification they want
1869 $desc = $line_desc;
1870 }
1871
1872 $ref_supplier = $productsupplier->ref_supplier;
1873
1874 // Get vat rate
1875 if (!GETPOSTISSET('tva_tx')) { // If vat rate not provided from the form (the form has the priority)
1876 $tmpidprodfournprice = GETPOST('idprodfournprice', 'alpha'); // can be an id of price, or -1, -2, -99 or 'idprod_...'
1877 if (is_numeric($tmpidprodfournprice) && (int) $tmpidprodfournprice > 0) {
1878 $tmpidprodfournprice = (int) $tmpidprodfournprice;
1879 } else {
1880 $tmpidprodfournprice = 0;
1881 }
1882
1883 $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, $tmpidprodfournprice);
1884 $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, $tmpidprodfournprice);
1885 }
1886 if (empty($tva_tx) || empty($tva_npr)) {
1887 $tva_npr = 0;
1888 }
1889 $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr);
1890 $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr);
1891
1892 $type = $productsupplier->type;
1893 if (GETPOST('price_ht') != '' || GETPOST('multicurrency_price_ht') != '') {
1894 $price_base_type = 'HT';
1895 $pu = price2num($price_ht, 'MU');
1896 $pu_devise = price2num($price_ht_devise, 'CU');
1897 } elseif (GETPOST('price_ttc') != '' || GETPOST('multicurrency_price_ttc') != '') {
1898 $price_base_type = 'TTC';
1899 $pu = price2num($price_ttc, 'MU');
1900 $pu_devise = price2num($price_ttc_devise, 'CU');
1901 } else {
1902 $price_base_type = ($productsupplier->fourn_price_base_type ? $productsupplier->fourn_price_base_type : 'HT');
1903 if (empty($object->multicurrency_code) || ($productsupplier->fourn_multicurrency_code != $object->multicurrency_code)) { // If object is in a different currency and price not in this currency
1904 $pu = $productsupplier->fourn_pu;
1905 $pu_devise = 0;
1906 } else {
1907 $pu = $productsupplier->fourn_pu;
1908 $pu_devise = $productsupplier->fourn_multicurrency_unitprice;
1909 }
1910 }
1911
1912 $ref_supplier = $productsupplier->ref_supplier;
1913
1914 if (empty($pu)) {
1915 $pu = 0; // If pu is '' or null, we force to have a numeric value
1916 }
1917
1918 $result = $object->addline(
1919 $desc,
1920 $pu,
1921 $tva_tx,
1922 $localtax1_tx,
1923 $localtax2_tx,
1924 (float) $qty,
1925 $idprod,
1926 $remise_percent,
1928 $date_end,
1929 0,
1930 $tva_npr,
1931 $price_base_type,
1932 $type,
1933 min($rank, count($object->lines) + 1),
1934 0,
1935 $array_options,
1936 $productsupplier->fk_unit,
1937 0,
1938 $pu_devise,
1939 GETPOST('fourn_ref', 'alpha'),
1940 0
1941 );
1942 }
1943 if ($idprod == -99 || $idprod == 0) {
1944 // Product not selected
1945 $error++;
1946 $langs->load("errors");
1947 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
1948 }
1949 if ($idprod == -1) {
1950 // Quantity too low
1951 $error++;
1952 $langs->load("errors");
1953 setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors');
1954 }
1955 } elseif (empty($error)) { // $price_ht is already set
1956 $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
1957 $tva_tx = str_replace('*', '', $tva_tx);
1958 $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
1959 $desc = $line_desc;
1960 $type = GETPOSTINT('type');
1961 $ref_supplier = GETPOST('fourn_ref', 'alpha');
1962
1963 $fk_unit = GETPOST('units') !== '' ? GETPOSTINT('units') : null;
1964
1965 if (!preg_match('/\‍((.*)\‍)/', $tva_tx)) {
1966 $tva_tx = price2num($tva_tx); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
1967 }
1968
1969 // Local Taxes
1970 $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
1971 $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
1972
1973 if (GETPOST('price_ht') != '' || GETPOST('multicurrency_price_ht') != '') {
1974 $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings
1975 } else {
1976 $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
1977 $pu_ht = price2num((float) $pu_ttc / (1 + ((float) $tva_tx / 100)), 'MU'); // $pu_ht must be rounded according to settings
1978 }
1979 $price_base_type = 'HT';
1980 $pu_devise = price2num($price_ht_devise, 'CU');
1981
1982 $result = $object->addline($line_desc, (float) $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, (float) $qty, 0, $remise_percent, $date_start, $date_end, 0, $tva_npr, $price_base_type, $type, -1, 0, $array_options, $fk_unit, 0, (float) $pu_devise, $ref_supplier);
1983 }
1984
1985 //print "xx".$tva_tx; exit;
1986 if (!$error && $result > 0) {
1987 $db->commit();
1988
1989 // Define output language
1990 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1991 $outputlangs = $langs;
1992 $newlang = '';
1993 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1994 $newlang = GETPOST('lang_id', 'aZ09');
1995 }
1996 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1997 $newlang = $object->thirdparty->default_lang;
1998 }
1999 if (!empty($newlang)) {
2000 $outputlangs = new Translate("", $conf);
2001 $outputlangs->setDefaultLang($newlang);
2002 }
2003 $model = $object->model_pdf;
2004 $ret = $object->fetch($id); // Reload to get new records
2005
2006 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
2007 if ($result < 0) {
2008 setEventMessages($object->error, $object->errors, 'errors');
2009 }
2010 }
2011
2012 unset($_POST ['prod_entry_mode']);
2013
2014 unset($_POST['qty']);
2015 unset($_POST['type']);
2016 unset($_POST['remise_percent']);
2017 unset($_POST['pu']);
2018 unset($_POST['price_ht']);
2019 unset($_POST['multicurrency_price_ht']);
2020 unset($_POST['price_ttc']);
2021 unset($_POST['fourn_ref']);
2022 unset($_POST['tva_tx']);
2023 unset($_POST['label']);
2024 unset($localtax1_tx);
2025 unset($localtax2_tx);
2026 unset($_POST['np_marginRate']);
2027 unset($_POST['np_markRate']);
2028 unset($_POST['dp_desc']);
2029 unset($_POST['idprodfournprice']);
2030 unset($_POST['units']);
2031
2032 unset($_POST['date_starthour']);
2033 unset($_POST['date_startmin']);
2034 unset($_POST['date_startsec']);
2035 unset($_POST['date_startday']);
2036 unset($_POST['date_startmonth']);
2037 unset($_POST['date_startyear']);
2038 unset($_POST['date_endhour']);
2039 unset($_POST['date_endmin']);
2040 unset($_POST['date_endsec']);
2041 unset($_POST['date_endday']);
2042 unset($_POST['date_endmonth']);
2043 unset($_POST['date_endyear']);
2044 } else {
2045 $db->rollback();
2046 setEventMessages($object->error, $object->errors, 'errors');
2047 }
2048
2049 $action = '';
2050 } elseif ($action == 'classin' && $usercancreate) {
2051 $object->fetch($id);
2052 $result = $object->setProject($projectid);
2053 } elseif ($action == 'confirm_edit' && $confirm == 'yes' && $usercancreate) {
2054 // Set invoice to draft status
2055 $object->fetch($id);
2056
2057 $totalpaid = $object->getSommePaiement();
2058 $resteapayer = $object->total_ttc - $totalpaid;
2059
2060 // We check that lines of invoices are exported in accountancy
2061 $ventilExportCompta = $object->getVentilExportCompta();
2062
2063 if (!$ventilExportCompta) {
2064 // We verify that no payment was done
2065 if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->status == FactureFournisseur::STATUS_VALIDATED) {
2066 $idwarehouse = GETPOST('idwarehouse');
2067
2068 $object->fetch_thirdparty();
2069
2070 $qualified_for_stock_change = 0;
2071 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
2072 $qualified_for_stock_change = $object->hasProductsOrServices(2);
2073 } else {
2074 $qualified_for_stock_change = $object->hasProductsOrServices(1);
2075 }
2076
2077 // Check parameters
2078 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $qualified_for_stock_change) {
2079 $langs->load("stocks");
2080 if (!$idwarehouse || $idwarehouse == -1) {
2081 $error++;
2082 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
2083 $action = '';
2084 }
2085 }
2086
2087 $object->setDraft($user, $idwarehouse);
2088
2089 // Define output language
2090 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
2091 $outputlangs = $langs;
2092 $newlang = '';
2093 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
2094 $newlang = GETPOST('lang_id', 'aZ09');
2095 }
2096 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2097 $newlang = $object->thirdparty->default_lang;
2098 }
2099 if (!empty($newlang)) {
2100 $outputlangs = new Translate("", $conf);
2101 $outputlangs->setDefaultLang($newlang);
2102 }
2103 $model = $object->model_pdf;
2104 $ret = $object->fetch($id); // Reload to get new records
2105
2106 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
2107 if ($result < 0) {
2108 dol_print_error($db, $object->error, $object->errors);
2109 }
2110 }
2111
2112 $action = '';
2113 }
2114 }
2115 } elseif ($action == 'reopen' && $usercancreate) {
2116 // Set invoice to validated/unpaid status
2117 $result = $object->fetch($id);
2119 || ($object->status == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) {
2120 $result = $object->setUnpaid($user);
2121 if ($result > 0) {
2122 header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
2123 exit;
2124 } else {
2125 setEventMessages($object->error, $object->errors, 'errors');
2126 }
2127 }
2128 }
2129
2130 // Actions when printing a doc from card
2131 include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
2132
2133 // Actions to send emails
2134 $triggersendname = 'BILL_SUPPLIER_SENTBYMAIL';
2135 $paramname = 'id';
2136 $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO';
2137 $trackid = 'sinv'.$object->id;
2138 include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
2139
2140 // Actions to build doc
2141 $upload_dir = getMultidirOutput($object);
2142 $permissiontoadd = $usercancreate;
2143 include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
2144
2145 // Make calculation according to calculationrule
2146 if ($action == 'calculate' && $usercancreate) {
2147 $calculationrule = GETPOST('calculationrule');
2148
2149 $object->fetch($id);
2150 $object->fetch_thirdparty();
2151 $result = $object->update_price(0, (($calculationrule == 'totalofround') ? '0' : '1'), 0, $object->thirdparty);
2152 if ($result <= 0) {
2153 dol_print_error($db, $object->error, $object->errors);
2154 exit;
2155 }
2156 }
2157 if ($action == 'update_extras' && $permissiontoeditextra) {
2158 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
2159
2160 $attribute_name = GETPOST('attribute', 'aZ09');
2161
2162 // Fill array 'array_options' with data from update form
2163 $ret = $extrafields->setOptionalsFromPost(null, $object, $attribute_name);
2164 if ($ret < 0) {
2165 $error++;
2166 }
2167
2168 if (!$error) {
2169 $result = $object->updateExtraField($attribute_name, 'BILL_SUPPLIER_MODIFY');
2170 if ($result < 0) {
2171 setEventMessages($object->error, $object->errors, 'errors');
2172 $error++;
2173 }
2174 }
2175
2176 if ($error) {
2177 $action = 'edit_extras';
2178 }
2179 }
2180
2181 if (getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB')) {
2182 if ($action == 'addcontact' && $usercancreate) {
2183 $result = $object->fetch($id);
2184
2185 if ($result > 0 && $id > 0) {
2186 $contactid = (GETPOST('userid') ? GETPOSTINT('userid') : GETPOSTINT('contactid'));
2187 $typeid = (GETPOST('typecontact') ? GETPOSTINT('typecontact') : GETPOSTINT('type'));
2188 $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
2189 }
2190
2191 if ($result >= 0) {
2192 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
2193 exit;
2194 } else {
2195 if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2196 $langs->load("errors");
2197 setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
2198 } else {
2199 setEventMessages($object->error, $object->errors, 'errors');
2200 }
2201 }
2202 } elseif ($action == 'swapstatut' && $usercancreate) {
2203 // bascule du statut d'un contact
2204 if ($object->fetch($id)) {
2205 $result = $object->swapContactStatus(GETPOSTINT('ligne'));
2206 } else {
2208 }
2209 } elseif ($action == 'deletecontact' && $usercancreate) {
2210 // Efface un contact
2211 $object->fetch($id);
2212 $result = $object->delete_contact(GETPOSTINT("lineid"));
2213
2214 if ($result >= 0) {
2215 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
2216 exit;
2217 } else {
2219 }
2220 }
2221 }
2222}
2223
2224
2225/*
2226 * View
2227 */
2228
2229$form = new Form($db);
2230$formfile = new FormFile($db);
2231$bankaccountstatic = new Account($db);
2232$paymentstatic = new PaiementFourn($db);
2233if (isModEnabled('project')) {
2234 $formproject = new FormProjets($db);
2235}
2236
2237$now = dol_now();
2238
2239$title = $object->ref." - ".$langs->trans('Card');
2240if ($action == 'create') {
2241 $title = $langs->trans("NewSupplierInvoice");
2242}
2243$help_url = 'EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores|DE:Modul_Lieferantenrechnungen';
2244llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-fourn-facture page-card');
2245
2246// Mode creation
2247if ($action == 'create') {
2248 $facturestatic = new FactureFournisseur($db);
2249 $selectedLines = array(); // Ensure initialised
2250
2251 print load_fiche_titre($langs->trans('NewSupplierInvoice'), '', 'supplier_invoice');
2252
2254
2255 $currency_code = $conf->currency;
2256 $vat_reverse_charge = 0;
2257
2258 $societe = '';
2259 if (GETPOSTINT('socid') > 0) {
2260 $societe = new Societe($db);
2261 $societe->fetch(GETPOSTINT('socid'));
2262 if (isModEnabled("multicurrency") && !empty($societe->multicurrency_code)) {
2263 $currency_code = $societe->multicurrency_code;
2264 }
2265 }
2266
2267 $objectsrc = null; // Initialise
2268 if (!empty($origin) && !empty($originid)) {
2269 // Parse element/subelement (ex: project_task)
2270 $element = $subelement = $origin;
2271
2272 if ($element == 'project') {
2273 $projectid = $originid;
2274 $element = 'projet';
2275 }
2276
2277 // For compatibility
2278 if ($element == 'order') {
2279 $element = $subelement = 'commande';
2280 }
2281 if ($element == 'propal') {
2282 $element = 'comm/propal';
2283 $subelement = 'propal';
2284 }
2285 if ($element == 'contract') {
2286 $element = $subelement = 'contrat';
2287 }
2288 if ($element == 'order_supplier') {
2289 $element = 'fourn';
2290 $subelement = 'fournisseur.commande';
2291 }
2292
2293 dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
2294 $classname = ucfirst($subelement);
2295 if ($classname == 'Fournisseur.commande') {
2296 $classname = 'CommandeFournisseur';
2297 }
2298 $objectsrc = new $classname($db);
2299 '@phan-var-force Project|Commande|Propal|Facture|Contrat|CommandeFournisseur|CommonObject $objectsrc';
2301 $objectsrc->fetch($originid);
2302 $objectsrc->fetch_thirdparty();
2303
2304 $projectid = (int) $objectsrc->fk_project;
2305 //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:'');
2306 $soc = $objectsrc->thirdparty;
2307
2308 $cond_reglement_id = 0;
2309 $mode_reglement_id = 0;
2310 $fk_account = 0;
2311 $transport_mode_id = 0;
2312
2313 // set from object source
2314 if (!empty($objectsrc->cond_reglement_id)) {
2315 $cond_reglement_id = $objectsrc->cond_reglement_id;
2316 }
2317 if (!empty($objectsrc->mode_reglement_id)) {
2318 $mode_reglement_id = $objectsrc->mode_reglement_id;
2319 }
2320 if (!empty($objectsrc->fk_account)) {
2321 $fk_account = $objectsrc->fk_account;
2322 }
2323 if (!empty($objectsrc->transport_mode_id)) {
2324 $transport_mode_id = $objectsrc->transport_mode_id;
2325 }
2326
2327 if (empty($cond_reglement_id)
2328 || empty($mode_reglement_id)
2329 || empty($fk_account)
2330 || empty($transport_mode_id)
2331 ) {
2332 if ($origin == 'reception') {
2333 // try to get from source of reception (supplier order)
2334 if (!isset($objectsrc->supplier_order)) {
2335 $objectsrc->fetch_origin();
2336 }
2337
2338 if (!empty($objectsrc->origin_object)) {
2339 $originObject = $objectsrc->origin_object;
2340 if (empty($cond_reglement_id) && !empty($originObject->cond_reglement_id)) {
2341 $cond_reglement_id = $originObject->cond_reglement_id;
2342 }
2343 if (empty($mode_reglement_id) && !empty($originObject->mode_reglement_id)) {
2344 $mode_reglement_id = $originObject->mode_reglement_id;
2345 }
2346 if (empty($fk_account) && !empty($originObject->fk_account)) {
2347 $fk_account = $originObject->fk_account;
2348 }
2349 if (empty($transport_mode_id) && !empty($originObject->transport_mode_id)) {
2350 $transport_mode_id = $originObject->transport_mode_id;
2351 }
2352 }
2353 }
2354
2355 // try to get from third-party of source object
2356 if (!empty($soc)) {
2357 if (empty($cond_reglement_id) && !empty($soc->cond_reglement_supplier_id)) {
2358 $cond_reglement_id = $soc->cond_reglement_supplier_id;
2359 }
2360 if (empty($mode_reglement_id) && !empty($soc->mode_reglement_supplier_id)) {
2361 $mode_reglement_id = $soc->mode_reglement_supplier_id;
2362 }
2363 if (empty($fk_account) && !empty($soc->fk_account)) {
2364 $fk_account = $soc->fk_account;
2365 }
2366 if (empty($transport_mode_id) && !empty($soc->transport_mode_id)) {
2367 $transport_mode_id = $soc->transport_mode_id;
2368 }
2369 }
2370 }
2371
2372 if (isModEnabled("multicurrency")) {
2373 if (!empty($objectsrc->multicurrency_code)) {
2374 $currency_code = $objectsrc->multicurrency_code;
2375 }
2376 if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($objectsrc->multicurrency_tx)) {
2377 $currency_tx = $objectsrc->multicurrency_tx;
2378 }
2379 }
2380
2381 $datetmp = dol_mktime(12, 0, 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'));
2382 $dateinvoice = ($datetmp == '' ? (getDolGlobalString('MAIN_AUTOFILL_DATE') ? '' : -1) : $datetmp);
2383 $datetmp = dol_mktime(12, 0, 0, GETPOSTINT('echmonth'), GETPOSTINT('echday'), GETPOSTINT('echyear'));
2384 $datedue = ($datetmp == '' ? -1 : $datetmp);
2385
2386 // Replicate extrafields
2387 $objectsrc->fetch_optionals();
2388 $object->array_options = $objectsrc->array_options;
2389 } else {
2390 $cond_reglement_id = !empty($societe->cond_reglement_supplier_id) ? $societe->cond_reglement_supplier_id : 0;
2391 $mode_reglement_id = !empty($societe->mode_reglement_supplier_id) ? $societe->mode_reglement_supplier_id : 0;
2392 $vat_reverse_charge = (empty($societe) ? '' : $societe->vat_reverse_charge);
2393 $transport_mode_id = !empty($societe->transport_mode_supplier_id) ? $societe->transport_mode_supplier_id : 0;
2394 $fk_account = !empty($societe->fk_account) ? $societe->fk_account : 0;
2395 $datetmp = dol_mktime(12, 0, 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'));
2396 $dateinvoice = ($datetmp == '' ? (getDolGlobalInt('MAIN_AUTOFILL_DATE') ? '' : -1) : $datetmp);
2397 $datetmp = dol_mktime(12, 0, 0, GETPOSTINT('echmonth'), GETPOSTINT('echday'), GETPOSTINT('echyear'));
2398 $datedue = ($datetmp == '' ? -1 : $datetmp);
2399
2400 if (isModEnabled("multicurrency") && !empty($societe->multicurrency_code)) {
2401 $currency_code = $societe->multicurrency_code;
2402 }
2403 }
2404
2405 // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value
2406 if (empty($cond_reglement_id)) {
2407 $cond_reglement_id = GETPOST("cond_reglement_id");
2408 }
2409
2410 // when payment mode is empty (means not override by payment condition form a other object, like third-party), try to use default value
2411 if (empty($mode_reglement_id)) {
2412 $mode_reglement_id = GETPOST("mode_reglement_id");
2413 }
2414
2415 // If form was posted (but error returned), we must reuse the value posted in priority (standard Dolibarr behaviour)
2416 if (!GETPOST('changecompany')) {
2417 if (GETPOSTISSET('cond_reglement_id')) {
2418 $cond_reglement_id = GETPOSTINT('cond_reglement_id');
2419 }
2420 if (GETPOSTISSET('mode_reglement_id')) {
2421 $mode_reglement_id = GETPOSTINT('mode_reglement_id');
2422 }
2423 if (GETPOSTISSET('cond_reglement_id')) {
2424 $fk_account = GETPOSTINT('fk_account');
2425 }
2426 }
2427
2428 $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && getDolGlobalString('FACTUREFOURN_REUSE_NOTES_ON_CREATE_FROM')) ? $objectsrc->note_public : null));
2429 $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && getDolGlobalString('FACTUREFOURN_REUSE_NOTES_ON_CREATE_FROM')) ? $objectsrc->note_private : null));
2430
2431 if ($origin == 'contrat') {
2432 $langs->load("admin");
2433 $text = $langs->trans("ToCreateARecurringInvoice");
2434 $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("SupplierBills"), $langs->transnoentitiesnoconv("ListOfTemplates"));
2435 if (!getDolGlobalString('INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE')) {
2436 $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name'));
2437 }
2438 print info_admin($text, 0, 0, '0', 'opacitymedium').'<br>';
2439 }
2440
2441 print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">';
2442 print '<input type="hidden" name="token" value="'.newToken().'">';
2443 print '<input type="hidden" name="action" value="add">';
2444 print '<input type="hidden" name="changecompany" value="0">'; // will be set to 1 by javascript so we know post is done after a company change
2445
2446 if (!empty($societe->id) && $societe->id > 0) {
2447 print '<input type="hidden" name="socid" value="'.$societe->id.'">'."\n";
2448 }
2449 print '<input type="hidden" name="origin" value="'.$origin.'">';
2450 print '<input type="hidden" name="originid" value="'.$originid.'">';
2451 if (!empty($currency_tx)) {
2452 print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
2453 }
2454 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
2455
2456 print dol_get_fiche_head();
2457
2458 // Call Hook tabContentCreateSupplierInvoice
2459 $parameters = array();
2460 // Note that $action and $object may be modified by hook
2461 $reshook = $hookmanager->executeHooks('tabContentCreateSupplierInvoice', $parameters, $object, $action);
2462 if (empty($reshook)) {
2463 print '<table class="border centpercent">';
2464
2465 // Ref
2466 //print '<tr><td class="titlefieldcreate">'.$langs->trans('Ref').'</td><td>'.$langs->trans('Draft').'</td></tr>';
2467
2468 $exampletemplateinvoice = new FactureFournisseurRec($db);
2469 $invoice_predefined = new FactureFournisseurRec($db);
2470 if (empty($origin) && empty($originid) && $fac_recid > 0) {
2471 $invoice_predefined->fetch($fac_recid);
2472 }
2473
2474 // Third party
2475 print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>';
2476 print '<td>';
2477
2478 if (!empty($societe->id) && $societe->id > 0 && ($fac_recid <= 0 || !empty($invoice_predefined->frequency))) {
2479 $absolute_discount = $societe->getAvailableDiscounts(null, '', 0, 1);
2480 print $societe->getNomUrl(1, 'supplier');
2481 print '<input type="hidden" name="socid" value="'.$societe->id.'">';
2482 } else {
2483 $filter = '((s.fournisseur:=:1) AND (s.status:=:1))';
2484 print img_picto('', 'company', 'class="pictofixedwidth"').$form->select_company(empty($societe->id) ? 0 : $societe->id, 'socid', $filter, 'SelectThirdParty', 1, 0, array(), 0, 'minwidth175 widthcentpercentminusxx maxwidth500');
2485 // reload page to retrieve supplier information
2486 if (!getDolGlobalString('RELOAD_PAGE_ON_SUPPLIER_CHANGE_DISABLED')) {
2487 print '<script type="text/javascript">
2488 $(document).ready(function() {
2489 $("#socid").change(function() {
2490 console.log("We have changed the company - Reload page");
2491 // reload page
2492 $("input[name=action]").val("create");
2493 $("input[name=changecompany]").val("1");
2494 $("form[name=add]").submit();
2495 });
2496 });
2497 </script>';
2498 }
2499 if ($fac_recid <= 0) {
2500 print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=0&fournisseur=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
2501 }
2502 }
2503 print '</td></tr>';
2504
2505 // Overwrite some values if creation of invoice is from a predefined invoice
2506 if (empty($origin) && empty($originid) && $fac_recid > 0) {
2507 $invoice_predefined->fetch($fac_recid);
2508
2509 $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
2510 if (empty($projectid)) {
2511 $projectid = $invoice_predefined->fk_project;
2512 }
2513 $cond_reglement_id = $invoice_predefined->cond_reglement_id;
2514 $mode_reglement_id = $invoice_predefined->mode_reglement_id;
2515 $fk_account = $invoice_predefined->fk_account;
2516 $note_public = $invoice_predefined->note_public;
2517 $note_private = $invoice_predefined->note_private;
2518
2519 if (!empty($invoice_predefined->multicurrency_code)) {
2520 $currency_code = $invoice_predefined->multicurrency_code;
2521 }
2522 if (!empty($invoice_predefined->multicurrency_tx)) {
2523 $currency_tx = $invoice_predefined->multicurrency_tx;
2524 }
2525
2526 $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc';
2527 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_rec as r';
2528 $sql .= ' WHERE r.fk_soc = '. (int) $invoice_predefined->socid;
2529
2530 $resql = $db->query($sql);
2531 if ($resql) {
2532 $num = $db->num_rows($resql);
2533 $i = 0;
2534
2535 if ($num > 0) {
2536 print '<tr><td>'.$langs->trans('CreateFromRepeatableInvoice').'</td><td>';
2537 //print '<input type="hidden" name="fac_rec" id="fac_rec" value="'.$fac_recid.'">';
2538 print '<select class="flat" id="fac_rec" name="fac_rec">'; // We may want to change the template to use
2539 print '<option value="0" selected></option>';
2540 while ($i < $num) {
2541 $objp = $db->fetch_object($resql);
2542 print '<option value="'.$objp->rowid.'"';
2543 if ($fac_recid == $objp->rowid) {
2544 print ' selected';
2545 $exampletemplateinvoice->fetch($fac_recid);
2546 }
2547 print '>'.$objp->title.' ('.price($objp->total_ttc).' '.$langs->trans("TTC").')</option>';
2548 $i++;
2549 }
2550 print '</select>';
2551 // Option to reload page to retrieve customer information. Note, this clear other input
2552 if (!getDolGlobalString('RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED')) {
2553 print '<script type="text/javascript">
2554 $(document).ready(function() {
2555 $("#fac_rec").change(function() {
2556 console.log("We have changed the template invoice - Reload page");
2557 // reload page
2558 $("input[name=action]").val("create");
2559 $("form[name=add]").submit();
2560 });
2561 });
2562 </script>';
2563 }
2564 print '</td></tr>';
2565 }
2566 $db->free($resql);
2567 } else {
2569 }
2570 }
2571
2572 print '<tr><td class="tdtop fieldrequired">'.$langs->trans('Type').'</td><td>';
2573
2574 print '<div class="tagtable">'."\n";
2575
2576 // Standard invoice
2577 print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
2578 $tmp = '<input type="radio" id="radio_standard" name="type" value="0"'.(GETPOSTINT('type') ? '' : 'checked').'> ';
2579 $desc = $form->textwithpicto($tmp.'<label for="radio_standard">'.$langs->trans("InvoiceStandardAsk").'</label>', $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3);
2580 print $desc;
2581 print '</div></div>';
2582
2583 if (empty($origin) || (($origin == 'supplier_proposal' || $origin == 'order_supplier' || $origin == 'reception') && !empty($originid))) {
2584 // Deposit - Down payment
2585 if (!getDolGlobalString('INVOICE_DISABLE_DEPOSIT')) {
2586 print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
2587 $tmp = '<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOSTINT('type') == 3 ? ' checked' : '') . '> ';
2588 print '<script type="text/javascript">
2589 jQuery(document).ready(function() {
2590 jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
2591 jQuery("#radio_standard").prop("checked", true);
2592 });
2593 jQuery("#typedeposit, #valuedeposit").click(function() {
2594 jQuery("#radio_deposit").prop("checked", true);
2595 });
2596 jQuery("#typedeposit").change(function() {
2597 console.log("We change type of down payment");
2598 jQuery("#radio_deposit").prop("checked", true);
2599 setRadioForTypeOfInvoice();
2600 });
2601 jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_template").change(function() {
2602 setRadioForTypeOfInvoice();
2603 });
2604 function setRadioForTypeOfInvoice() {
2605 console.log("Change radio");
2606 if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
2607 jQuery(".checkforselect").prop("disabled", true);
2608 jQuery(".checkforselect").prop("checked", false);
2609 } else {
2610 jQuery(".checkforselect").prop("disabled", false);
2611 jQuery(".checkforselect").prop("checked", true);
2612 }
2613 }
2614 });
2615 </script>';
2616
2617 $tmp = $tmp.'<label for="radio_deposit" >'.$langs->trans("InvoiceDeposit").'</label>';
2618 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
2619 $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3);
2620 print '<table class="nobordernopadding"><tr>';
2621 print '<td>';
2622 print $desc;
2623 print '</td>';
2624 if ($origin == 'supplier_proposal' || $origin == 'order_supplier' || $origin == 'reception') {
2625 print '<td class="nowrap" style="padding-left: 15px">';
2626 $arraylist = array(
2627 'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
2628 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
2629 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
2630 );
2631 $typedeposit = GETPOST('typedeposit', 'aZ09');
2632 $valuedeposit = GETPOST('valuedeposit', 'int');
2633 $deposit_percent = null;
2634 if ($origin == 'reception') {
2635 // try to get from source of reception (supplier order)
2636 if (!isset($objectsrc->origin_object)) {
2637 $objectsrc->fetch_origin();
2638 }
2639 if (!empty($objectsrc->origin_object)) {
2640 $deposit_percent = $objectsrc->origin_object->deposit_percent;
2641 }
2642 } elseif (!empty($objectsrc->deposit_percent)) {
2643 $deposit_percent = $objectsrc->deposit_percent;
2644 }
2645 if (empty($typedeposit) && !empty($deposit_percent)) {
2646 $origin_payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $objectsrc->cond_reglement_id);
2647 if (!empty($origin_payment_conditions_deposit_percent)) {
2648 $typedeposit = 'variable';
2649 }
2650 }
2651 if (empty($valuedeposit) && $typedeposit == 'variable' && !empty($deposit_percent)) {
2652 $valuedeposit = $deposit_percent;
2653 }
2654 print $form->selectarray('typedeposit', $arraylist, $typedeposit, 0, 0, 0, '', 1);
2655 print '</td>';
2656 print '<td class="nowrap" style="padding-left: 5px">';
2657 print '<span class="opacitymedium paddingleft">'.$langs->trans("AmountOrPercent").'</span><input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="' . $valuedeposit . '"/>';
2658 print '</td>';
2659 }
2660 print '</tr></table>';
2661
2662 print '</div></div>';
2663 }
2664 }
2665
2666 /* Not yet supported for supplier
2667 if ($societe->id > 0)
2668 {
2669 // Replacement
2670 if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT))
2671 {
2672 // Type invoice
2673 $facids = $facturestatic->list_replacable_supplier_invoices($societe->id);
2674 if ($facids < 0) {
2675 dol_print_error($db, $facturestatic->error, $facturestatic->errors);
2676 exit();
2677 }
2678 $options = "";
2679 foreach ($facids as $facparam)
2680 {
2681 $options .= '<option value="' . $facparam ['id'] . '"';
2682 if ($facparam ['id'] == GETPOST('fac_replacement') {
2683 $options .= ' selected';
2684 }
2685 $options .= '>' . $facparam ['ref'];
2686 $options .= ' (' . $facturestatic->LibStatut(0, $facparam ['status']) . ')';
2687 $options .= '</option>';
2688 }
2689
2690 print '<!-- replacement line -->';
2691 print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
2692 $tmp='<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOSTINT('type') == 1 ? ' checked' : '');
2693 if (! $options) $tmp.=' disabled';
2694 $tmp.='> ';
2695 print '<script type="text/javascript">
2696 jQuery(document).ready(function() {
2697 jQuery("#fac_replacement").change(function() {
2698 jQuery("#radio_replacement").prop("checked", true);
2699 });
2700 });
2701 </script>';
2702 $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' ';
2703 $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
2704 if (! $options)
2705 $text .= ' disabled';
2706 $text .= '>';
2707 if ($options) {
2708 $text .= '<option value="-1">&nbsp;</option>';
2709 $text .= $options;
2710 } else {
2711 $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
2712 }
2713 $text .= '</select>';
2714 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
2715 print $desc;
2716 print '</div></div>';
2717 }
2718 }
2719 else
2720 {
2721 print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
2722 $tmp='<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
2723 $text = $tmp.$langs->trans("InvoiceReplacement") . ' ';
2724 $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') ';
2725 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
2726 print $desc;
2727 print '</div></div>';
2728 }
2729 */
2730
2731 if (empty($origin)) {
2732 if (!empty($societe->id) && $societe->id > 0) {
2733 // Credit note
2734 if (!getDolGlobalString('INVOICE_DISABLE_CREDIT_NOTE')) {
2735 // Show link for credit note
2736 $facids = $facturestatic->list_qualified_avoir_supplier_invoices($societe->id);
2737 if ($facids < 0) {
2738 dol_print_error($db, $facturestatic->error, $facturestatic->errors);
2739 exit;
2740 }
2741 $optionsav = "";
2742 $newinvoice_static = new FactureFournisseur($db);
2743 foreach ($facids as $key => $valarray) {
2744 $newinvoice_static->id = $key;
2745 $newinvoice_static->ref = $valarray ['ref'];
2746 $newinvoice_static->status = $valarray ['status'];
2747 $newinvoice_static->statut = $valarray ['status'];
2748 $newinvoice_static->type = $valarray ['type'];
2749 $newinvoice_static->paid = $valarray ['paye'];
2750 $newinvoice_static->paye = $valarray ['paye'];
2751
2752 $optionsav .= '<option value="'.$key.'"';
2753 if ($key == GETPOSTINT('fac_avoir')) {
2754 $optionsav .= ' selected';
2755 // pre-fill extra fields with selected source invoice
2756 $newinvoice_static->fetch_optionals($key);
2757 $object->array_options = $newinvoice_static->array_options;
2758 }
2759 $optionsav .= '>';
2760 $optionsav .= $newinvoice_static->ref;
2761 $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray ['paymentornot']).')';
2762 $optionsav .= '</option>';
2763 }
2764
2765 print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
2766 $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOSTINT('type') == 2 ? ' checked' : '');
2767 if (!$optionsav && !getDolGlobalString('INVOICE_CREDIT_NOTE_STANDALONE')) {
2768 $tmp .= ' disabled';
2769 }
2770 $tmp .= '> ';
2771 // Show credit note options only if we checked credit note
2772 print '<script type="text/javascript">
2773 jQuery(document).ready(function() {
2774 if (! jQuery("#radio_creditnote").is(":checked"))
2775 {
2776 jQuery("#credit_note_options").hide();
2777 }
2778 jQuery("#radio_creditnote").click(function() {
2779 jQuery("#credit_note_options").show();
2780 });
2781 jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
2782 jQuery("#credit_note_options").hide();
2783 });
2784 });
2785 </script>';
2786 $text = $tmp.'<label for="radio_creditnote">'.$langs->transnoentities("InvoiceAvoirAsk").'</label> ';
2787 // $text.='<input type="text" value="">';
2788 $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
2789 if (!$optionsav) {
2790 $text .= ' disabled';
2791 }
2792 $text .= '>';
2793 if ($optionsav) {
2794 $text .= '<option value="-1"></option>';
2795 $text .= $optionsav;
2796 } else {
2797 $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
2798 }
2799 $text .= '</select>';
2800 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
2801 print $desc;
2802
2803 print '<div id="credit_note_options" class="clearboth">';
2804 print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithPaymentRestAmount\').removeAttr(\'checked\'); }" '.(GETPOSTINT('invoiceAvoirWithLines') > 0 ? 'checked' : '').' /> ';
2805 print '<label for="invoiceAvoirWithLines">'.$langs->trans('invoiceAvoirWithLines')."</label>";
2806 print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithLines\').removeAttr(\'checked\'); }" '.(GETPOSTINT('invoiceAvoirWithPaymentRestAmount') > 0 ? 'checked' : '').' /> ';
2807 print '<label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
2808 print '</div>';
2809
2810 print '</div></div>';
2811 }
2812 } else {
2813 print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
2814 if (!getDolGlobalString('INVOICE_CREDIT_NOTE_STANDALONE')) {
2815 $tmp = '<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
2816 } else {
2817 $tmp = '<input type="radio" name="type" id="radio_creditnote" value="2"> ';
2818 }
2819 $text = $tmp.$langs->trans("InvoiceAvoir").' ';
2820 $text .= '<span class="opacitymedium">('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").')</span> ';
2821 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
2822 print $desc;
2823 print '</div></div>'."\n";
2824 }
2825 }
2826
2827 print '</div><br>';
2828
2829 print '</td></tr>';
2830
2831
2832 // Ref supplier
2833 print '<tr><td class="fieldrequired">';
2834 print $form->textwithpicto($langs->trans('RefSupplierBill'), $langs->trans("RefOfOnVendorSide", $langs->trans("SupplierBill"))).'</td><td>';
2835 print '<input name="ref_supplier" value="'.(GETPOSTISSET('ref_supplier') ? GETPOST('ref_supplier') : (!empty($objectsrc->ref_supplier) ? $objectsrc->ref_supplier : '')).'" type="text" spellcheck="false"';
2836 if (!empty($societe->id) && $societe->id > 0) {
2837 print ' autofocus';
2838 }
2839 print '></td>';
2840 print '</tr>';
2841
2842
2843 // Invoice Subtype
2844 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED')) {
2845 print '<tr><td class="fieldrequired">'.$langs->trans('InvoiceSubtype').'</td><td colspan="2">';
2846 print $form->getSelectInvoiceSubtype(GETPOSTINT('subtype'), 'subtype', 1, 0, '');
2847 print '</td></tr>';
2848 }
2849
2850 if (!empty($societe->id) && $societe->id > 0) {
2851 // Discounts for third party
2852 print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
2853
2854 $thirdparty = $societe;
2855 $discount_type = 1;
2856 $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$societe->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid'));
2857 include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
2858
2859 print '</td></tr>';
2860 }
2861
2862 // Label
2863 print '<tr><td>'.$langs->trans('Label').'</td><td><input class="minwidth300" name="label" value="'.dol_escape_htmltag(GETPOST('label')).'" type="text"></td></tr>';
2864
2865
2866 // Date invoice
2867 print '<tr><td class="fieldrequired">'.$langs->trans('DateInvoice').'</td><td>';
2868 print img_picto('', 'action', 'class="pictofixedwidth"');
2869 print $form->selectDate($dateinvoice ? (int) $dateinvoice : '', '', 0, 0, 0, "add", 1, 1);
2870 print '</td></tr>';
2871
2872 // Date point of tax
2873 if (getDolGlobalString('INVOICE_POINTOFTAX_DATE')) {
2874 print '<tr><td class="fieldrequired">'.$langs->trans('DatePointOfTax').'</td><td>';
2875 print img_picto('', 'action', 'class="pictofixedwidth"');
2876 print $form->selectDate($date_pointoftax ? $date_pointoftax : -1, 'date_pointoftax', 0, 0, 0, "add", 1, 1);
2877 print '</td></tr>';
2878 }
2879
2880 // Payment term
2881 print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
2882 print img_picto('', 'payment', 'class="pictofixedwidth"');
2883 print $form->getSelectConditionsPaiements($cond_reglement_id, 'cond_reglement_id', -1, 1, 0, 'maxwidth200 widthcentpercentminusx');
2884 print '</td></tr>';
2885
2886 // Due date
2887 print '<tr><td>'.$langs->trans('DateMaxPayment').'</td><td>';
2888 print img_picto('', 'action', 'class="pictofixedwidth"');
2889 print $form->selectDate($datedue, 'ech', 0, 0, 0, "add", 1, 1);
2890 print '</td></tr>';
2891
2892 // Payment mode
2893 print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>';
2894 print img_picto('', 'bank', 'class="pictofixedwidth"');
2895 $form->select_types_paiements((string) $mode_reglement_id, 'mode_reglement_id', 'DBIT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx');
2896 print '</td></tr>';
2897
2898 // Bank Account
2899 if (isModEnabled("bank")) {
2900 print '<tr><td>'.$langs->trans('BankAccount').'</td><td>';
2901 // when bank account is empty (means not override by payment mode form a other object, like third-party), try to use default value
2902 print img_picto('', 'bank_account', 'class="pictofixedwidth"').$form->select_comptes((int) $fk_account, 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
2903 print '</td></tr>';
2904 }
2905
2906 // Project
2907 if (isModEnabled('project')) {
2908 $formproject = new FormProjets($db);
2909
2910 $langs->load('projects');
2911 print '<tr><td>'.$langs->trans('Project').'</td><td>';
2912 print img_picto('', 'project', 'class="pictofixedwidth"').$formproject->select_projects((!getDolGlobalString('PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS') ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
2913 print ' <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.(!empty($soc->id) ? $soc->id : 0).'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.(!empty($soc->id) ? $soc->id : 0).($fac_recid > 0 ? '&fac_rec='.$fac_recid : '')).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
2914 print '</td></tr>';
2915 }
2916
2917 // Incoterms
2918 if (isModEnabled('incoterm')) {
2919 print '<tr>';
2920 print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->label_incoterms) ? $objectsrc->label_incoterms : '', 1).'</label></td>';
2921 print '<td colspan="3" class="maxwidthonsmartphone">';
2922 print img_picto('', 'incoterm', 'class="pictofixedwidth"');
2923 print $form->select_incoterms(GETPOSTISSET('incoterm_id') ? GETPOST('incoterm_id', 'alphanohtml') : (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), GETPOSTISSET('location_incoterms') ? GETPOST('location_incoterms', 'alphanohtml') : (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : ''));
2924 print '</td></tr>';
2925 }
2926
2927 // Vat reverse-charge by default
2928 if (getDolGlobalString('ACCOUNTING_FORCE_ENABLE_VAT_REVERSE_CHARGE')) {
2929 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
2930 print '<tr><td>' . $langs->trans('VATReverseCharge') . '</td><td>';
2931 // Try to propose to use VAT reverse charge even if the VAT reverse charge is not activated in the supplier card, if this corresponds to the context of use, the activation is proposed
2932 if (GETPOSTISSET('vat_reverse_charge')) { // Check if form was submitted previously
2933 $vat_reverse_charge = (GETPOST('vat_reverse_charge', 'alpha') == 'on' || GETPOST('vat_reverse_charge', 'alpha') == '1') ? 1 : 0;
2934 } elseif ($vat_reverse_charge == 1 || $societe->vat_reverse_charge == 1 || ($societe->country_code != $mysoc->country_code && isInEEC($mysoc) && isInEEC($societe) && !empty($societe->tva_intra))) {
2935 $vat_reverse_charge = 1;
2936 } else {
2937 $vat_reverse_charge = 0;
2938 }
2939
2940 print '<input type="checkbox" name="vat_reverse_charge"'. (!empty($vat_reverse_charge) ? ' checked ' : '') . '>';
2941 print '</td></tr>';
2942 }
2943
2944 // Multicurrency
2945 if (isModEnabled("multicurrency")) {
2946 print '<tr>';
2947 print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
2948 print '<td class="maxwidthonsmartphone">';
2949 print img_picto('', 'currency', 'class="pictofixedwidth"');
2950 $used_currency_code = $currency_code;
2951 if (!GETPOST('changecompany')) {
2952 $used_currency_code = GETPOSTISSET('multicurrency_code') ? GETPOST('multicurrency_code', 'alpha') : $currency_code;
2953 }
2954 print $form->selectMultiCurrency($used_currency_code, 'multicurrency_code');
2955 print '</td></tr>';
2956 }
2957
2958 // Help of substitution key
2959 $htmltext = '';
2960 if ($fac_recid > 0) {
2961 $dateexample = $dateinvoice;
2962 if (empty($dateexample)) {
2963 $dateexample = dol_now();
2964 }
2965 $substitutionarray = array(
2966 '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')',
2967 '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')',
2968 '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m').')',
2969 '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%m').')',
2970 '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m').')',
2971 '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B').')',
2972 '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%B').')',
2973 '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')',
2974 '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y').')',
2975 '__INVOICE_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')',
2976 '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y').')'
2977 );
2978
2979 $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
2980 foreach ($substitutionarray as $key => $val) {
2981 $htmltext .= $key.' = '.$langs->trans($val).'<br>';
2982 }
2983 $htmltext .= '</i>';
2984 }
2985
2986 // Intracomm report
2987 if (isModEnabled('intracommreport')) {
2988 $langs->loadLangs(array("intracommreport"));
2989 print '<!-- If module intracomm on -->'."\n";
2990 print '<tr><td>'.$langs->trans('IntracommReportTransportMode').'</td><td>';
2991 $form->selectTransportMode(GETPOSTISSET('transport_mode_id') ? GETPOST('transport_mode_id') : $transport_mode_id, 'transport_mode_id');
2992 print '</td></tr>';
2993 }
2994
2995 if (empty($reshook)) {
2996 print $object->showOptionals($extrafields, 'create');
2997 }
2998
2999 // Categories
3000 if (isModEnabled("category")) {
3001 print '<tr><td>'.$langs->trans("Categories").'</td><td colspan="3">';
3002 print $form->selectCategories(Categorie::TYPE_SUPPLIER_INVOICE, 'categories', $object);
3003 print "</td></tr>";
3004 }
3005
3006 // Public note
3007 print '<tr><td>'.$langs->trans('NotePublic').'</td>';
3008 print '<td>';
3009 $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $note_public), '', 80, 'dolibarr_notes', 'In', false, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PUBLIC') ? 0 : 1, ROWS_3, '90%');
3010 print $doleditor->Create(1);
3011 print '</td>';
3012 // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
3013 print '</tr>';
3014
3015 // Private note
3016 print '<tr><td>'.$langs->trans('NotePrivate').'</td>';
3017 print '<td>';
3018 $doleditor = new DolEditor('note_private', (GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $note_private), '', 80, 'dolibarr_notes', 'In', false, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PRIVATE') ? 0 : 1, ROWS_3, '90%');
3019 print $doleditor->Create(1);
3020 print '</td>';
3021 // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
3022 print '</tr>';
3023
3024
3025 if (!empty($objectsrc) && $classname !== null) {
3026 print "\n<!-- ".$classname." info -->";
3027 print "\n";
3028 print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
3029 print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
3030 print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
3031 print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
3032 print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
3033
3034 $txt = $langs->trans($classname);
3035 if ($classname == 'CommandeFournisseur') {
3036 $langs->load('orders');
3037 $txt = $langs->trans("SupplierOrder");
3038 }
3039 print '<tr><td>'.$txt.'</td><td>'.$objectsrc->getNomUrl(1);
3040 // We check if Origin document (id and type is known) has already at least one invoice attached to it
3041 $objectsrc->fetchObjectLinked($originid, $origin, null, 'invoice_supplier');
3042
3043 if (isset($objectsrc->linkedObjects['invoice_supplier'])) {
3044 $invoice_supplier = $objectsrc->linkedObjects['invoice_supplier'];
3045 } else {
3046 $invoice_supplier = [];
3047 }
3048 '@phan-var-force null|FactureFournisseur[] $invoice_supplier';
3049
3050 // count function need a array as argument (Note: the array must implement Countable too)
3051 if (is_array($invoice_supplier)) {
3052 $cntinvoice = count($invoice_supplier);
3053
3054 if ($cntinvoice >= 1) {
3055 setEventMessages('WarningBillExist', null, 'warnings');
3056 echo ' ('.$langs->trans('LatestRelatedBill').end($invoice_supplier)->getNomUrl(1).')';
3057 }
3058 }
3059
3060 print '</td></tr>';
3061 print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>';
3062 print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>";
3063 if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { //Localtax1
3064 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>";
3065 }
3066
3067 if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { //Localtax2
3068 print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>";
3069 }
3070 print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>";
3071
3072 if (isModEnabled("multicurrency")) {
3073 print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht, 0, $langs, 1, -1, -1, $objectsrc->multicurrency_code).'</td></tr>';
3074 print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva, 0, $langs, 1, -1, -1, $objectsrc->multicurrency_code)."</td></tr>";
3075 print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc, 0, $langs, 1, -1, -1, $objectsrc->multicurrency_code)."</td></tr>";
3076 }
3077 }
3078
3079 // Other options
3080 $parameters = array();
3081 $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3082 print $hookmanager->resPrint;
3083
3084
3085 print "</table>\n";
3086 }
3087
3088 print dol_get_fiche_end();
3089
3090 print $form->buttonsSaveCancel("CreateDraft");
3091
3092 // Show origin lines
3093 if (!empty($objectsrc)) {
3094 print '<br>';
3095
3096 $title = $langs->trans('ProductsAndServices');
3097 print load_fiche_titre($title);
3098
3099 print '<div class="div-table-responsive-no-min">';
3100 print '<table class="noborder centpercent">';
3101
3102 $objectsrc->printOriginLinesList('', $selectedLines);
3103
3104 print '</table>';
3105 print '</div>';
3106 }
3107
3108 print "</form>\n";
3109} else {
3110 if ($id > 0 || !empty($ref)) {
3111 //
3112 // View or edit mode
3113 //
3114 $now = dol_now();
3115
3116 $result = $object->fetch($id, $ref);
3117 if ($result <= 0) {
3118 recordNotFound('', 0);
3119 }
3120
3121 $result = $object->fetch_thirdparty();
3122 if ($result < 0) {
3123 dol_print_error($db, $object->error, $object->errors);
3124 exit;
3125 }
3126
3127 $societe = $object->thirdparty;
3128
3129 $totalpaid = $object->getSommePaiement();
3130 $totalcreditnotes = $object->getSumCreditNotesUsed();
3131 $totaldeposits = $object->getSumDepositsUsed();
3132 // print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
3133 // selleruserrevenuestamp=".$selleruserevenustamp;
3134
3135 // We can also use bcadd to avoid pb with floating points
3136 // For example print 239.2 - 229.3 - 9.9; does not return 0.
3137 // $resteapayer=bcadd($object->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
3138 // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
3139 $resteapayer = price2num($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
3140
3141 // Multicurrency
3142 $multicurrency_resteapayer = 0;
3143 if (isModEnabled("multicurrency")) {
3144 $multicurrency_totalpaid = $object->getSommePaiement(1);
3145 $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
3146 $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
3147 $multicurrency_resteapayer = price2num($object->multicurrency_total_ttc - $multicurrency_totalpaid - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits, 'MT');
3148 // Code to fix case of corrupted data
3149 // TODO We should not need this. Also data comes from not reliable value of $object->multicurrency_total_ttc that may be wrong if it was
3150 // calculated by summing lines that were in a currency for some of them and into another for others (lines from discount/down payment into another currency for example)
3151 if ($resteapayer == 0 && $multicurrency_resteapayer != 0 && $object->multicurrency_code != $conf->currency) {
3152 $resteapayer = price2num((float) $multicurrency_resteapayer / $object->multicurrency_tx, 'MT');
3153 }
3154 }
3155
3156 if ($object->paid) {
3157 $resteapayer = 0;
3158 }
3159 $resteapayeraffiche = $resteapayer;
3160
3161 if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) { // Never use this
3162 $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
3163 $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
3164 } else {
3165 $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')";
3166 $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')";
3167 }
3168
3169 $absolute_discount = $societe->getAvailableDiscounts(null, $filterabsolutediscount, 0, 1);
3170 $absolute_creditnote = $societe->getAvailableDiscounts(null, $filtercreditnote, 0, 1);
3171 $absolute_discount = price2num($absolute_discount, 'MT');
3172 $absolute_creditnote = price2num($absolute_creditnote, 'MT');
3173
3174 // View card
3175
3176 $objectidnext = $object->getIdReplacingInvoice();
3177
3178 $head = facturefourn_prepare_head($object);
3179 $titre = $langs->trans('SupplierInvoice');
3180
3181 print dol_get_fiche_head($head, 'card', $titre, -1, 'supplier_invoice', 0, '', '', 0, '', 1);
3182
3183 $formconfirm = '';
3184
3185 // Confirmation de la conversion de l'avoir en reduc
3186 if ($action == 'converttoreduc') {
3187 $type_fac = '';
3189 $type_fac = 'ExcessPaid';
3190 } elseif ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
3191 $type_fac = 'CreditNote';
3192 } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) {
3193 $type_fac = 'Deposit';
3194 }
3195 $text = $langs->trans('ConfirmConvertToReducSupplier', strtolower($langs->transnoentities($type_fac)));
3196 $text .= '<br>'.$langs->trans('ConfirmConvertToReducSupplier2');
3197 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
3198 }
3199
3200 // Clone confirmation
3201 if ($action == 'clone') {
3202 // Create an array for form
3203 $formquestion = array(
3204 array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplierBill"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier),
3205 array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
3206 );
3207 // Ask confirmation to clone
3208 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 0);
3209 }
3210
3211 // Confirmation of validation
3212 if ($action == 'valid') {
3213 // We check if number is temporary number
3214 if (preg_match('/^[\‍(]?PROV/i', $object->ref) || empty($object->ref)) {
3215 // empty should not happened, but when it occurs, the test save life
3216 $numref = $object->getNextNumRef($societe);
3217 } else {
3218 $numref = (string) $object->ref;
3219 }
3220
3221 if ($numref < 0) {
3222 setEventMessages($object->error, $object->errors, 'errors');
3223 $action = '';
3224 } else {
3225 $text = $langs->trans('ConfirmValidateBill', $numref);
3226 /*if (isModEnabled('notification'))
3227 {
3228 require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
3229 $notify=new Notify($db);
3230 $text.='<br>';
3231 $text.=$notify->confirmMessage('BILL_SUPPLIER_VALIDATE',$object->socid, $object);
3232 }*/
3233 $formquestion = array();
3234
3235 $qualified_for_stock_change = 0;
3236 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
3237 $qualified_for_stock_change = $object->hasProductsOrServices(2);
3238 } else {
3239 $qualified_for_stock_change = $object->hasProductsOrServices(1);
3240 }
3241
3242 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $qualified_for_stock_change) {
3243 $langs->load("stocks");
3244 require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
3245 $formproduct = new FormProduct($db);
3246 $warehouse = new Entrepot($db);
3247 $warehouse_array = $warehouse->list_array();
3248 if (count($warehouse_array) == 1) {
3249 $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
3250 $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
3251 } else {
3252 $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
3253 $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
3254 }
3255 $formquestion = array(
3256 array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
3257 );
3258 }
3259
3260 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1);
3261 }
3262 }
3263
3264 // Confirmation edit (back to draft)
3265 if ($action == 'edit') {
3266 $formquestion = array();
3267
3268 $qualified_for_stock_change = 0;
3269 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
3270 $qualified_for_stock_change = $object->hasProductsOrServices(2);
3271 } else {
3272 $qualified_for_stock_change = $object->hasProductsOrServices(1);
3273 }
3274 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $qualified_for_stock_change) {
3275 $langs->load("stocks");
3276 require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
3277 $formproduct = new FormProduct($db);
3278 $warehouse = new Entrepot($db);
3279 $warehouse_array = $warehouse->list_array();
3280 if (count($warehouse_array) == 1) {
3281 $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
3282 $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
3283 } else {
3284 $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
3285 $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
3286 }
3287 $formquestion = array(
3288 array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
3289 );
3290 }
3291 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1);
3292 }
3293
3294 // Confirmation set paid
3295 if ($action == 'paid' && ($resteapayer <= 0 || (getDolGlobalString('SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') && $resteapayer == $object->total_ttc))) {
3296 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1);
3297 }
3298
3299 if ($action == 'paid' && $resteapayer > 0 && (!getDolGlobalString('SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') || $resteapayer != $object->total_ttc)) {
3300 $close = array();
3301 // Code
3302 $i = 0;
3303 $close[$i]['code'] = 'discount_vat'; // escompte
3304 $i++;
3305 $close[$i]['code'] = 'badsupplier';
3306 $i++;
3307 $close[$i]['code'] = 'other';
3308 $i++;
3309 // Help
3310 $i = 0;
3311 $close[$i]['label'] = $langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
3312 $i++;
3313 $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadSupplierDesc");
3314 $i++;
3315 $close[$i]['label'] = $langs->trans("Other");
3316 $i++;
3317 // Text
3318 $i = 0;
3319 $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
3320 $i++;
3321 $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
3322 $i++;
3323 $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("Other"), $close[$i]['label'], 1);
3324 $i++;
3325 // arrayreasons[code]=reason
3326 $arrayreasons = array();
3327 foreach ($close as $key => $val) {
3328 $arrayreasons[$close[$key]['code']] = $close[$key]['reason'];
3329 }
3330
3331 // Create a form table
3332 $formquestion = array('text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"), 0 => array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), 1 => array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
3333 // Incomplete payment. We ask if the reason is discount or other
3334 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 310);
3335 }
3336
3337 // Confirmation of the abandoned classification
3338 if ($action == 'canceled') {
3339 // Code
3340 $close[1]['code'] = 'badsupplier';
3341 $close[2]['code'] = 'abandon';
3342 // Help
3343 $close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadSupplierDesc");
3344 $close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
3345 // Text
3346 $close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadSupplier", $object->ref), $close[1]['label'], 1);
3347 $close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
3348 // arrayreasons
3349 $arrayreasons[$close[1]['code']] = $close[1]['reason'];
3350 $arrayreasons[$close[2]['code']] = $close[2]['reason'];
3351
3352 // Create a form table
3353 $formquestion = array('text' => $langs->trans("ConfirmCancelBillQuestion"), 0 => array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), 1 => array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
3354
3355 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 280);
3356 }
3357
3358 // Confirmation for supplier invoice deletion
3359 if ($action == 'delete') {
3360 $formquestion = array();
3361
3362 $qualified_for_stock_change = 0;
3363 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
3364 $qualified_for_stock_change = $object->hasProductsOrServices(2);
3365 } else {
3366 $qualified_for_stock_change = $object->hasProductsOrServices(1);
3367 }
3368
3369 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $qualified_for_stock_change) {
3370 $langs->load("stocks");
3371 require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
3372 $formproduct = new FormProduct($db);
3373 $warehouse = new Entrepot($db);
3374 $warehouse_array = $warehouse->list_array();
3375
3376 $selectwarehouse = '<span class="questionrevertstock hidden">';
3377 if (count($warehouse_array) == 1) {
3378 $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
3379 $selectwarehouse .= '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
3380 } else {
3381 $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
3382 $selectwarehouse .= $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
3383 }
3384 $selectwarehouse .= '</span>';
3385
3386 $selectyesno = array(0 => $langs->trans('No'), 1 => $langs->trans('Yes'));
3387
3388 print '<script type="text/javascript">
3389 $(document).ready(function() {
3390 $("#revertstock").change(function() {
3391 if(this.value > 0) {
3392 $(".questionrevertstock").removeClass("hidden");
3393 } else {
3394 $(".questionrevertstock").addClass("hidden");
3395 }
3396 });
3397 });
3398 </script>';
3399
3400 $formquestion = array(
3401 array('type' => 'select', 'name' => 'revertstock', 'label' => $langs->trans("RevertProductsToStock"), 'select_show_empty' => 0, 'values' => $selectyesno),
3402 array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $selectwarehouse, 'tdclass' => 'questionrevertstock hidden')
3403 );
3404 }
3405
3406 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', $formquestion, 1, 1);
3407 }
3408 if ($action == 'deletepayment') {
3409 $payment_id = GETPOST('paiement_id');
3410 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1);
3411 }
3412
3413 // Confirmation to delete line
3414 if ($action == 'ask_deleteline') {
3415 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
3416 }
3417
3418 // Subtotal line form
3419 if ($action == 'add_title_line') {
3420 $langs->load('subtotals');
3421 $type = 'title';
3422 $depth_array = $object->getPossibleLevels($langs);
3423 require DOL_DOCUMENT_ROOT . '/core/tpl/subtotal_create.tpl.php';
3424 } elseif ($action == 'add_subtotal_line') {
3425 $langs->load('subtotals');
3426 $type = 'subtotal';
3427 $titles = $object->getPossibleTitles();
3428 require DOL_DOCUMENT_ROOT . '/core/tpl/subtotal_create.tpl.php';
3429 }
3430
3431 // Call Hook formConfirm
3432 $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
3433 $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3434 if (empty($reshook)) {
3435 $formconfirm .= $hookmanager->resPrint;
3436 } elseif ($reshook > 0) {
3437 $formconfirm = $hookmanager->resPrint;
3438 }
3439
3440 // Print form confirm
3441 print $formconfirm;
3442
3443
3444 // Supplier invoice card
3445 $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
3446
3447 $morehtmlref = '<div class="refidno">';
3448 // Ref supplier
3449 $morehtmlref .= $form->editfieldkey("RefSupplierBill", 'ref_supplier', $object->ref_supplier, $object, (int) $usercancreate, 'string', '', 0, 1);
3450 $morehtmlref .= $form->editfieldval("RefSupplierBill", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1);
3451 // Thirdparty
3452 $morehtmlref .= '<br>'.$object->thirdparty->getNomUrl(1, 'supplier');
3453 if (!getDolGlobalString('MAIN_DISABLE_OTHER_LINK') && $object->thirdparty->id > 0) {
3454 $morehtmlref .= ' <div class="inline-block valignmiddle">(<a class="valignmiddle" href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.((int) $object->thirdparty->id).'">'.$langs->trans("OtherBills").'</a>)</div>';
3455 }
3456 // Project
3457 if (isModEnabled('project')) {
3458 $langs->load("projects");
3459 $morehtmlref .= '<br>';
3460 if ($permissiontoadd) {
3461 $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
3462 if ($action != 'classify') {
3463 $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.((int) $object->id).'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
3464 }
3465 $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, (!getDolGlobalString('PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS') ? $object->socid : -1), (string) $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
3466 } else {
3467 if (!empty($object->fk_project)) {
3468 $proj = new Project($db);
3469 $proj->fetch($object->fk_project);
3470 $morehtmlref .= $proj->getNomUrl(1);
3471 if ($proj->title) {
3472 $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
3473 }
3474 }
3475 }
3476 }
3477 $morehtmlref .= '</div>';
3478
3479 $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status
3480
3481 dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
3482
3483 // Call Hook tabContentViewSupplierInvoice
3484 $parameters = array();
3485 // Note that $action and $object may be modified by hook
3486 $reshook = $hookmanager->executeHooks('tabContentViewSupplierInvoice', $parameters, $object, $action);
3487 if (empty($reshook)) {
3488 print '<div class="fichecenter">';
3489 print '<div class="fichehalfleft">';
3490 print '<div class="underbanner clearboth"></div>';
3491
3492 print '<table class="border tableforfield centpercent">';
3493
3494 // Type
3495 print '<tr><td>'.$langs->trans('Type').'</td><td>';
3496 print '<span class="badgeneutral">';
3497 print $object->getLibType();
3498 print '</span>';
3499 if ($object->subtype > 0) {
3500 print ' '.$object->getSubtypeLabel('facture_fourn');
3501 }
3503 $facreplaced = new FactureFournisseur($db);
3504 $facreplaced->fetch($object->fk_facture_source);
3505 print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).'</span>';
3506 }
3508 if ($object->fk_facture_source > 0) {
3509 $facusing = new FactureFournisseur($db);
3510 $facusing->fetch($object->fk_facture_source);
3511 print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).'</span>';
3512 } else {
3513 $langs->load("errors");
3514 print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("WarningCorrectedInvoiceNotFound").'</span>';
3515 }
3516 }
3517
3518 // Retrieve credit note ids
3519 $object->getListIdAvoirFromInvoice();
3520
3521 if (!empty($object->creditnote_ids)) {
3522 $invoicecredits = array();
3523 foreach ($object->creditnote_ids as $invoiceid) {
3524 $creditnote = new FactureFournisseur($db);
3525 $creditnote->fetch($invoiceid);
3526 $invoicecredits[] = $creditnote->getNomUrl(1);
3527 }
3528 print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("InvoiceHasAvoir") . (count($invoicecredits) ? ' ' : '') . implode(',', $invoicecredits);
3529 print '</span>';
3530 }
3531 if (isset($objectidnext) && $objectidnext > 0) {
3532 $facthatreplace = new FactureFournisseur($db);
3533
3534 $facthatreplace->fetch($objectidnext);
3535 print ' <span class="opacitymediumbycolor paddingleft">'.str_replace('{s1}', $facthatreplace->getNomUrl(1), $langs->transnoentities("ReplacedByInvoice", '{s1}')).'</span>';
3536 }
3538 $discount = new DiscountAbsolute($db);
3539 $result = $discount->fetch(0, 0, $object->id);
3540 if ($result > 0) {
3541 print ' <span class="opacitymediumbycolor paddingleft">';
3542 $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}');
3543 $s = str_replace('{s1}', $object->getLibType(1), $s);
3544 $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s);
3545 print $s;
3546 print '</span><br>';
3547 }
3548 }
3549
3550 if ($object->fk_fac_rec_source > 0) {
3551 $tmptemplate = new FactureFournisseurRec($db);
3552 $result = $tmptemplate->fetch($object->fk_fac_rec_source);
3553 if ($result > 0) {
3554 print ' <span class="opacitymediumbycolor paddingleft">';
3555 $link = '<a href="'.DOL_URL_ROOT.'/fourn/facture/card-rec.php?facid='.$tmptemplate->id.'">'.dol_escape_htmltag($tmptemplate->title).'</a>';
3556 $s = $langs->transnoentities("GeneratedFromSupplierTemplate", $link);
3557
3558 print $s;
3559 print '</span>';
3560 }
3561 }
3562 print '</td></tr>';
3563
3564
3565 // Relative and absolute discounts
3566 print '<!-- Discounts -->'."\n";
3567 print '<tr><td>'.$langs->trans('DiscountStillRemaining');
3568 print '</td><td>';
3569
3570 $thirdparty = $societe;
3571 $discount_type = 1;
3572 include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
3573
3574 print '</td></tr>';
3575
3576 // Label
3577 print '<tr>';
3578 print '<td>'.$form->editfieldkey("Label", 'label', $object->label, $object, (int) $usercancreate).'</td>';
3579 print '<td>'.$form->editfieldval("Label", 'label', $object->label, $object, $usercancreate).'</td>';
3580 print '</tr>';
3581
3582 //$form_permission = ($object->status < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0);
3583 $form_permission = ($object->status < FactureFournisseur::STATUS_CLOSED) && $usercancreate;
3584
3585 // Date
3586 print '<tr><td>';
3587 print $form->editfieldkey("DateInvoice", 'datef', (string) $object->date, $object, (int) $form_permission, 'datepicker');
3588 print '</td><td colspan="3">';
3589 print $form->editfieldval("Date", 'datef', $object->date, $object, $form_permission, 'datepicker');
3590 print '</td>';
3591
3592 if (getDolGlobalString('INVOICE_POINTOFTAX_DATE')) {
3593 $pointoftax_form_permission = ($object->status == FactureFournisseur::STATUS_DRAFT) && $usercancreate;
3594 print '<tr><td>';
3595 print $form->editfieldkey("DatePointOfTax", 'date_pointoftax', (string) $object->date_pointoftax, $object, (int) $pointoftax_form_permission, 'datepicker');
3596 print '</td><td colspan="3">';
3597 print $form->editfieldval("DatePointOfTax", 'date_pointoftax', $object->date_pointoftax, $object, $pointoftax_form_permission, 'datepicker');
3598 print '</td></tr>';
3599 }
3600
3601 // Default terms of the settlement
3602 $langs->load('bills');
3603 print '<tr><td class="nowrap">';
3604 print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
3605 print $langs->trans('PaymentConditions');
3606 print '<td>';
3607 if ($action != 'editconditions' && $form_permission) {
3608 print '<td class="right"><a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
3609 }
3610 print '</tr></table>';
3611 print '</td><td>';
3612 if ($action == 'editconditions') {
3613 $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->cond_reglement_id, 'cond_reglement_id');
3614 } else {
3615 $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->cond_reglement_id, 'none');
3616 }
3617 print "</td>";
3618 print '</tr>';
3619
3620 // Due date
3621 print '<tr><td>';
3622 print $form->editfieldkey("DateMaxPayment", 'date_lim_reglement', (string) $object->date_echeance, $object, (int) $form_permission, 'datepicker');
3623 print '</td><td>';
3624 print $form->editfieldval("DateMaxPayment", 'date_lim_reglement', $object->date_echeance, $object, $form_permission, 'datepicker');
3625 if ($action != 'editdate_lim_reglement' && $object->hasDelay()) {
3626 print img_warning($langs->trans('Late'));
3627 }
3628 print '</td>';
3629
3630 // Mode of payment
3631 $langs->load('bills');
3632 print '<tr><td class="nowrap">';
3633 print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
3634 print $langs->trans('PaymentMode');
3635 print '</td>';
3636 if ($action != 'editmode' && $form_permission) {
3637 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
3638 }
3639 print '</tr></table>';
3640 print '</td><td>';
3641 if ($action == 'editmode') {
3642 $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1);
3643 } else {
3644 $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->mode_reglement_id, 'none');
3645 }
3646 print '</td></tr>';
3647
3648 // Bank Account
3649 if (isModEnabled("bank")) {
3650 print '<tr><td class="nowrap">';
3651 print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
3652 print $langs->trans('BankAccount');
3653 print '<td>';
3654 if ($action != 'editbankaccount' && $usercancreate) {
3655 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>';
3656 }
3657 print '</tr></table>';
3658 print '</td><td>';
3659 if ($action == 'editbankaccount') {
3660 $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->fk_account, 'fk_account', 1);
3661 } else {
3662 $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->fk_account, 'none');
3663 }
3664 print "</td>";
3665 print '</tr>';
3666 }
3667
3668 // Vat reverse-charge by default
3669 if (getDolGlobalString('ACCOUNTING_FORCE_ENABLE_VAT_REVERSE_CHARGE')) {
3670 print '<tr><td class="nowrap">';
3671 print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
3672 print $langs->trans('VATReverseCharge');
3673 print '<td>';
3674 if ($action != 'editvatreversecharge' && $usercancreate) {
3675 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editvatreversecharge&amp;token='.newToken().'&amp;id='.$object->id.'">'.img_edit($langs->trans('SetVATReverseCharge'), 1).'</a></td>';
3676 }
3677 print '</tr></table>';
3678 print '</td><td>';
3679 if ($action == 'editvatreversecharge') {
3680 print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
3681 print '<input type="hidden" name="action" value="setvatreversecharge">';
3682 print '<input type="hidden" name="token" value="'.newToken().'">';
3683
3684 print '<input type="checkbox" name="vat_reverse_charge"' . ($object->vat_reverse_charge == '1' ? ' checked ' : '') . '>';
3685
3686 print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
3687 print '</form>';
3688 } else {
3689 print '<input type="checkbox" name="vat_reverse_charge"'. ($object->vat_reverse_charge == '1' ? ' checked ' : '') . ' disabled>';
3690 }
3691 print '</td></tr>';
3692 }
3693
3694 // Incoterms
3695 if (isModEnabled('incoterm')) {
3696 print '<tr><td>';
3697 print '<table width="100%" class="nobordernopadding"><tr><td>';
3698 print $langs->trans('IncotermLabel');
3699 print '<td><td class="right">';
3700 if ($usercancreate) {
3701 print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=editincoterm&token='.newToken().'">'.img_edit().'</a>';
3702 } else {
3703 print '&nbsp;';
3704 }
3705 print '</td></tr></table>';
3706 print '</td>';
3707 print '<td>';
3708 if ($action != 'editincoterm') {
3709 print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
3710 } else {
3711 print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
3712 }
3713 print '</td></tr>';
3714 }
3715
3716 // Intracomm report
3717 if (isModEnabled('intracommreport')) {
3718 $langs->loadLangs(array("intracommreport"));
3719 print '<!-- If module intracomm on -->'."\n";
3720 print '<tr><td>';
3721 print '<table class="nobordernopadding centpercent"><tr><td>';
3722 print $langs->trans('IntracommReportTransportMode');
3723 print '</td>';
3724 if ($action != 'edittransportmode' && ($user->hasRight("fournisseur", "facture", "creer") || $user->hasRight("supplier_invoice", "creer"))) {
3725 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edittransportmode&token='.newToken().'&id='.$object->id.'">'.img_edit().'</a></td>';
3726 }
3727 print '</tr></table>';
3728 print '</td>';
3729 print '<td>';
3730 if ($action == 'edittransportmode') {
3731 $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->transport_mode_id, 'transport_mode_id', 1, 1);
3732 } else {
3733 $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->transport_mode_id, 'none');
3734 }
3735 print '</td></tr>';
3736 }
3737
3738 // Categories
3739 if (isModEnabled('category')) {
3740 print '<tr><td>';
3741 print '<table class="nobordernopadding centpercent"><tr><td>';
3742 print $langs->trans("Categories");
3743 print '<td><td class="right">';
3744 if ($usercancreate) {
3745 print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=edittags&token='.newToken().'">'.img_edit().'</a>';
3746 } else {
3747 print '&nbsp;';
3748 }
3749 print '</td></tr></table>';
3750 print '</td>';
3751 print '<td>';
3752 if ($action == 'edittags') {
3753 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
3754 print '<input type="hidden" name="action" value="settags">';
3755 print '<input type="hidden" name="token" value="'.newToken().'">';
3756 print $form->selectCategories(Categorie::TYPE_SUPPLIER_INVOICE, 'categories', $object);
3757 print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
3758 print '</form>';
3759 } else {
3760 print $form->showCategories($object->id, Categorie::TYPE_SUPPLIER_INVOICE, 1);
3761 }
3762 print "</td></tr>";
3763 }
3764
3765
3766 // Other attributes. Fields from hook formObjectOptions and Extrafields.
3767 $cols = 2;
3768 if ($object->status != $object::STATUS_DRAFT) {
3769 $disableedit = 1;
3770 $disableremove = 1;
3771 }
3772 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
3773
3774 print '</table>';
3775 print '</div>';
3776
3777 print '<div class="fichehalfright">';
3778 print '<div class="underbanner clearboth"></div>';
3779
3780 print '<table class="border tableforfield centpercent">';
3781
3782 include DOL_DOCUMENT_ROOT.'/core/tpl/object_currency_amount.tpl.php';
3783
3784 print '<tr>';
3785 print '<td class="titlefieldmiddle">' . $langs->trans('AmountHT') . '</td>';
3786 print '<td class="nowrap amountcard right">' . price($object->total_ht, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
3787 if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
3788 print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_ht, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
3789 }
3790 print '</tr>';
3791
3792 print '<tr>';
3793 print '<td>' . $langs->trans('AmountVAT') . '</td>';
3794 print '<td class="nowrap amountcard right">';
3795 if (GETPOST('calculationrule')) {
3796 $calculationrule = GETPOST('calculationrule', 'alpha');
3797 } else {
3798 $calculationrule = (!getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER') ? 'totalofround' : 'roundoftotal');
3799 }
3800 if ($calculationrule == 'totalofround') {
3801 $calculationrulenum = 1;
3802 } else {
3803 $calculationrulenum = 2;
3804 }
3805 // Show link for "recalculate"
3806 if ($object->getVentilExportCompta() == 0) {
3807 $s = '<span class="hideonsmartphone opacitymedium">' . $langs->trans("ReCalculate") . ' </span>';
3808 $s .= '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=calculate&token='.newToken().'&calculationrule=totalofround">' . $langs->trans("Mode1") . '</a>';
3809 $s .= ' / ';
3810 $s .= '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=calculate&token='.newToken().'&calculationrule=roundoftotal">' . ($conf->dol_optimize_smallscreen ? "2" : $langs->trans("Mode2")) . '</a>';
3811 print '<div class="inline-block">';
3812 print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc", $calculationrulenum) . '<br>' . $langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('', 'help', 'class="paddingleft paddingright"'), '', 3, '', 0, 'recalculate');
3813 print '&nbsp; &nbsp; &nbsp; &nbsp;';
3814 print '</div>';
3815 }
3816 print '<span class="nowraponall">'.price($object->total_tva, 1, $langs, 0, -1, -1, $conf->currency).'</span>';
3817 print '</td>';
3818 if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
3819 print '<td class="nowraponall amountcard right">' . price($object->multicurrency_total_tva, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
3820 }
3821 print '</tr>';
3822
3823 if ($societe->localtax1_assuj == "1") { //Localtax1
3824 print '<tr>';
3825 print '<td>' . $langs->transcountry("AmountLT1", $societe->country_code) . '</td>';
3826 print '<td class="nowrap amountcard right">' . price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency) . '</td>';
3827 print '</tr>';
3828 }
3829 if ($societe->localtax2_assuj == "1") { //Localtax2
3830 print '<tr>';
3831 print '<td>' . $langs->transcountry("AmountLT2", $societe->country_code) . '</td>';
3832 print '<td class="nowrap amountcard right">' . price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency) . '</td>';
3833 print '</tr>';
3834 }
3835
3836 print '<tr>';
3837 print '<td>' . $langs->trans('AmountTTC') . '</td>';
3838 print '<td class="nowrap amountcard right">' . price($object->total_ttc, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
3839 if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
3840 print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_ttc, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
3841 }
3842 print '</tr>';
3843
3844 print '</table>';
3845
3846
3847 // List of payments already done
3848
3849 $totalpaid = 0;
3850
3851 $sign = 1;
3853 $sign = - 1;
3854 }
3855
3856 $nbrows = 9;
3857 $nbcols = 3;
3858 if (isModEnabled('project')) {
3859 $nbrows++;
3860 }
3861 if (isModEnabled("bank")) {
3862 $nbrows++;
3863 $nbcols++;
3864 }
3865 if (isModEnabled('incoterm')) {
3866 $nbrows++;
3867 }
3868 if (isModEnabled("multicurrency")) {
3869 $nbrows += 5;
3870 }
3871
3872 // Local taxes
3873 if ($societe->localtax1_assuj == "1") {
3874 $nbrows++;
3875 }
3876 if ($societe->localtax2_assuj == "1") {
3877 $nbrows++;
3878 }
3879
3880 $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
3881 $sql .= ' c.id as payment_type, c.code as payment_code,';
3882 $sql .= ' pf.amount,';
3883 $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal';
3884 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p';
3885 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
3886 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
3887 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
3888 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid';
3889 $sql .= ' WHERE pf.fk_facturefourn = '.((int) $object->id);
3890 $sql .= ' ORDER BY p.datep, p.tms';
3891
3892 $result = $db->query($sql);
3893 if ($result) {
3894 $num = $db->num_rows($result);
3895 $i = 0;
3896
3897 print '<div class="div-table-responsive-no-min">';
3898 print '<table class="noborder paymenttable centpercent">';
3899 print '<tr class="liste_titre">';
3900 print '<td class="liste_titre">'.($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
3901 print '<td><span class="hideonsmartphone">'.$langs->trans('Date').'</span></td>';
3902 print '<td><span class="hideonsmartphone">'.$langs->trans('Type').'</span></td>';
3903 if (isModEnabled("bank")) {
3904 print '<td class="right">'.$langs->trans('BankAccount').'</td>';
3905 }
3906 // Action
3907 print '<td></td>';
3908 // Amount
3909 print '<td class="right">'.$langs->trans('Amount').'</td>';
3910 print '</tr>';
3911
3912 if ($num > 0) {
3913 while ($i < $num) {
3914 $objp = $db->fetch_object($result);
3915
3916 $paymentstatic->id = $objp->rowid;
3917 $paymentstatic->datepaye = $db->jdate($objp->dp);
3918 $paymentstatic->ref = ($objp->ref ? $objp->ref : $objp->rowid);
3919 $paymentstatic->num_payment = $objp->num_payment;
3920
3921 $paymentstatic->paiementcode = $objp->payment_code;
3922 $paymentstatic->type_code = $objp->payment_code;
3923 $paymentstatic->type_label = $objp->payment_type;
3924
3925 print '<tr class="oddeven">';
3926 print '<td class="nowraponall">';
3927 print $paymentstatic->getNomUrl(1);
3928 print '</td>';
3929 print '<td>'.dol_print_date($db->jdate($objp->dp), 'day').'</td>';
3930 $s = $form->form_modes_reglement('', $objp->payment_type, 'none', '', 1, 0, '', 1).' '.$objp->num_payment;
3931 print '<td class="tdoverflowmax125" title="'.dol_escape_htmltag($s).'">';
3932 print $s;
3933 print '</td>';
3934 if (isModEnabled("bank")) {
3935 $bankaccountstatic->id = $objp->baid;
3936 $bankaccountstatic->ref = $objp->baref;
3937 $bankaccountstatic->label = $objp->baref;
3938 $bankaccountstatic->number = $objp->banumber;
3939
3940 if (isModEnabled('accounting')) {
3941 $bankaccountstatic->account_number = $objp->account_number;
3942
3943 $accountingjournal = new AccountingJournal($db);
3944 $accountingjournal->fetch($objp->fk_accountancy_journal);
3945 $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
3946 }
3947
3948 print '<td class="right nowraponall">';
3949 if ($objp->baid > 0) {
3950 print $bankaccountstatic->getNomUrl(1, 'transactions');
3951 }
3952 print '</td>';
3953 }
3954 // Delete
3955 print '<td class="center">';
3956 if ($object->status == FactureFournisseur::STATUS_VALIDATED && $object->paid == 0 && $user->socid == 0) {
3957 print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepayment&token='.newToken().'&paiement_id='.$objp->rowid.'">';
3958 print img_delete();
3959 print '</a>';
3960 }
3961 print '</td>';
3962 // Amount
3963 print '<td class="right">'.price($sign * $objp->amount).'</td>';
3964 print '</tr>';
3965 $totalpaid += $objp->amount;
3966 $i++;
3967 }
3968 } else {
3969 print '<tr class="oddeven"><td colspan="'.$nbcols.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td>';
3970 print '<td></td>';
3971 print '<td></td>';
3972 print '</tr>';
3973 }
3974
3975 /*
3976 if ($object->paid == 0)
3977 {
3978 print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('AlreadyPaid').' :</td><td class="right">'.price($totalpaid).'</td><td></td></tr>';
3979 print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($object->total_ttc).'</td><td></td></tr>';
3980
3981 $resteapayer = $object->total_ttc - $totalpaid;
3982
3983 print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('RemainderToPay').' :</td>';
3984 print '<td class="right'.($resteapayer?' amountremaintopay':'').'">'.price($resteapayer).'</td><td></td></tr>';
3985 }
3986 */
3987
3988 $db->free($result);
3989 } else {
3991 }
3992
3994 // Total already paid
3995 print '<tr><td colspan="'.($nbcols + 1).'" class="right">';
3996 print '<span class="opacitymedium">';
3998 print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
3999 } else {
4000 print $langs->trans('AlreadyPaid');
4001 }
4002 print '</span>';
4003 print '</td>';
4004 //print '<td></td>';
4005 print '<td class="right"'.(($totalpaid > 0) ? ' class="amountalreadypaid"' : '').'>'.price($totalpaid).'</td>';
4006 print '</tr>';
4007
4008 //$resteapayer = $object->total_ttc - $totalpaid;
4009 $resteapayeraffiche = $resteapayer;
4010
4011 $cssforamountpaymentcomplete = 'amountpaymentcomplete';
4012
4013 // Loop on each credit note or deposit amount applied
4014 $creditnoteamount = 0;
4015 $depositamount = 0;
4016
4017 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
4018 $sql .= " re.description, re.fk_invoice_supplier_source";
4019 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
4020 $sql .= " WHERE fk_invoice_supplier = ".((int) $object->id);
4021 $resql = $db->query($sql);
4022 if ($resql) {
4023 $num = $db->num_rows($resql);
4024 $i = 0;
4025 $invoice = new FactureFournisseur($db);
4026 while ($i < $num) {
4027 $obj = $db->fetch_object($resql);
4028 $invoice->fetch($obj->fk_invoice_supplier_source);
4029 print '<tr><td colspan="'.$nbcols.'" class="right">';
4030 if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
4031 print $langs->trans("CreditNote").' ';
4032 }
4033 if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
4034 print $langs->trans("Deposit").' ';
4035 }
4036 print $invoice->getNomUrl(0);
4037 print '</td>';
4038 // Delete
4039 print '<td class="right">';
4040 print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&token='.newToken().'&discountid='.$obj->rowid.'">';
4041 print img_picto($langs->transnoentitiesnoconv("RemoveDiscount"), 'unlink');
4042 print '</a>';
4043 print '</td>';
4044 // Amount
4045 print '<td class="right">'.price($obj->amount_ttc).'</td>';
4046 print '</tr>';
4047 $i++;
4048 if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
4049 $creditnoteamount += $obj->amount_ttc;
4050 }
4051 if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
4052 $depositamount += $obj->amount_ttc;
4053 }
4054 }
4055 } else {
4057 }
4058
4059 // Pay partially 'escompte'
4060 if (($object->status == FactureFournisseur::STATUS_CLOSED || $object->status == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
4061 print '<tr><td colspan="'.($nbcols + 1).'" class="right nowrap">';
4062 print '<span class="opacitymedium">';
4063 print $form->textwithpicto($langs->trans("Discount"), $langs->trans("HelpEscompte"), - 1);
4064 print '</span>';
4065 print '</td>';
4066 //print '<td></td>';
4067 print '<td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid).'</td>';
4068 print '</tr>';
4069 $resteapayeraffiche = 0;
4070 $cssforamountpaymentcomplete = 'amountpaymentneutral';
4071 }
4072 // Paye partiellement ou Abandon 'badsupplier'
4073 if (($object->status == FactureFournisseur::STATUS_CLOSED || $object->status == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'badsupplier') {
4074 print '<tr><td colspan="'.($nbcols + 1).'" class="right nowrap">';
4075 print '<span class="opacitymedium">';
4076 print $form->textwithpicto($langs->trans("Abandoned"), $langs->trans("HelpAbandonBadCustomer"), - 1);
4077 print '</span>';
4078 print '</td>';
4079 //print '<td></td>';
4080 print '<td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid).'</td>';
4081 print '</tr>';
4082 // $resteapayeraffiche=0;
4083 $cssforamountpaymentcomplete = 'amountpaymentneutral';
4084 }
4085 // Paye partiellement ou Abandon 'product_returned'
4086 if (($object->status == FactureFournisseur::STATUS_CLOSED || $object->status == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
4087 print '<tr><td colspan="'.($nbcols + 1).'" class="right nowrap">';
4088 print '<span class="opacitymedium">';
4089 print $form->textwithpicto($langs->trans("ProductReturned"), $langs->trans("HelpAbandonProductReturned"), - 1);
4090 print '</span>';
4091 print '</td>';
4092 //print '<td></td>';
4093 print '<td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid).'</td>';
4094 print '</tr>';
4095 $resteapayeraffiche = 0;
4096 $cssforamountpaymentcomplete = 'amountpaymentneutral';
4097 }
4098 // Paye partiellement ou Abandon 'abandon'
4099 if (($object->status == FactureFournisseur::STATUS_CLOSED || $object->status == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'abandon') {
4100 print '<tr><td colspan="'.($nbcols + 1).'" class="right nowrap">';
4101 $text = $langs->trans("HelpAbandonOther");
4102 if ($object->close_note) {
4103 $text .= '<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
4104 }
4105 print '<span class="opacitymedium">';
4106 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
4107 print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1);
4108 print '</span>';
4109 print '</td>';
4110 //print '<td></td>';
4111 print '<td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid).'</td>';
4112 print '</tr>';
4113 $resteapayeraffiche = 0;
4114 $cssforamountpaymentcomplete = 'amountpaymentneutral';
4115 }
4116
4117 // Billed
4118 print '<tr><td colspan="'.($nbcols + 1).'" class="right">';
4119 print '<span class="opacitymedium">';
4120 print $langs->trans("Billed");
4121 print '</span>';
4122 print '</td>';
4123 //print '<td></td>';
4124 print '<td class="right">'.price($object->total_ttc).'</td>';
4125 print '</tr>';
4126
4127 // Remainder to pay
4128 print '<tr><td colspan="'.($nbcols + 1).'" class="right">';
4129 print '<span class="opacitymedium">';
4130 print $langs->trans('RemainderToPay');
4131 if ($resteapayeraffiche < 0) {
4132 print ' ('.$langs->trans('NegativeIfExcessPaid').')';
4133 }
4134 print '</span>';
4135 print '</td>';
4136 //print '<td></td>';
4137 print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td>';
4138 print '</tr>';
4139
4140 // Remainder to pay Multicurrency
4141 if (isModEnabled('multicurrency') && (($object->multicurrency_code && $object->multicurrency_code != $conf->currency) || $object->multicurrency_tx != 1)) {
4142 print '<tr><td colspan="'.($nbcols + 1).'" class="right">';
4143 print '<span class="opacitymedium">';
4144 print $langs->trans('RemainderToPayMulticurrency');
4145 if ($resteapayeraffiche < 0) {
4146 print ' ('.$langs->trans('NegativeIfExcessPaid').')';
4147 }
4148 print '</span>';
4149 print '</td>';
4150 //print '<td></td>';
4151 print '<td class="right'.($resteapayeraffiche ? ' amountremaintopaynoresize' : (' '.$cssforamountpaymentcomplete)).'">'.price(price2num($multicurrency_resteapayer, 'MT'), 0, $langs, 1, -1, -1, $object->multicurrency_code).'</td>';
4152 print '</tr>';
4153 }
4154 } else { // Credit note
4155 $cssforamountpaymentcomplete = 'amountpaymentneutral';
4156
4157 // Total already paid back
4158 print '<tr><td colspan="'.($nbcols + 1).'" class="right">';
4159 print $langs->trans('AlreadyPaidBack');
4160 print '</td>';
4161 //print '<td></td>';
4162 print '<td class="right">'.price($sign * $totalpaid).'</td>';
4163 print '</tr>';
4164
4165 // Billed
4166 print '<tr><td colspan="'.($nbcols + 1).'" class="right">'.$langs->trans("Billed").'</td>';
4167 //print '<td></td>';
4168 print '<td class="right">'.price($sign * $object->total_ttc).'</td>';
4169 print '</tr>';
4170
4171 // Remainder to pay back
4172 print '<tr><td colspan="'.($nbcols + 1).'" class="right">';
4173 print '<span class="opacitymedium">';
4174 print $langs->trans('RemainderToPayBack');
4175 if ($resteapayeraffiche > 0) {
4176 print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
4177 }
4178 print '</td>';
4179 print '</span>';
4180 //print '<td></td>';
4181 print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($sign * $resteapayeraffiche).'</td>';
4182 print '</tr>';
4183
4184 // Remainder to pay back Multicurrency
4185 if (isModEnabled('multicurrency') && (($object->multicurrency_code && $object->multicurrency_code != $conf->currency) || $object->multicurrency_tx != 1)) {
4186 print '<tr><td colspan="'.($nbcols + 1).'" class="right">';
4187 print '<span class="opacitymedium">';
4188 print $langs->trans('RemainderToPayBackMulticurrency');
4189 if ($resteapayeraffiche > 0) {
4190 print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
4191 }
4192 print '</span>';
4193 print '</td>';
4194 //print '<td></td>';
4195 print '<td class="right'.($resteapayeraffiche ? ' amountremaintopaynoresize' : (' '.$cssforamountpaymentcomplete)).'">'.(!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency).' '.price(price2num($sign * $object->multicurrency_tx * $resteapayeraffiche, 'MT')).'</td>';
4196 print '</tr>';
4197 }
4198
4199 // Sold credit note
4200 // print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('TotalTTC').' :</td>';
4201 // print '<td class="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
4202 // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
4203 }
4204
4205 print '</table>';
4206 print '</div>';
4207
4208 print '</div>';
4209 print '</div>';
4210
4211 print '<div class="clearboth"></div><br>';
4212
4213 if (getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB')) {
4214 $blocname = 'contacts';
4215 $title = $langs->trans('ContactsAddresses');
4216 include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
4217 }
4218
4219 if (getDolGlobalString('MAIN_DISABLE_NOTES_TAB')) {
4220 $colwidth = 20;
4221 $blocname = 'notes';
4222 $title = $langs->trans('Notes');
4223 include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
4224 }
4225
4226
4227 /*
4228 * Lines
4229 */
4230 print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">';
4231 print '<input type="hidden" name="token" value="'.newToken().'">';
4232 print '<input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">';
4233 print '<input type="hidden" name="mode" value="">';
4234 print '<input type="hidden" name="page_y" value="">';
4235 print '<input type="hidden" name="id" value="'.$object->id.'">';
4236 print '<input type="hidden" name="socid" value="'.$societe->id.'">';
4237 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
4238
4239 if (!empty($conf->use_javascript_ajax) && $object->status == FactureFournisseur::STATUS_DRAFT) {
4240 if (isModEnabled('subtotals')) {
4241 include DOL_DOCUMENT_ROOT . '/core/tpl/subtotal_ajaxrow.tpl.php';
4242 } else {
4243 include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
4244 }
4245 }
4246
4247 print '<div class="div-table-responsive-no-min">';
4248 print '<table id="tablelines" class="noborder noshadow centpercent">';
4249
4250 global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax;
4251 $forceall = 1;
4252 $dateSelector = 0;
4253 $inputalsopricewithtax = 1;
4254 $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum.
4255 if (getDolGlobalInt('SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY')) {
4256 $senderissupplier = getDolGlobalInt('SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY');
4257 }
4258
4259 // Show object lines (result may vary according to hidden option MAIN_NO_INPUT_PRICE_WITH_TAX)
4260 if (!empty($object->lines)) {
4261 $object->printObjectLines($action, $societe, $mysoc, $lineid, 1);
4262 }
4263
4264 $num = count($object->lines);
4265
4266 // Form to add new line
4267 if ($object->status == FactureFournisseur::STATUS_DRAFT && $usercancreate) {
4268 if ($action != 'editline') {
4269 // Add free products/services
4270
4271 $parameters = array();
4272 $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
4273 if ($reshook < 0) {
4274 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
4275 }
4276 if (empty($reshook)) {
4277 $object->formAddObjectLine(1, $societe, $mysoc);
4278 }
4279 }
4280 }
4281
4282 print '</table>';
4283 print '</div>';
4284 print '</form>';
4285 }
4286
4287 print dol_get_fiche_end();
4288
4289
4290 if ($action != 'presend') {
4291 // Buttons actions
4292
4293 print '<div class="tabsAction">';
4294
4295 $parameters = array();
4296 $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
4297 // modified by hook
4298 if (empty($reshook)) {
4299 // Subtotal
4300 if ($object->status == FactureFournisseur::STATUS_DRAFT && isModEnabled('subtotals') && getDolGlobalString('SUBTOTAL_TITLE_'.strtoupper($object->element))) {
4301 $langs->load('subtotals');
4302
4303 $url_button = array();
4304
4305 $url_button[] = array(
4306 'lang' => 'subtotals',
4307 'enabled' => true,
4308 'perm' => (bool) $usercancreate,
4309 'label' => $langs->trans('AddTitleLine'),
4310 'url' => dolBuildUrl($_SERVER['PHP_SELF'], ['id' => $object->id, 'action' => 'add_title_line'], true)
4311 );
4312
4313 $url_button[] = array(
4314 'lang' => 'subtotals',
4315 'enabled' => true,
4316 'perm' => (bool) $usercancreate,
4317 'label' => $langs->trans('AddSubtotalLine'),
4318 'url' => dolBuildUrl($_SERVER['PHP_SELF'], ['id' => $object->id, 'action' => 'add_subtotal_line'], true)
4319 );
4320
4321 print dolGetButtonAction('', $langs->trans('SubTotal'), 'default', $url_button, '', true);
4322 }
4323 // Modify a validated invoice with no payments
4324 if ($object->status == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate) {
4325 // We check if lines of invoice are not already transferred into accountancy
4326 $ventilExportCompta = $object->getVentilExportCompta(); // Should be 0 since the sum of payments are zero. But we keep the protection.
4327
4328 if ($ventilExportCompta == 0) {
4329 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=edit&token='.newToken().'">'.$langs->trans('Modify').'</a>';
4330 } else {
4331 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Modify').'</span>';
4332 }
4333 }
4334
4335 $discount = new DiscountAbsolute($db);
4336 $result = $discount->fetch(0, 0, $object->id);
4337
4338 // Reopen a standard paid invoice
4340 || ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && empty($discount->id))
4341 || ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discount->id)))
4342 && ($object->status == FactureFournisseur::STATUS_CLOSED || $object->status == FactureFournisseur::STATUS_ABANDONED)) { // A paid invoice (partially or completely)
4343 if (!$objectidnext && $object->close_code != 'replaced' && $usercancreate) { // Not replaced by another invoice
4344 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen&token='.newToken().'">'.$langs->trans('ReOpen').'</a>';
4345 } else {
4346 if ($usercancreate) {
4347 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span>';
4348 } elseif (!getDolGlobalString('MAIN_BUTTON_HIDE_UNAUTHORIZED')) {
4349 print '<span class="butActionRefused classfortooltip">'.$langs->trans('ReOpen').'</span>';
4350 }
4351 }
4352 }
4353
4354 // Validate
4355 if ($action != 'confirm_edit' && $object->status == FactureFournisseur::STATUS_DRAFT && count($object->lines) > 0
4356 && ((($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_PROFORMA || $object->type == FactureFournisseur::TYPE_SITUATION) && (getDolGlobalString('SUPPLIER_INVOICE_ENABLE_NEGATIVE') || $object->total_ttc >= 0)) // @phan-suppress-current-line PhanDeprecatedClassConstant
4357 || ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) {
4358 // if (count($object->lines)) { // already tested in condition
4359 if ($usercanvalidate) {
4360 print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=valid&token='.newToken().'"';
4361 print '>'.$langs->trans('Validate').'</a>';
4362 } else {
4363 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'"';
4364 print '>'.$langs->trans('Validate').'</a>';
4365 }
4366 //}
4367 }
4368
4369 // Send by mail
4370 if (empty($user->socid)) {
4372 if ($usercansend) {
4373 print dolGetButtonAction('', $langs->trans('SendMail'), 'email', dolBuildUrl($_SERVER["PHP_SELF"], ['id' => $object->id, 'action' => 'presend', 'mode' => 'init'], true).'#formmailbeforetitle', '');
4374 } else {
4375 print dolGetButtonAction('', $langs->trans('SendMail'), 'email', '#', '', false);
4376 }
4377 }
4378 }
4379
4380 // Request a direct debit order
4381 if ($object->status > FactureFournisseur::STATUS_DRAFT && $object->paid == 0) {
4382 $langs->load("withdrawals");
4383 if ($resteapayer > 0) {
4384 if ($usercancreatecreditransfer) {
4385 if (!$objectidnext && $object->close_code != 'replaced') { // Not replaced by another invoice
4386 print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$object->id.'&type=bank-transfer" title="'.dol_escape_htmltag($langs->trans("MakeBankTransferOrder")).'">'.$langs->trans("MakeBankTransferOrder").'</a>';
4387 } else {
4388 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('MakeBankTransferOrder').'</span>';
4389 }
4390 } else {
4391 //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
4392 }
4393 } else {
4394 //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("AmountMustBePositive")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
4395 }
4396 }
4397
4398 // Create payment
4399 if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->status == FactureFournisseur::STATUS_VALIDATED && $object->paid == 0 && $usercancreate) {
4400 print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/paiement.php?facid='.$object->id.'&action=create'.($object->fk_account > 0 ? '&accountid='.$object->fk_account : '').'">'.$langs->trans('DoPayment').'</a>'; // must use facid because id is for payment id not invoice
4401 }
4402
4403 // Reverse back money or convert to reduction
4405 // For credit note only
4406 if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->status == 1 && $object->paid == 0) {
4407 if ($resteapayer == 0) {
4408 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span>';
4409 } elseif ($usercancreate) {
4410 print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/paiement.php?facid='.$object->id.'&action=create&accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a>';
4411 }
4412 }
4413
4414 // For standard invoice with excess paid
4415 if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paid) && ($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits) < 0 && $usercancreate && empty($discount->id)) {
4416 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=converttoreduc&token='.newToken().'">'.$langs->trans('ConvertExcessPaidToReduc').'</a>';
4417 }
4418 // For credit note
4419 if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->status == 1 && $object->paid == 0 && $usercancreate
4420 && (getDolGlobalString('SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED') || $object->getSommePaiement() == 0)
4421 ) {
4422 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=converttoreduc&token='.newToken().'" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReducSupplier2")).'">'.$langs->trans('ConvertToReduc').'</a>';
4423 }
4424 // For deposit invoice
4425 if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $usercancreate && $object->status > 0 && empty($discount->id)) {
4426 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=converttoreduc&token='.newToken().'">'.$langs->trans('ConvertToReduc').'</a>';
4427 }
4428 }
4429
4430 // Classify paid
4431 if ($object->status == FactureFournisseur::STATUS_VALIDATED && $object->paid == 0 && (
4432 ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT && ($resteapayer <= 0 || (getDolGlobalString('SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') && $object->total_ttc == $resteapayer))) ||
4433 ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $resteapayer >= 0) ||
4434 ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->total_ttc > 0 && ($resteapayer == 0 || (getDolGlobalString('SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') && $object->total_ttc == $resteapayer)))
4435 )
4436 ) {
4437 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=paid&token='.newToken().'">'.$langs->trans('ClassifyPaid').'</a>';
4438 }
4439
4440 // Classify 'closed not completely paid' (possible if validated and not yet filed paid)
4441 if ($object->status == FactureFournisseur::STATUS_VALIDATED && $object->paid == 0 && $resteapayer > 0 && (!getDolGlobalString('SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') || $object->total_ttc != $resteapayer)) {
4442 if ($totalpaid > 0 || $totalcreditnotes > 0) {
4443 // If one payment or one credit note was linked to this invoice
4444 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=paid&token='.newToken().'">'.$langs->trans('ClassifyPaidPartially').'</a>';
4445 } else {
4446 if (!getDolGlobalString('INVOICE_CAN_NEVER_BE_CANCELED')) {
4447 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=canceled&token='.newToken().'">'.$langs->trans('ClassifyCanceled').'</a>';
4448 }
4449 }
4450 }
4451
4452 // Create event
4453 /*if (isModEnabled('agenda') && getDolGlobalString('MAIN_ADD_EVENT_ON_ELEMENT_CARD')) { // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page.
4454 print '<div class="inline-block divButAction"><a class="butAction" href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&amp;origin=' . $object->element . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '">' . $langs->trans("AddAction") . '</a></div>';
4455 }*/
4456
4457 // Create a credit note
4458 if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->status > 0 && $usercancreate) {
4459 if (!$objectidnext) {
4460 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&amp;fac_avoir='.$object->id.'&action=create&type=2'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').'">'.$langs->trans("CreateCreditNote").'</a>';
4461 }
4462 }
4463
4464 // Clone
4465 if ($action != 'edit' && $usercancreate) {
4466 print '<a class="butAction butActionClone" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=clone&socid='.$object->socid.'&token='.newToken().'">'.$langs->trans('ToClone').'</a>';
4467 }
4468
4469 // Clone as predefined / Create template
4470 if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->status == 0 && $usercancreate) {
4471 if (!$objectidnext && count($object->lines) > 0) {
4472 print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card-rec.php?facid='.$object->id.'&action=create">'.$langs->trans("ChangeIntoRepeatableInvoice").'</a>';
4473 }
4474 }
4475
4476 // Delete
4477 if ($action != 'confirm_edit' && $usercandelete) {
4478 $isErasable = $object->is_erasable();
4479
4480 $enableDelete = false;
4481 $htmltooltip = '';
4482 $params = (empty($conf->use_javascript_ajax) ? array() : array('attr' => array('class' => 'reposition')));
4483 //var_dump($isErasable); var_dump($params);
4484 if ($isErasable == -4) {
4485 $htmltooltip = $langs->trans("DisabledBecausePayments");
4486 } elseif ($isErasable == -3) { // Should never happen with supplier invoice
4487 $htmltooltip = $langs->trans("DisabledBecauseNotLastSituationInvoice");
4488 } elseif ($isErasable == -2) { // Should never happen with supplier invoice
4489 $htmltooltip = $langs->trans("DisabledBecauseNotLastInvoice");
4490 } elseif ($isErasable == -1) {
4491 $htmltooltip = $langs->trans("DisabledBecauseDispatchedInBookkeeping");
4492 } elseif ($isErasable <= 0) { // Any other cases
4493 $htmltooltip = $langs->trans("DisabledBecauseNotErasable");
4494 } else {
4495 $enableDelete = true;
4496 $htmltooltip = '';
4497 }
4498 print dolGetButtonAction($htmltooltip, $langs->trans("Delete"), 'delete', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken(), (string) $object->id, $enableDelete, $params);
4499 }
4500 print '</div>';
4501
4502 if ($action != 'confirm_edit') {
4503 print '<div class="fichecenter"><div class="fichehalfleft">';
4504
4505 /*
4506 * Generated documents
4507 */
4508 $ref = dol_sanitizeFileName($object->ref);
4509 $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref;
4510 $filedir = getMultidirOutput($object).'/'.$subdir;
4511 $urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id;
4512 $genallowed = $usercanread;
4513 $delallowed = $usercancreate;
4514 $modelpdf = (empty($object->model_pdf) ? getDolGlobalString('INVOICE_SUPPLIER_ADDON_PDF') : $object->model_pdf);
4515 $genifempty = 0;
4516
4517 print $formfile->showdocuments('facture_fournisseur', $subdir, $filedir, $urlsource, (int) $genallowed, (int) $delallowed, $modelpdf, $genifempty, 0, 0, 40, 0, '', '', '', $societe->default_lang);
4518 $somethingshown = $formfile->numoffiles;
4519
4520 // Show links to link elements
4521 $tmparray = $form->showLinkToObjectBlock($object, array(), array('invoice_supplier'), 1);
4522 $linktoelem = $tmparray['linktoelem'];
4523 $htmltoenteralink = $tmparray['htmltoenteralink'];
4524 print $htmltoenteralink;
4525
4526 $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
4527
4528 print '</div><div class="fichehalfright">';
4529
4530 // List of actions on element
4531 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
4532 $formactions = new FormActions($db);
4533 $somethingshown = $formactions->showactions($object, 'invoice_supplier', $socid, 1, 'listaction'.($genallowed ? 'largetitle' : ''));
4534
4535 print '</div></div>';
4536 }
4537 }
4538 }
4539
4540 // Select mail models is same action as presend
4541 if (GETPOST('modelselected')) {
4542 $action = 'presend';
4543 }
4544
4545 // Presend form
4546 $modelmail = 'invoice_supplier_send';
4547 $defaulttopic = 'SendBillRef';
4548 $diroutput = getMultidirOutput($object);
4549 $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO';
4550 $trackid = 'sinv'.$object->id;
4551
4552 include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
4553 }
4554}
4555
4556
4557// End of page
4558llxFooter();
4559$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
Class to manage bank accounts.
Class to manage accounting journals.
const TYPE_PROFORMA
Proforma invoice.
const TYPE_SITUATION
Situation invoice.
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage warehouses.
Class to manage standard extra fields.
Class to manage suppliers invoices.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
const TYPE_REPLACEMENT
Replacement invoice.
const STATUS_VALIDATED
Validated (need to be paid)
const TYPE_STANDARD
Standard invoice.
const STATUS_ABANDONED
Classified abandoned and no payment done.
const STATUS_CLOSED
Classified paid.
Class to manage invoice templates.
Class to manage building of HTML components.
Class to offer components to list and upload files.
Class to manage generation of HTML components Only common components must be here.
Class with static methods for building HTML components related to products Only components common to ...
Class to manage building of HTML components.
Class to manage payments for supplier invoices.
Class ProductCombination Used to represent the relation between a product and one of its variants.
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 line invoices.
Class to manage translations.
isInEEC($object)
Return if a country of an object is inside the EEC (European Economic Community)
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:666
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:129
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
$date_start
Variables from include:
facturefourn_prepare_head(FactureFournisseur $object)
Prepare array with list of tabs.
Definition fourn.lib.php:38
dol_now($mode='gmt')
Return date for now.
recordNotFound($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Displays an error page when a record is not found.
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...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
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.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
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.
GETPOSTFLOAT($paramname, $rounding='', $option=2)
Return the value of a $_GET or $_POST supervariable, converted into float.
dolGetButtonAction($label, $text='', $actionType='default', $url='', $id='', $userRight=1, $params=array())
Function dolGetButtonAction.
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...
dol_htmloutput_events($disabledoutputofmessages=0)
Print formatted messages to output (Used to show messages on html output).
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).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
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.
img_edit($titlealt='default', $float=0, $other='')
Show logo edit/modify fiche.
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...
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
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.
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,...
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
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.