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