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