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