dolibarr 24.0.3
card.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
4 * Copyright (C) 2004-2025 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
6 * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
7 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
8 * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
9 * Copyright (C) 2012-2023 Christophe Battarel <christophe.battarel@altairis.fr>
10 * Copyright (C) 2012-2013 Cédric Salvador <csalvador@gpcsolutions.fr>
11 * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
12 * Copyright (C) 2013 Jean-Francois FERRY <jfefe@aternatik.fr>
13 * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
14 * Copyright (C) 2014-2024 Ferran Marcet <fmarcet@2byte.es>
15 * Copyright (C) 2015-2016 Marcos García <marcosgdf@gmail.com>
16 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
17 * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
18 * Copyright (C) 2022-2023 Solution Libre SAS <contact@solution-libre.fr>
19 * Copyright (C) 2023 Nick Fragoulis
20 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
21 * Copyright (C) 2024-2025 Alexandre Spangaro <alexandre@inovea-conseil.com>
22 * Copyright (C) 2025 Lenin Rivas <lenin.rivas777@gmail.com>
23 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
24 * Copyright (C) 2026 Joachim Küter <git-jk@bloxera.com>
25 *
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 3 of the License, or
29 * (at your option) any later version.
30 *
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
35 *
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <https://www.gnu.org/licenses/>.
38 */
39
46// Load Dolibarr environment
47require '../../main.inc.php';
57require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
58require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
59require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
60require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
61require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
62require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
63require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
64require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
65require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
66require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
67require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
68require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
69require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
70require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
71if (isModEnabled('order')) {
72 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
73}
74if (isModEnabled('project')) {
75 require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
76 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
77}
78require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
79
80if (isModEnabled('variants')) {
81 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
82}
83if (isModEnabled('accounting')) {
84 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
85}
86
87// Load translation files required by the page
88$langs->loadLangs(array('bills', 'companies', 'compta', 'products', 'banks', 'main', 'withdrawals'));
89if (isModEnabled('incoterm')) {
90 $langs->load('incoterm');
91}
92if (isModEnabled('margin')) {
93 $langs->load('margins');
94}
95
96// General $Variables
97$action = GETPOST('action', 'aZ09');
98$confirm = GETPOST('confirm', 'alpha');
99$cancel = GETPOST('cancel', 'alpha');
100$backtopage = GETPOST('backtopage', 'alpha'); // if not set, a default page will be used
101$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); // if not set, $backtopage will be used
102
103$id = (GETPOSTINT('id') ? GETPOSTINT('id') : GETPOSTINT('facid')); // For backward compatibility
104$ref = GETPOST('ref', 'alpha');
105$socid = GETPOSTINT('socid');
106$lineid = GETPOSTINT('lineid');
107$origin = GETPOST('origin', 'alpha');
108$originid = (GETPOSTINT('originid') ? GETPOSTINT('originid') : GETPOSTINT('origin_id')); // For backward compatibility
109$fac_rec = GETPOSTINT('fac_rec');
110$facid = GETPOSTINT('facid');
111$ref_client = GETPOST('ref_client', 'alpha');
112$inputReasonId = GETPOSTINT('input_reason_id');
113$rank = (GETPOSTINT('rank') > 0) ? GETPOSTINT('rank') : -1;
114$projectid = (GETPOSTINT('projectid') ? GETPOSTINT('projectid') : 0);
115$selectedLines = GETPOST('toselect', 'array:int');
116
117// PDF
118$hidedetails = (GETPOSTINT('hidedetails') ? GETPOSTINT('hidedetails') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0));
119$hidedesc = (GETPOSTINT('hidedesc') ? GETPOSTINT('hidedesc') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0));
120$hideref = (GETPOSTINT('hideref') ? GETPOSTINT('hideref') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0));
121
122// Number of lines for predefined product/service choices
123$NBLINES = 4;
124
125$object = new Facture($db);
126
127// Fetch optionals attributes and labels
128$extrafields->fetch_name_optionals_label($object->table_element);
129
130$objectidnext = 0;
131$total_global_ttc = 0;
132$displayWarranty = false;
133$statusreplacement = 0;
134$type_fac = 0;
135$price_base_type = '';
136$array_options = array();
137
138// Load object
139if ($id > 0 || !empty($ref)) {
140 if ($action != 'add') {
141 if (!getDolGlobalString('INVOICE_USE_SITUATION')) {
142 $fetch_situation = false;
143 } else {
144 $fetch_situation = true;
145 }
146 $ret = $object->fetch($id, $ref, '', 0, $fetch_situation);
147 if ($ret > 0 && isset($object->fk_project)) {
148 $ret = $object->fetchProject();
149 }
150 }
151}
152
153// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
154$hookmanager->initHooks(array('invoicecard', 'globalcard'));
155
156// Permissions
157$usercanread = $user->hasRight("facture", "lire");
158$usercancreate = $user->hasRight("facture", "creer");
159$usercanissuepayment = $user->hasRight("facture", "paiement");
160$usercandelete = $user->hasRight("facture", "supprimer") || ($usercancreate && isset($object->status) && $object->status == $object::STATUS_DRAFT);
161$usercancreatecontract = $user->hasRight("contrat", "creer");
162
163// Advanced Permissions
164$usercanvalidate = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('facture', 'invoice_advance', 'validate')));
165$usercansend = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $usercanread) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('facture', 'invoice_advance', 'send')));
166$usercanreopen = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('facture', 'invoice_advance', 'reopen')));
167if (getDolGlobalString('INVOICE_DISALLOW_REOPEN')) {
168 $usercanreopen = false;
169}
170$usercanunvalidate = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !empty($usercancreate)) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('facture', 'invoice_advance', 'unvalidate')));
171$usermustrespectpricemin = ((getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('produit', 'ignore_price_min_advance')) || !getDolGlobalString('MAIN_USE_ADVANCED_PERMS'));
172
173// Other permissions
174$usercancreatemargin = $user->hasRight('margins', 'creer');
175$usercanreadallmargin = $user->hasRight('margins', 'liretous');
176$usercancreatewithdrarequest = $user->hasRight('prelevement', 'bons', 'creer');
177
178$permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
179$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
180$permissiontoedit = $usercancreate; // Used by the include of actions_lineupdonw.inc.php
181$permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php
182$permissiontoeditextra = $usercancreate;
183if (GETPOST('attribute', 'aZ09') && isset($extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')])) {
184 // For action 'update_extras', is there a specific permission set for the attribute to update
185 $permissiontoeditextra = dol_eval((string) $extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')]);
186}
187
188// retained warranty invoice available type
189$retainedWarrantyInvoiceAvailableType = array();
190if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
191 $retainedWarrantyInvoiceAvailableType = explode('+', getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY'));
192}
193
194// Security check
195if ($user->socid) {
196 $socid = $user->socid;
197}
198$isdraft = (($object->status == Facture::STATUS_DRAFT) ? 1 : 0);
199
200$result = restrictedArea($user, 'facture', $object->id, '', '', 'fk_soc', 'rowid', $isdraft);
201
202
203/*
204 * Actions
205 */
206
207$error = 0;
208
209$parameters = array('socid' => $socid);
210$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
211if ($reshook < 0) {
212 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
213}
214
215if (empty($reshook)) {
216 $backurlforlist = dolBuildUrl(DOL_URL_ROOT.'/compta/facture/list.php');
217
218 if (empty($backtopage) || ($cancel && empty($id))) {
219 if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
220 if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
221 $backtopage = $backurlforlist;
222 } else {
223 $backtopage = dolBuildUrl(DOL_URL_ROOT.'/compta/facture/card.php', ['id' => ((!empty($id) && $id > 0) ? $id : '__ID__')]);
224 }
225 }
226 }
227
228 if ($cancel) {
229 if (!empty($backtopageforcancel)) {
230 header("Location: ".$backtopageforcancel);
231 exit;
232 } elseif (!empty($backtopage)) {
233 header("Location: ".$backtopage);
234 exit;
235 }
236 $action = '';
237 }
238
239 include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be 'include', not 'include_once'
240
241 include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be 'include', not 'include_once'
242
243 include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be 'include', not 'include_once'
244
245 // Action clone object
246 if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) {
247 if (!($socid > 0)) {
248 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('IdThirdParty')), null, 'errors');
249 } else {
250 $objectutil = dol_clone($object, 1); // We use a clone to avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid.
251 '@phan-var-force Facture $objectutil';
252
253 $objectutil->date = dol_mktime(12, 0, 0, GETPOSTINT('newdatemonth'), GETPOSTINT('newdateday'), GETPOSTINT('newdateyear'));
254 $objectutil->socid = $socid;
255 $result = $objectutil->createFromClone($user, $id, (GETPOSTISSET('entity') ? GETPOSTINT('entity') : null));
256 if ($result > 0) {
257 $warningMsgLineList = array();
258 // check all product lines are to sell otherwise add a warning message for each product line is not to sell
259 foreach ($objectutil->lines as $line) {
260 if (!is_object($line->product)) {
261 $line->fetch_product();
262 }
263 if (is_object($line->product) && $line->product->id > 0) {
264 if (empty($line->product->status)) {
265 $warningMsgLineList[$line->id] = $langs->trans('WarningLineProductNotToSell', $line->product->ref);
266 }
267 }
268 }
269 if (!empty($warningMsgLineList)) {
270 setEventMessages('', $warningMsgLineList, 'warnings');
271 }
272
273 header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $result);
274 exit();
275 } else {
276 $langs->load("errors");
277 setEventMessages($objectutil->error, $objectutil->errors, 'errors');
278 $action = '';
279 }
280 }
281 } elseif ($action == 'reopen' && $usercanreopen) {
282 $result = $object->fetch($id);
283
284 if ($object->status == Facture::STATUS_CLOSED || ($object->status == Facture::STATUS_ABANDONED && ($object->close_code != 'replaced' || $object->getIdReplacingInvoice() == 0)) || ($object->status == Facture::STATUS_VALIDATED && $object->paye == 1)) { // ($object->status == 1 && $object->paye == 1) should not happened but can be found when data are corrupted
285 $result = $object->setUnpaid($user);
286 if ($result > 0) {
287 header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
288 exit();
289 } else {
290 setEventMessages($object->error, $object->errors, 'errors');
291 }
292 }
293 } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) {
294 // Delete invoice
295 $result = $object->fetch($id);
296 $object->fetch_thirdparty();
297
298 $idwarehouse = GETPOST('idwarehouse');
299
300 $qualified_for_stock_change = 0;
301 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
302 $qualified_for_stock_change = $object->hasProductsOrServices(2);
303 } else {
304 $qualified_for_stock_change = $object->hasProductsOrServices(1);
305 }
306
307 $isErasable = $object->is_erasable();
308
309 if (($isErasable > 0) || ($usercancreate && $isErasable == 1)) {
310 $result = $object->delete($user, 0, (int) $idwarehouse);
311 if ($result > 0) {
312 header('Location: '.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1');
313 exit();
314 } else {
315 setEventMessages($object->error, $object->errors, 'errors');
316 $action = '';
317 }
318 }
319 } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
320 // Delete line
321 $object->fetch($id);
322 $object->fetch_thirdparty();
323
324 $result = $object->deleteLine(GETPOSTINT('lineid'));
325 if ($result > 0) {
326 // reorder lines
327 $object->line_order(true);
328 // Define output language
329 $outputlangs = $langs;
330 $newlang = '';
331 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id')) {
332 $newlang = GETPOST('lang_id');
333 }
334 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
335 $newlang = $object->thirdparty->default_lang;
336 }
337 if (!empty($newlang)) {
338 $outputlangs = new Translate("", $conf);
339 $outputlangs->setDefaultLang($newlang);
340 $outputlangs->load('products');
341 }
342 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
343 $ret = $object->fetch($id); // Reload to get new records
344 $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
345 }
346 if ($result >= 0) {
347 header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
348 exit();
349 }
350 } else {
351 setEventMessages($object->error, $object->errors, 'errors');
352 $action = '';
353 }
354 } elseif ($action == 'confirm_delete_subtotalline' && $confirm == 'yes' && $usercancreate) {
355 // Delete line
356 $object->fetch($id);
357 $object->fetch_thirdparty();
358
359 $result = $object->deleteSubtotalLine($langs, GETPOSTINT('lineid'), (bool) GETPOST('deletecorrespondingsubtotalline'));
360 if ($result > 0) {
361 // reorder lines
362 $object->line_order(true);
363 // Define output language
364 $outputlangs = $langs;
365 $newlang = '';
366 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id')) {
367 $newlang = GETPOST('lang_id');
368 }
369 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
370 $newlang = $object->thirdparty->default_lang;
371 }
372 if (!empty($newlang)) {
373 $outputlangs = new Translate("", $conf);
374 $outputlangs->setDefaultLang($newlang);
375 $outputlangs->load('products');
376 }
377 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
378 $ret = $object->fetch($id); // Reload to get new records
379 $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
380 }
381 if ($result >= 0) {
382 header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
383 exit();
384 }
385 } else {
386 setEventMessages($object->error, $object->errors, 'errors');
387 $action = '';
388 }
389 } elseif ($action == 'unlinkdiscount' && $usercancreate) {
390 // Delete link of credit note to invoice
391 $discount = new DiscountAbsolute($db);
392 $result = $discount->fetch(GETPOSTINT("discountid"));
393 if ($result > 0 && $discount->fk_facture == $object->id) { // The credit note must be linked to this invoice
394 $discount->unlink_invoice();
395 } else {
396 setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors');
397 }
398 } elseif ($action == 'valid' && $usercancreate) {
399 // Validation
400 $object->fetch($id);
401
402 if ((preg_match('/^[\‍(]?PROV/i', $object->ref) || empty($object->ref)) && // empty should not happened, but when it occurs, the test save life
403 getDolGlobalString('FAC_FORCE_DATE_VALIDATION') // If option enabled, we force invoice date
404 ) {
405 $object->date = dol_now();
406 }
407
408 if (getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
409 $last_of_type = $object->willBeLastOfSameType(true);
410 if (empty($object->date_validation) && !$last_of_type[0]) {
411 setEventMessages($langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $object->ref, dol_print_date($object->date, 'day'), dol_print_date($last_of_type[1], 'day')), null, 'errors');
412 $action = '';
413 }
414 }
415
416 // We check invoice sign
417 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
418 // If a credit note, the sign must be negative
419 if ($object->total_ht > 0) {
420 setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
421 $action = '';
422 }
423 } else {
424 // If not a credit note, amount with tax must be positive or nul.
425 // Note that amount excluding tax can be negative because you can have a invoice of 100 with vat of 20 that
426 // consumes a credit note of 100 with vat 0 (total with tax is 0 but without tax is -20).
427 // For some cases, credit notes can have a vat of 0 (for example when selling goods in France).
428 if (!getDolGlobalString('FACTURE_ENABLE_NEGATIVE') && $object->total_ttc < 0) {
429 setEventMessages($langs->trans("ErrorInvoiceOfThisTypeMustBePositive"), null, 'errors');
430 $action = '';
431 }
432
433 // Also negative lines should not be allowed on 'non Credit notes' invoices. A test is done when adding or updating lines but we must
434 // do it again in validation to avoid cases where invoice is created from another object that allow negative lines.
435 // Note that we can accept the negative line if sum with other lines with same vat makes total positive: Because all the lines will be merged together
436 // when converted into 'available credit' and we will get a positive available credit line.
437 // Note: Other solution if you want to add a negative line on invoice, is to create a discount for customer and consumme it (but this is possible on standard invoice only).
438 $array_of_total_ht_per_vat_rate = array();
439 $array_of_total_ht_devise_per_vat_rate = array();
440 foreach ($object->lines as $line) {
441 //$vat_src_code_for_line = $line->vat_src_code; // TODO We check sign of total per vat without taking into account the vat code because for the moment the vat code is lost/unknown when we add a down payment.
442 $vat_src_code_for_line = '';
443 if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) {
444 $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0;
445 }
446 if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) {
447 $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0;
448 }
449 $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] += $line->total_ht;
450 $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] += $line->multicurrency_total_ht;
451 }
452
453 //var_dump($array_of_total_ht_per_vat_rate);exit;
454 foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) {
455 $tmp_total_ht = price2num($array_of_total_ht_per_vat_rate[$vatrate]);
456 $tmp_total_ht_devise = price2num($array_of_total_ht_devise_per_vat_rate[$vatrate]);
457
458 if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && !getDolGlobalString('FACTURE_ENABLE_NEGATIVE_LINES')) {
459 if ($object->type == $object::TYPE_DEPOSIT) {
460 $langs->load("errors");
461 // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
462 setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
463 $error++;
464 $action = '';
465 } else {
466 $tmpvatratetoshow = explode('_', $vatrate);
467 $tmpvatratetoshow[0] = round((float) $tmpvatratetoshow[0], 2);
468
469 if ($tmpvatratetoshow[0] != 0) {
470 $langs->load("errors");
471 setEventMessages($langs->trans("ErrorLinesCantBeNegativeForOneVATRate", (string) $tmpvatratetoshow[0]), null, 'errors');
472 $error++;
473 $action = '';
474 }
475 }
476 }
477 }
478 }
479 } elseif ($action == 'classin' && $usercancreate) {
480 $object->fetch($id);
481 $object->setProject(GETPOSTINT('projectid'));
482 if ($result < 0) {
483 setEventMessages($object->error, $object->errors, 'errors');
484 }
485 } elseif ($action == 'setposinfo' && $usercancreate) {
486 $object->fetch($id);
487 $object->module_source = GETPOST('posmodule');
488 $object->pos_source = GETPOST('posterminal');
489 $result = $object->update($user);
490 if ($result < 0) {
491 setEventMessages($object->error, $object->errors, 'errors');
492 }
493 } elseif ($action == 'setmode' && $usercancreate) {
494 $object->fetch($id);
495 $result = $object->setPaymentMethods(GETPOSTINT('mode_reglement_id'));
496 if ($result < 0) {
497 setEventMessages($object->error, $object->errors, 'errors');
498 }
499 } elseif ($action == 'setretainedwarrantyconditions' && $usercancreate) {
501 $object->fetch($id);
502 $object->retained_warranty_fk_cond_reglement = 0; // To clean property
503 $result = $object->setRetainedWarrantyPaymentTerms(GETPOSTINT('retained_warranty_fk_cond_reglement'));
504 if ($result < 0) {
505 setEventMessages($object->error, $object->errors, 'errors');
506 }
507
508 $old_rw_date_lim_reglement = $object->retained_warranty_date_limit;
509 $new_rw_date_lim_reglement = $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
510 if ($new_rw_date_lim_reglement > $old_rw_date_lim_reglement) {
511 $object->retained_warranty_date_limit = $new_rw_date_lim_reglement;
512 }
513 if ($object->retained_warranty_date_limit < $object->date) {
514 $object->retained_warranty_date_limit = $object->date;
515 }
516 $result = $object->update($user);
517 if ($result < 0) {
518 setEventMessages($object->error, $object->errors, 'errors');
519 }
520 } elseif ($action == 'setretainedwarranty' && $usercancreate) {
521 $object->fetch($id);
522 $result = $object->setRetainedWarranty(GETPOSTFLOAT('retained_warranty'));
523 if ($result < 0) {
524 setEventMessages($object->error, $object->errors, 'errors');
525 }
526 } elseif ($action == 'setretainedwarrantydatelimit' && $usercancreate) {
527 $object->fetch($id);
528 $result = $object->setRetainedWarrantyDateLimit(GETPOSTDATE('retained_warranty_date_limit'));
529 if ($result < 0) {
530 setEventMessages($object->error, $object->errors, 'errors');
531 }
532 } elseif ($action == 'setmulticurrencycode' && $usercancreate) { // Multicurrency Code
533 $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
534 } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { // Multicurrency rate
535 $result = $object->setMulticurrencyRate(GETPOSTFLOAT('multicurrency_tx'), GETPOSTINT('calculation_mode'));
536 } elseif ($action == 'setinvoicedate' && $usercancreate) {
537 $object->fetch($id);
538 $old_date_lim_reglement = $object->date_lim_reglement;
539 $newdate = dol_mktime(0, 0, 0, GETPOSTINT('invoicedatemonth'), GETPOSTINT('invoicedateday'), GETPOSTINT('invoicedateyear'), 'tzserver');
540 if (empty($newdate)) {
541 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
542 header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate&token='.newToken());
543 exit;
544 }
545 if ($newdate > (dol_now('tzuserrel') + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
546 if (!getDolGlobalString('INVOICE_MAX_FUTURE_DELAY')) {
547 setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
548 } else {
549 setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
550 }
551 }
552
553 $object->date = $newdate;
554 $new_date_lim_reglement = $object->calculate_date_lim_reglement();
555 if ($new_date_lim_reglement) {
556 $object->date_lim_reglement = $new_date_lim_reglement;
557 }
558 if ($object->date_lim_reglement < $object->date) {
559 $object->date_lim_reglement = $object->date;
560 }
561 $result = $object->update($user);
562 if ($result < 0) {
563 setEventMessages($object->error, $object->errors, 'errors');
564 $action = 'editinvoicedate';
565 }
566 } elseif ($action == 'setdate_pointoftax' && $usercancreate) {
567 $object->fetch($id);
568
569 $date_pointoftax = dol_mktime(0, 0, 0, GETPOSTINT('date_pointoftaxmonth'), GETPOSTINT('date_pointoftaxday'), GETPOSTINT('date_pointoftaxyear'), 'tzserver');
570
571 $object->date_pointoftax = $date_pointoftax;
572 $result = $object->update($user);
573 if ($result < 0) {
574 setEventMessages($object->error, $object->errors, 'errors');
575 }
576 } elseif ($action == 'setconditions' && $usercancreate) {
577 $object->fetch($id);
578 $object->cond_reglement_code = 0; // To clean property
579 $object->cond_reglement_id = 0; // To clean property
580
581 $db->begin();
582
583 if (!$error) {
584 $result = $object->setPaymentTerms(GETPOSTINT('cond_reglement_id'));
585 if ($result < 0) {
586 $error++;
587 setEventMessages($object->error, $object->errors, 'errors');
588 }
589 }
590
591 if (!$error) {
592 $old_date_lim_reglement = $object->date_lim_reglement;
593 $new_date_lim_reglement = $object->calculate_date_lim_reglement();
594 if ($new_date_lim_reglement) {
595 $object->date_lim_reglement = $new_date_lim_reglement;
596 }
597 if ($object->date_lim_reglement < $object->date) {
598 $object->date_lim_reglement = $object->date;
599 }
600 $result = $object->update($user);
601 if ($result < 0) {
602 $error++;
603 setEventMessages($object->error, $object->errors, 'errors');
604 }
605 }
606
607 if ($error) {
608 $db->rollback();
609 } else {
610 $db->commit();
611 }
612 } elseif ($action == 'setpaymentterm' && $usercancreate) {
613 $object->fetch($id);
614 $object->date_lim_reglement = dol_mktime(12, 0, 0, GETPOSTINT('paymenttermmonth'), GETPOSTINT('paymenttermday'), GETPOSTINT('paymenttermyear'));
615 if ($object->date_lim_reglement < $object->date) {
616 $object->date_lim_reglement = $object->calculate_date_lim_reglement();
617 setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
618 }
619 $result = $object->update($user);
620 if ($result < 0) {
621 setEventMessages($object->error, $object->errors, 'errors');
622 }
623 } elseif ($action == 'setrevenuestamp' && $usercancreate) {
624 $object->fetch($id);
625 $object->revenuestamp = (float) price2num(GETPOST('revenuestamp'));
626 $result = $object->update($user);
627 $object->update_price(1);
628 if ($result < 0) {
629 setEventMessages($object->error, $object->errors, 'errors');
630 } else {
631 $object->fetch_thirdparty();
632 // Define output language
633 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
634 $outputlangs = $langs;
635 $newlang = '';
636 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
637 $newlang = GETPOST('lang_id', 'aZ09');
638 }
639 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
640 $newlang = $object->thirdparty->default_lang;
641 }
642 if (!empty($newlang)) {
643 $outputlangs = new Translate("", $conf);
644 $outputlangs->setDefaultLang($newlang);
645 $outputlangs->load('products');
646 }
647 $model = $object->model_pdf;
648 $ret = $object->fetch($id); // Reload to get new records
649
650 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
651 if ($result < 0) {
652 setEventMessages($object->error, $object->errors, 'errors');
653 }
654 }
655 }
656 } elseif ($action == 'set_incoterms' && isModEnabled('incoterm') && $usercancreate) { // Set incoterm
657 $result = $object->setIncoterms(GETPOSTINT('incoterm_id'), GETPOST('location_incoterms'));
658 if ($result < 0) {
659 setEventMessages($object->error, $object->errors, 'errors');
660 }
661 } elseif ($action == 'set_dispute_status' && $usercancreate) { // Set dispute status
662 $result = $object->setStatut(GETPOSTINT('dispute_status'), null, 'facture', 'FACTURE_MODIFY', 'dispute_status');
663 if ($result < 0) {
664 setEventMessages($object->error, $object->errors, 'errors');
665 }
666 } elseif ($action == 'settags' && isModEnabled('category') && $usercancreate) { // Set tags
667 $result = $object->setCategories(GETPOST('categories', 'array'));
668 if ($result < 0) {
669 setEventMessages($object->error, $object->errors, 'errors');
670 }
671 } elseif ($action == 'setbankaccount' && $usercancreate) { // Bank account
672 $result = $object->setBankAccount(GETPOSTINT('fk_account'));
673 if ($result < 0) {
674 setEventMessages($object->error, $object->errors, 'errors');
675 }
676 } elseif ($action == 'setremisepercent' && $usercancreate) {
677 $object->fetch($id);
678 $result = $object->setDiscount($user, (float) price2num(GETPOST('remise_percent'), '', 2));
679 if ($result < 0) {
680 setEventMessages($object->error, $object->errors, 'errors');
681 }
682 } elseif ($action == 'setabsolutediscount' && $usercancreate) {
683 // We have POST[remise_id] (common case) xor POST[remise_id_for_payment] (with unstable oldoption)
684 $db->begin();
685
686 // We use the credit note to reduce amount of invoice
687 if (GETPOSTINT("remise_id") > 0) {
688 $ret = $object->fetch($id);
689 if ($ret > 0) {
690 $result = $object->insert_discount(GETPOSTINT("remise_id"));
691 if ($result < 0) {
692 setEventMessages($object->error, $object->errors, 'errors');
693 }
694 } else {
695 $error++;
696 setEventMessages($object->error, $object->errors, 'errors');
697 }
698
699 if (!$error) {
700 if ($object->status == Facture::STATUS_VALIDATED) {
701 $newremaintopay = $object->getRemainToPay(0);
702 if ($newremaintopay == 0) {
703 $object->setPaid($user);
704 }
705 }
706 }
707 }
708 // We use the credit note to reduce remain to pay
709 if (GETPOSTINT("remise_id_for_payment") > 0) {
710 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
711 $discount = new DiscountAbsolute($db);
712 $discount->fetch(GETPOSTINT("remise_id_for_payment"));
713
714 //var_dump($object->getRemainToPay(0));
715 //var_dump($discount->amount_ttc);exit;
716 $remaintopay = $object->getRemainToPay(0);
717 if (price2num($discount->total_ttc) > price2num($remaintopay)) {
718 // TODO Split the discount in 2 automatically
719 $error++;
720 setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors');
721 }
722
723 if (!$error) {
724 $result = $discount->link_to_invoice(0, $id);
725 if ($result < 0) {
726 $error++;
727 setEventMessages($discount->error, $discount->errors, 'errors');
728 }
729 }
730
731 if (!$error) {
732 // Only mark as paid when the invoice is already validated. On a still-draft
733 // invoice the discount link reduces the remain_to_pay but the invoice is not
734 // yet a legally issued document (ref is still PROV-...), so closing it would
735 // leave it stuck as paid+PROV (see #37744).
736 if ($object->status == Facture::STATUS_VALIDATED) {
737 $newremaintopay = $object->getRemainToPay(0);
738 if ($newremaintopay == 0) {
739 $object->setPaid($user);
740 }
741 }
742 }
743 }
744
745 if (!$error) {
746 $db->commit();
747 } else {
748 $db->rollback();
749 }
750
751 if (empty($error) && !getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
752 $outputlangs = $langs;
753 $newlang = '';
754 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
755 $newlang = GETPOST('lang_id', 'aZ09');
756 }
757 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
758 $object->fetch_thirdparty();
759 $newlang = $object->thirdparty->default_lang;
760 }
761 if (!empty($newlang)) {
762 $outputlangs = new Translate("", $conf);
763 $outputlangs->setDefaultLang($newlang);
764 }
765 $ret = $object->fetch($id); // Reload to get new records
766
767 $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
768 if ($result < 0) {
769 setEventMessages($object->error, $object->errors, 'errors');
770 }
771 }
772 } elseif ($action == 'setref' && $usercancreate) {
773 $object->fetch($id);
774 $object->setValueFrom('ref', GETPOST('ref'), '', 0, '', '', $user, 'BILL_MODIFY');
775 if ($result < 0) {
776 setEventMessages($object->error, $object->errors, 'errors');
777 }
778 } elseif ($action == 'setref_client' && $usercancreate) {
779 $object->fetch($id);
780 $result = $object->set_ref_client(GETPOST('ref_client', 'alpha'));
781 if ($result < 0) {
782 setEventMessages($object->error, $object->errors, 'errors');
783 }
784 } elseif ($action == 'setdemandreason' && $usercancreate) {
785 $result = $object->setInputReason($inputReasonId);
786 if ($result < 0) {
787 setEventMessages($object->error, $object->errors, 'errors');
788 }
789 } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
790 // Classify to validated
791 $idwarehouse = GETPOSTINT('idwarehouse');
792
793 $object->fetch($id);
794 $object->fetch_thirdparty();
795
796 // Check for warehouse
797 if ($object->type != Facture::TYPE_DEPOSIT && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
798 $qualified_for_stock_change = 0;
799 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
800 $qualified_for_stock_change = $object->hasProductsOrServices(2);
801 } else {
802 $qualified_for_stock_change = $object->hasProductsOrServices(1);
803 }
804
805 if ($qualified_for_stock_change) {
806 if (!$idwarehouse || $idwarehouse == - 1) {
807 $error++;
808 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
809 $action = '';
810 }
811 }
812 }
813
814 if (!$error) {
815 $result = $object->validate($user, '', $idwarehouse);
816 if ($result >= 0) {
817 // Define output language
818 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
819 $outputlangs = $langs;
820 $newlang = '';
821 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
822 $newlang = GETPOST('lang_id', 'aZ09');
823 }
824 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
825 $newlang = $object->thirdparty->default_lang;
826 }
827 if (!empty($newlang)) {
828 $outputlangs = new Translate("", $conf);
829 $outputlangs->setDefaultLang($newlang);
830 $outputlangs->load('products');
831 }
832 $model = $object->model_pdf;
833
834 $ret = $object->fetch($id); // Reload to get new records
835
836 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
837 if ($result < 0) {
838 setEventMessages($object->error, $object->errors, 'errors');
839 }
840 }
841 } else {
842 if (count($object->errors)) {
843 setEventMessages(null, $object->errors, 'errors');
844 } else {
845 setEventMessages($object->error, $object->errors, 'errors');
846 }
847 }
848 }
849 } elseif ($action == 'confirm_modif' && $usercanunvalidate && !getDolGlobalString('INVOICE_CAN_NEVER_BE_EDITED')) {
850 // Go back to draft status (unvalidate)
851 $idwarehouse = GETPOSTINT('idwarehouse');
852
853 $object->fetch($id);
854 $object->fetch_thirdparty();
855
856 // Check parameters
857 if ($object->type != Facture::TYPE_DEPOSIT && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
858 $qualified_for_stock_change = 0;
859 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
860 $qualified_for_stock_change = $object->hasProductsOrServices(2);
861 } else {
862 $qualified_for_stock_change = $object->hasProductsOrServices(1);
863 }
864
865 if ($qualified_for_stock_change) {
866 if (!$idwarehouse || $idwarehouse == -1) {
867 $error++;
868 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
869 $action = '';
870 }
871 }
872 }
873
874 if (!$error) {
875 // We check if invoice has payments
876 $totalpaid = 0;
877 $sql = 'SELECT pf.amount';
878 $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf';
879 $sql .= ' WHERE pf.fk_facture = ' . ((int) $object->id);
880
881 $result = $db->query($sql);
882 if ($result) {
883 $i = 0;
884 $num = $db->num_rows($result);
885
886 while ($i < $num) {
887 $objp = $db->fetch_object($result);
888 $totalpaid += $objp->amount;
889 $i++;
890 }
891 } else {
892 dol_print_error($db, '');
893 }
894
895 $resteapayer = $object->total_ttc - $totalpaid;
896
897 // We check that invoice lines are transferred into accountancy
898 $ventilExportCompta = $object->getVentilExportCompta();
899
900 // We check if no payment has been made
901 if ($ventilExportCompta == 0) {
902 if (getDolGlobalString('INVOICE_CAN_BE_EDITED_EVEN_IF_PAYMENT_DONE') || ($resteapayer == $object->total_ttc && empty($object->paye))) {
903 // Set invoice to draft status
904 $result = $object->setDraft($user, $idwarehouse);
905
906 if ($result < 0) {
907 setEventMessages($object->error, $object->errors, 'errors');
908 } else {
909 // Define output language
910 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
911 $outputlangs = $langs;
912 $newlang = '';
913 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
914 $newlang = GETPOST('lang_id', 'aZ09');
915 }
916 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
917 $newlang = $object->thirdparty->default_lang;
918 }
919 if (!empty($newlang)) {
920 $outputlangs = new Translate("", $conf);
921 $outputlangs->setDefaultLang($newlang);
922 $outputlangs->load('products');
923 }
924 $model = $object->model_pdf;
925 $ret = $object->fetch($id); // Reload to get new records
926
927 $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
928 }
929 }
930 }
931 }
932 }
933 } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercanissuepayment) {
934 // Classify "paid"
935 $object->fetch($id);
936 $result = $object->setPaid($user);
937 if ($result < 0) {
938 setEventMessages($object->error, $object->errors, 'errors');
939 }
940 } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercanissuepayment) {
941 // Classif "paid partially"
942 $object->fetch($id);
943 $close_code = GETPOST("close_code", 'restricthtml');
944 $close_note = GETPOST("close_note", 'restricthtml');
945 if ($close_code) {
946 // if VatRefund
947 if (isModEnabled('tax') && $close_code == $object::CLOSECODE_WITHHOLDINGTAX) {
948 require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
949 $resteapayer = GETPOSTFLOAT("resteapayer");
950 $amount = (float) ($resteapayer > 0 ? $resteapayer * -1 : $resteapayer);
951 if ($amount < 0) {
952 $db->begin();
953 $tempTva = new Tva($db);
954 $tempTva->datev = $object->date;
955 $tempTva->datep = $object->date;
956 $tempTva->amount = $amount;
957 $tempTva->label = $langs->trans('WithholdingTax') . ' - ' . $object->ref;
958 //$tempTva->paye = 1;
959 $valid = $tempTva->getIdForLabel($tempTva->label);
960 if (!$valid) {
961 $ret = $tempTva->create($user);
962 if ($ret < 0) {
963 $error++;
964 } else {
965 $tempTva->setPaid($user);
966 }
967 if (empty($error)) {
968 $db->commit();
969 } else {
970 setEventMessages($tempTva->error, $tempTva->errors, 'errors');
971 $db->rollback();
972 }
973 } else {
974 $error++;
975 setEventMessages($langs->trans('LabelWithholdingExist'), $tempTva->errors, 'errors');
976 $db->rollback();
977 }
978 }
979 }
980 if (!$error) {
981 $result = $object->setPaid($user, $close_code, $close_note);
982 if ($result < 0) {
983 setEventMessages($object->error, $object->errors, 'errors');
984 } else {
985 $object->fetch($object->id); // Reload properties
986 }
987 }
988 } else {
989 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
990 }
991 } elseif ($action == 'confirm_canceled' && $confirm == 'yes' && $usercancreate) {
992 // Classify "abandoned"
993 $object->fetch($id);
994 $close_code = GETPOST("close_code", 'restricthtml');
995 $close_note = GETPOST("close_note", 'restricthtml');
996 if ($close_code) {
997 $result = $object->setCanceled($user, $close_code, $close_note);
998 if ($result < 0) {
999 setEventMessages($object->error, $object->errors, 'errors');
1000 } else {
1001 $object->fetch($object->id); // Reload properties
1002 }
1003 } else {
1004 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
1005 }
1006 } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) {
1007 // Convert to discount
1008 $object->fetch($id);
1009 $object->fetch_thirdparty();
1010 //$object->fetch_lines(); // Already done into fetch
1011
1012 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1013 $discountcheck = new DiscountAbsolute($db);
1014 $result = $discountcheck->fetch(0, $object->id);
1015
1016 $canconvert = 0;
1017 if ($object->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1018 $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
1019 }
1020 if (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->paye == 0 && empty($discountcheck->id)) {
1021 $canconvert = 1; // we can convert credit note into discount if credit note is not paid back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
1022 }
1023
1024 if ($canconvert) {
1025 $db->begin();
1026
1027 $amount_ht = $amount_tva = $amount_ttc = $amount_localtax1 = $amount_localtax2 = array();
1028 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1029
1030 // Loop on each vat rate
1031 $i = 0;
1032 foreach ($object->lines as $line) {
1033 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
1034 $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
1035
1036 if (!isset($amount_ht[$keyforvatrate])) {
1037 $amount_ht[$keyforvatrate] = 0;
1038 }
1039 $amount_ht[$keyforvatrate] += $line->total_ht;
1040 if (!isset($amount_tva[$keyforvatrate])) {
1041 $amount_tva[$keyforvatrate] = 0;
1042 }
1043 $amount_tva[$keyforvatrate] += $line->total_tva;
1044 if (!isset($amount_localtax1[$keyforvatrate])) {
1045 $amount_localtax1[$keyforvatrate] = 0;
1046 }
1047 $amount_localtax1[$keyforvatrate] += $line->total_localtax1;
1048 if (!isset($amount_localtax2[$keyforvatrate])) {
1049 $amount_localtax2[$keyforvatrate] = 0;
1050 }
1051 $amount_localtax2[$keyforvatrate] += $line->total_localtax2;
1052 if (!isset($amount_ttc[$keyforvatrate])) {
1053 $amount_ttc[$keyforvatrate] = 0;
1054 }
1055 $amount_ttc[$keyforvatrate] += $line->total_ttc;
1056 if (!isset($multicurrency_amount_ht[$keyforvatrate])) {
1057 $multicurrency_amount_ht[$keyforvatrate] = 0;
1058 }
1059 $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
1060 if (!isset($multicurrency_amount_tva[$keyforvatrate])) {
1061 $multicurrency_amount_tva[$keyforvatrate] = 0;
1062 }
1063 $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
1064 if (!isset($multicurrency_amount_ttc[$keyforvatrate])) {
1065 $multicurrency_amount_ttc[$keyforvatrate] = 0;
1066 }
1067 $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
1068 $i++;
1069 }
1070 }
1071 '@phan-var-force array<string,float> $amount_ht
1072 @phan-var-force array<string,float> $amount_tva
1073 @phan-var-force array<string,float> $amount_ttc
1074 @phan-var-force array<string,float> $amount_localtax1
1075 @phan-var-force array<string,float> $amount_localtax2
1076 @phan-var-force array<string,float> $multicurrency_amount_ht
1077 @phan-var-force array<string,float> $multicurrency_amount_tva
1078 @phan-var-force array<string,float> $multicurrency_amount_ttc';
1079
1080 // If some payments were already done, we change the amount to pay using same prorate
1081 if (getDolGlobalString('INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED') && $object->type == Facture::TYPE_CREDIT_NOTE) {
1082 $alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
1083 if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
1084 $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
1085 foreach ($amount_ht as $vatrate => $val) {
1086 $amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
1087 $amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
1088 $amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
1089 $amount_localtax1[$vatrate] = price2num($amount_localtax1[$vatrate] * $ratio, 'MU');
1090 $amount_localtax2[$vatrate] = price2num($amount_localtax2[$vatrate] * $ratio, 'MU');
1091 $multicurrency_amount_ht[$vatrate] = price2num($multicurrency_amount_ht[$vatrate] * $ratio, 'MU');
1092 $multicurrency_amount_tva[$vatrate] = price2num($multicurrency_amount_tva[$vatrate] * $ratio, 'MU');
1093 $multicurrency_amount_ttc[$vatrate] = price2num($multicurrency_amount_ttc[$vatrate] * $ratio, 'MU');
1094 }
1095 }
1096 }
1097 //var_dump($amount_ht);var_dump($amount_tva);var_dump($amount_ttc);exit;
1098
1099 // Insert one discount by VAT rate category
1100 $discount = new DiscountAbsolute($db);
1101 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1102 $discount->description = '(CREDIT_NOTE)';
1103 } elseif ($object->type == Facture::TYPE_DEPOSIT) {
1104 $discount->description = '(DEPOSIT)';
1106 $discount->description = '(EXCESS RECEIVED)';
1107 } else {
1108 setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
1109 }
1110 $discount->fk_soc = $object->socid;
1111 $discount->socid = $object->socid;
1112 $discount->fk_facture_source = $object->id;
1113
1114 $error = 0;
1115
1116
1117 // Create a discount that is the amount of the excess received
1119 || $object->type == Facture::TYPE_DEPOSIT) {
1120 // If we have an excess received that need to create a discount in TTC without VAT
1121 $discount->description = '(EXCESS RECEIVED)';
1122
1123 // Total payments
1124 $sql = 'SELECT SUM(pf.amount) as total_paiements';
1125 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1126 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1127 $sql .= ' WHERE pf.fk_facture = '.((int) $object->id);
1128 $sql .= ' AND pf.fk_paiement = p.rowid';
1129 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1130 $resql = $db->query($sql);
1131 if (!$resql) {
1133 }
1134
1135 $res = $db->fetch_object($resql);
1136 $total_paiements = $res->total_paiements;
1137
1138 // Total credit note and deposit
1139 $total_creditnote_and_deposit = 0;
1140 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1141 $sql .= " re.description, re.fk_facture_source";
1142 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1143 $sql .= " WHERE fk_facture = ".((int) $object->id);
1144 $resql = $db->query($sql);
1145 if (!empty($resql)) {
1146 while ($obj = $db->fetch_object($resql)) {
1147 $total_creditnote_and_deposit += $obj->amount_ttc;
1148 }
1149 } else {
1151 }
1152
1153 $discount->amount_ttc = price2num($total_paiements + $total_creditnote_and_deposit - $object->total_ttc, 'MT');
1154 $discount->amount_tva = 0;
1155 $discount->amount_ht = $discount->amount_ttc;
1156 $discount->tva_tx = 0;
1157 $discount->localtax1_tx = 0;
1158 $discount->localtax1_type = 0;
1159 $discount->localtax2_tx = 0;
1160 $discount->localtax2_type = 0;
1161 $discount->vat_src_code = '';
1162
1163 if ($discount->amount_ttc > 0) {
1164 $result = $discount->create($user);
1165 if ($result < 0) {
1166 $error++;
1167 }
1168 }
1169 }
1170
1171 // Create a discount that is the amount of the invoice
1173 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1174 $discount->description = '(CREDIT_NOTE)';
1175 } else {
1176 $discount->description = '(DEPOSIT)';
1177 }
1178
1179 foreach ($amount_ht as $tva_tx => $xxx) {
1180 // Get localtaxes from TVA tx
1181 $taxes = getTaxesFromId($tva_tx, $object->thirdparty, $mysoc, 0);
1182
1183 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1184 $discount->amount_ht = -((float) $amount_ht[$tva_tx]);
1185 $discount->amount_tva = -((float) $amount_tva[$tva_tx]);
1186 $discount->amount_ttc = -((float) $amount_ttc[$tva_tx]);
1187 $discount->total_ht = -((float) $amount_ht[$tva_tx]);
1188 $discount->total_tva = -((float) $amount_tva[$tva_tx]);
1189 $discount->total_localtax1 = -((float) $amount_localtax1[$tva_tx]);
1190 $discount->total_localtax2 = -((float) $amount_localtax2[$tva_tx]);
1191 $discount->total_ttc = -((float) $amount_ttc[$tva_tx]);
1192 $discount->multicurrency_amount_ht = -((float) $multicurrency_amount_ht[$tva_tx]);
1193 $discount->multicurrency_amount_tva = -((float) $multicurrency_amount_tva[$tva_tx]);
1194 $discount->multicurrency_amount_ttc = -((float) $multicurrency_amount_ttc[$tva_tx]);
1195 $discount->multicurrency_total_ht = -((float) $multicurrency_amount_ht[$tva_tx]);
1196 $discount->multicurrency_total_tva = -((float) $multicurrency_amount_tva[$tva_tx]);
1197 $discount->multicurrency_total_ttc = -((float) $multicurrency_amount_ttc[$tva_tx]);
1198 } else {
1199 //We keep the absolute value to be consistent with the function used to create the discount in case of deposit in the "create" function of the Payment class
1200 $discount->amount_ht = abs((float) $amount_ht[$tva_tx]);
1201 $discount->amount_tva = abs((float) $amount_tva[$tva_tx]);
1202 $discount->amount_ttc = abs((float) $amount_ttc[$tva_tx]);
1203 $discount->total_ht = abs((float) $amount_ht[$tva_tx]);
1204 $discount->total_tva = abs((float) $amount_tva[$tva_tx]);
1205 $discount->total_localtax1 = abs((float) $amount_localtax1[$tva_tx]);
1206 $discount->total_localtax2 = abs((float) $amount_localtax2[$tva_tx]);
1207 $discount->total_ttc = abs((float) $amount_ttc[$tva_tx]);
1208 $discount->multicurrency_amount_ht = abs((float) $multicurrency_amount_ht[$tva_tx]);
1209 $discount->multicurrency_amount_tva = abs((float) $multicurrency_amount_tva[$tva_tx]);
1210 $discount->multicurrency_amount_ttc = abs((float) $multicurrency_amount_ttc[$tva_tx]);
1211 $discount->multicurrency_total_ht = abs((float) $multicurrency_amount_ht[$tva_tx]);
1212 $discount->multicurrency_total_tva = abs((float) $multicurrency_amount_tva[$tva_tx]);
1213 $discount->multicurrency_total_ttc = abs((float) $multicurrency_amount_ttc[$tva_tx]);
1214 }
1215
1216 // Clean vat code
1217 $reg = array();
1218 $vat_src_code = '';
1219 if (preg_match('/\‍((.*)\‍)/', $tva_tx, $reg)) {
1220 $vat_src_code = $reg[1];
1221 $tva_tx = preg_replace('/\s*\‍(.*\‍)/', '', $tva_tx); // Remove code into vatrate.
1222 }
1223
1224 $discount->tva_tx = abs((float) $tva_tx);
1225 $discount->localtax1_tx = $taxes['localtax1'];
1226 $discount->localtax1_type = $taxes['localtax1_type'];
1227 $discount->localtax2_tx = $taxes['localtax2'];
1228 $discount->localtax2_type = $taxes['localtax2_type'];
1229 $discount->vat_src_code = $vat_src_code;
1230
1231 $result = $discount->create($user);
1232 if ($result < 0) {
1233 $error++;
1234 break;
1235 }
1236 }
1237 }
1238
1239 if (empty($error)) {
1240 // Set invoice as paid, unless it's a down payment converted to credit without any payment received
1241 // (option DEPOSIT_CAN_BE_CONVERTED_AS_AVAILABLE_CREDIT_EVEN_IF_NOT_YET_PAID allows creating the discount/credit even if the down payment
1242 // has not been paid yet; in that case we must NOT mark it as paid since no payment was actually received)
1243 $skipSetPaid = ($object->type == Facture::TYPE_DEPOSIT && getDolGlobalInt('DEPOSIT_CAN_BE_CONVERTED_AS_AVAILABLE_CREDIT_EVEN_IF_NOT_YET_PAID') && price2num($object->getSommePaiement(), 'MT') == 0);
1244
1245 if ($skipSetPaid) {
1246 $object->fetch($object->id); // Reload properties
1247 $db->commit();
1248 } else {
1249 $result = $object->setPaid($user); // We can close the invoice. Even if we got an excess received, it is now into discounts.
1250 if ($result >= 0) {
1251 $object->fetch($object->id); // Reload properties
1252 $db->commit();
1253 } else {
1254 setEventMessages($object->error, $object->errors, 'errors');
1255 $db->rollback();
1256 }
1257 }
1258 } else {
1259 setEventMessages($discount->error, $discount->errors, 'errors');
1260 $db->rollback();
1261 }
1262 }
1263 } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercanissuepayment) {
1264 // Delete payment
1265 $object->fetch($id);
1266 if ($object->status == Facture::STATUS_VALIDATED && $object->paye == 0) {
1267 $paiement = new Paiement($db);
1268 $result = $paiement->fetch(GETPOSTINT('paiement_id'));
1269 $paymentbills = ($result > 0) ? $paiement->getBillsArray() : array();
1270 if ($result > 0 && is_array($paymentbills) && in_array($object->id, $paymentbills)) { // The payment must be linked to this invoice
1271 $result = $paiement->delete($user); // If fetch ok and found
1272 if ($result >= 0) {
1273 header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
1274 exit;
1275 }
1276 if ($result < 0) {
1277 setEventMessages($paiement->error, $paiement->errors, 'errors');
1278 }
1279 } else {
1280 setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors');
1281 }
1282 }
1283 } elseif ($action == 'add' && $usercancreate) {
1284 // Insert new invoice in database
1285 if ($socid > 0) {
1286 $object->socid = GETPOSTINT('socid');
1287 }
1288
1289 if (GETPOST('type') === '') {
1290 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
1291 }
1292
1293 $db->begin();
1294
1295 $originentity = GETPOSTINT('originentity');
1296 $object->demand_reason_id = $inputReasonId;
1297
1298 // Fill array 'array_options' with data from add form
1299 $ret = $extrafields->setOptionalsFromPost(null, $object);
1300 if ($ret < 0) {
1301 $error++;
1302 }
1303
1304 $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
1305 $date_pointoftax = dol_mktime(0, 0, 0, GETPOSTINT('date_pointoftaxmonth'), GETPOSTINT('date_pointoftaxday'), GETPOSTINT('date_pointoftaxyear'), 'tzserver');
1306
1307 $classname = null;
1308
1309
1310 // Add a Replacement invoice
1311 if (GETPOST('type') == Facture::TYPE_REPLACEMENT) {
1312 if (empty($dateinvoice)) {
1313 $error++;
1314 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1315 $action = 'create';
1316 } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1317 $error++;
1318 setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1319 $action = 'create';
1320 }
1321
1322 if (!(GETPOSTINT('fac_replacement') > 0)) {
1323 $error++;
1324 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
1325 $action = 'create';
1326 }
1327
1328 if (!$error) {
1329 // This is a replacement invoice
1330 $result = $object->fetch(GETPOSTINT('fac_replacement'));
1331 $object->fetch_thirdparty();
1332
1333 $object->date = $dateinvoice;
1334 $object->date_pointoftax = $date_pointoftax;
1335 $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1336 $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
1337 $object->ref_client = GETPOST('ref_client', 'alphanohtml');
1338 $object->ref_customer = GETPOST('ref_client', 'alphanohtml');
1339 $object->model_pdf = GETPOST('model', 'alphanohtml');
1340 $object->fk_project = GETPOSTINT('projectid');
1341 $object->cond_reglement_id = GETPOSTINT('cond_reglement_id');
1342 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
1343 $object->fk_account = GETPOSTINT('fk_account');
1344 $object->fk_incoterms = GETPOSTINT('incoterm_id');
1345 $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1346 $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1347 $object->multicurrency_tx = GETPOSTFLOAT('originmulticurrency_tx');
1348
1349 // Special properties of replacement invoice
1350 $object->fk_facture_source = GETPOSTINT('fac_replacement');
1352
1353 $id = $object->createFromCurrent($user);
1354 if ($id <= 0) {
1355 setEventMessages($object->error, $object->errors, 'errors');
1356 }
1357 }
1358 }
1359
1360 // Add a Credit note invoice
1361 if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) {
1362 $sourceinvoice = GETPOSTINT('fac_avoir');
1363 if (!($sourceinvoice > 0) && !getDolGlobalString('INVOICE_CREDIT_NOTE_STANDALONE')) {
1364 $error++;
1365 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceAvoirAskCombo")), null, 'errors');
1366 $action = 'create';
1367 }
1368
1369 if (empty($dateinvoice)) {
1370 $error++;
1371 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1372 $action = 'create';
1373 } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1374 $error++;
1375 setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1376 $action = 'create';
1377 }
1378
1379 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED') && empty(GETPOST("subtype"))) {
1380 $error++;
1381 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSubtype")), null, 'errors');
1382 $action = 'create';
1383 }
1384
1385 if (!$error) {
1386 if (!empty($originentity)) {
1387 $object->entity = $originentity;
1388 }
1389 $object->socid = GETPOSTINT('socid');
1390 $object->subtype = GETPOSTINT('subtype');
1391 $object->ref = GETPOST('ref');
1392 $object->date = $dateinvoice;
1393 $object->date_pointoftax = $date_pointoftax;
1394 $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1395 $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
1396 $object->ref_client = GETPOST('ref_client', 'alphanohtml');
1397 $object->ref_customer = GETPOST('ref_client', 'alphanohtml');
1398 $object->model_pdf = GETPOST('model');
1399 $object->fk_project = GETPOSTINT('projectid');
1400 $object->cond_reglement_id = 0; // No payment term for a credit note
1401 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
1402 $object->fk_account = GETPOSTINT('fk_account');
1403 $object->fk_incoterms = GETPOSTINT('incoterm_id');
1404 $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1405 $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1406 $object->multicurrency_tx = GETPOSTFLOAT('originmulticurrency_tx');
1407
1408 // Special properties of replacement invoice
1409 $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
1411
1412 $facture_source = new Facture($db); // fetch origin object
1413 if ($object->fk_facture_source > 0 && $facture_source->fetch($object->fk_facture_source) > 0) {
1414 if ($facture_source->isSituationInvoice()) {
1415 $object->situation_counter = $facture_source->situation_counter;
1416 $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
1417 $facture_source->fetchPreviousNextSituationInvoice();
1418 }
1419
1420 $object->pos_source = $facture_source->pos_source; // We must reuse the same than original values so correction will appear in same terminal same original invoice for conformity
1421 $object->module_source = $facture_source->module_source; // We must reuse the same than original values so correction will appear in same terminal same original invoice for conformity
1422 }
1423
1424 $id = $object->create($user);
1425 if ($id < 0) {
1426 $error++;
1427 } else {
1428 // copy internal contacts
1429 if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
1430 $error++;
1431 } elseif ($facture_source->socid == $object->socid) {
1432 // copy external contacts if same company
1433 if ($object->copy_linked_contact($facture_source, 'external') < 0) {
1434 $error++;
1435 }
1436 }
1437 }
1438
1439 // NOTE: Pb with situation invoice when INVOICE_USE_SITUATION=1 (legacy mode)
1440 // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
1441 // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
1442 // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
1443 // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
1444 if (GETPOSTINT('invoiceAvoirWithLines') == 1 && $id > 0) {
1445 if (!empty($facture_source->lines)) {
1446 $fk_parent_line = 0;
1447
1448 foreach ($facture_source->lines as $line) {
1449 // Extrafields
1450 if (method_exists($line, 'fetch_optionals')) {
1451 // load extrafields
1452 $line->fetch_optionals();
1453 }
1454
1455 // Reset fk_parent_line for no child products and special product
1456 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1457 $fk_parent_line = 0;
1458 }
1459
1460
1461 if ($facture_source->isSituationInvoice()) {
1462 $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
1463 $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
1464
1465 // The subtraction below assumes total_ht/situation_percent are stored cumulative on situation invoice lines
1466 // (INVOICE_USE_SITUATION = 1, legacy). In progressive mode (INVOICE_USE_SITUATION = 2), each line already
1467 // holds its own delta, so subtracting the previous invoice's line here would credit the wrong amount.
1468 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1 && !empty($facture_source->tab_previous_situation_invoice)) {
1469 // search the last standard invoice in cycle and the possible credit note between this last and facture_source
1470 // TODO Move this out of loop of $facture_source->lines
1471 $tab_jumped_credit_notes = array();
1472 $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
1473 $searchPreviousInvoice = true;
1474 while ($searchPreviousInvoice) {
1475 if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
1476 $searchPreviousInvoice = false; // find, exit;
1477 break;
1478 } else {
1479 if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
1480 $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
1481 }
1482 $lineIndex--; // go to previous invoice in cycle
1483 }
1484 }
1485
1486 $maxPrevSituationPercent = 0;
1487 foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
1488 if ($prevLine->id == $source_fk_prev_id) {
1489 $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
1490
1491 //$line->subprice = $line->subprice - $prevLine->subprice;
1492 $line->total_ht -= $prevLine->total_ht;
1493 $line->total_tva -= $prevLine->total_tva;
1494 $line->total_ttc -= $prevLine->total_ttc;
1495 $line->total_localtax1 -= $prevLine->total_localtax1;
1496 $line->total_localtax2 -= $prevLine->total_localtax2;
1497
1498 $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
1499 $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
1500 $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
1501 $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
1502 }
1503 }
1504
1505 // prorata
1506 $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
1507
1508 //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
1509
1510 // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
1511 $maxPrevSituationPercent = 0;
1512 foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
1513 foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
1514 if ($prevLine->fk_prev_id == $source_fk_prev_id) {
1515 $maxPrevSituationPercent = $prevLine->situation_percent;
1516
1517 $line->total_ht -= $prevLine->total_ht;
1518 $line->total_tva -= $prevLine->total_tva;
1519 $line->total_ttc -= $prevLine->total_ttc;
1520 $line->total_localtax1 -= $prevLine->total_localtax1;
1521 $line->total_localtax2 -= $prevLine->total_localtax2;
1522
1523 $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
1524 $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
1525 $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
1526 $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
1527 }
1528 }
1529 }
1530
1531 // prorata
1532 $line->situation_percent += $maxPrevSituationPercent;
1533
1534 //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
1535 }
1536 }
1537
1538 $line->fk_facture = $object->id;
1539 $line->fk_parent_line = $fk_parent_line;
1540
1541 $line->subprice = -$line->subprice; // invert price for object
1542 // $line->pa_ht = $line->pa_ht; // we chose to have buy/cost price always positive, so no revert of sign here
1543 $line->total_ht = -$line->total_ht;
1544 $line->total_tva = -$line->total_tva;
1545 $line->total_ttc = -$line->total_ttc;
1546 $line->total_localtax1 = -$line->total_localtax1;
1547 $line->total_localtax2 = -$line->total_localtax2;
1548
1549 $line->multicurrency_subprice = -$line->multicurrency_subprice;
1550 $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
1551 $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
1552 $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
1553
1554 $line->context['createcreditnotefrominvoice'] = 1;
1555 $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount already linked
1556
1557 $object->lines[] = $line; // insert new line in current object
1558
1559 // Defined the new fk_parent_line
1560 if ($result > 0 && $line->product_type == 9) {
1561 $fk_parent_line = $result;
1562 }
1563 }
1564
1565 $object->update_price(1);
1566 }
1567 }
1568
1569 if (GETPOSTINT('invoiceAvoirWithPaymentRestAmount') == 1 && $id > 0) {
1570 if ($facture_source->fetch($object->fk_facture_source) > 0) {
1571 $totalpaid = $facture_source->getSommePaiement();
1572 $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
1573 $totaldeposits = $facture_source->getSumDepositsUsed();
1574 $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
1575
1576 if (getDolGlobalString('INVOICE_VAT_TO_USE_ON_CREDIT_NOTE_WHEN_GENERATED_FROM_REMAIN_TO_PAY') == 'default') {
1577 if ((empty($object->thirdparty) || !is_object($object->thirdparty) || get_class($object->thirdparty) != 'Societe')) {
1578 $object->fetch_thirdparty();
1579 }
1580 if (!empty($object->thirdparty) && is_object($object->thirdparty) && get_class($object->thirdparty) == 'Societe') {
1581 $tva_tx = get_default_tva($mysoc, $object->thirdparty);
1582 } else {
1583 $tva_tx = 0;
1584 }
1585 } elseif ((float) getDolGlobalString('INVOICE_VAT_TO_USE_ON_CREDIT_NOTE_WHEN_GENERATED_FROM_REMAIN_TO_PAY') > 0) {
1586 $tva_tx = (float) getDolGlobalString('INVOICE_VAT_TO_USE_ON_CREDIT_NOTE_WHEN_GENERATED_FROM_REMAIN_TO_PAY');
1587 } else {
1588 $tva_tx = 0;
1589 }
1590
1591 // Pass the amount already signed: addline() forces -abs() on credit notes with the default setup, so this
1592 // changes nothing there, but it keeps the line negative when that forcing is relaxed (see addline()).
1593 $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), 0, 1, $tva_tx, 0, 0, 0, 0, '', '', 0, 0, 0, 'TTC', -$remain_to_pay);
1594 }
1595 }
1596
1597 // Add link between credit note and origin
1598 if (!empty($object->fk_facture_source) && $id > 0) {
1599 $facture_source->fetch($object->fk_facture_source);
1600 $facture_source->fetchObjectLinked();
1601
1602 if (!empty($facture_source->linkedObjectsIds)) {
1603 foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
1604 $object->add_object_linked($sourcetype, current($TIds));
1605 }
1606 }
1607 }
1608 }
1609 }
1610
1611 // Standard invoice or Deposit invoice, created from a Predefined template invoice
1612 if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT) && GETPOSTINT('fac_rec') > 0) {
1613 if (empty($dateinvoice)) {
1614 $error++;
1615 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1616 $action = 'create';
1617 } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1618 $error++;
1619 setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1620 $action = 'create';
1621 }
1622
1623
1624 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED') && empty(GETPOST("subtype"))) {
1625 $error++;
1626 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSubtype")), null, 'errors');
1627 $action = 'create';
1628 }
1629
1630 if (!$error) {
1631 $object->socid = GETPOSTINT('socid');
1632 $object->type = GETPOSTINT('type');
1633 $object->subtype = GETPOSTINT('subtype');
1634 $object->ref = GETPOST('ref');
1635 $object->date = $dateinvoice;
1636 $object->date_pointoftax = $date_pointoftax;
1637 $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1638 $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
1639
1640 $object->ref_customer = GETPOST('ref_client');
1641
1642 $object->model_pdf = GETPOST('model');
1643 $object->fk_project = GETPOSTINT('projectid');
1644 $object->cond_reglement_id = (GETPOSTINT('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
1645 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
1646 $object->fk_account = GETPOSTINT('fk_account');
1647 $object->amount = price2num(GETPOST('amount'));
1648 $object->fk_incoterms = GETPOSTINT('incoterm_id');
1649 $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1650 $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1651 $object->multicurrency_tx = GETPOSTFLOAT('originmulticurrency_tx');
1652
1653 // Source facture
1654 $object->fac_rec = GETPOSTINT('fac_rec');
1655
1656 $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines
1657 }
1658 }
1659
1660 // Standard or deposit invoice, not from a Predefined template invoice
1661 if ((GETPOST('type') == Facture::TYPE_STANDARD
1662 || GETPOST('type') == Facture::TYPE_DEPOSIT
1663 || GETPOST('type') == Facture::TYPE_PROFORMA
1664 || (GETPOST('type') == Facture::TYPE_SITUATION && GETPOSTINT('situations') <= 0))
1665 && GETPOST('fac_rec') <= 0) {
1666 $typeamount = GETPOST('typedeposit', 'aZ09');
1667 $valuestandardinvoice = price2num(str_replace('%', '', GETPOST('valuestandardinvoice', 'alpha')), 'MU');
1668 $valuedeposit = price2num(str_replace('%', '', GETPOST('valuedeposit', 'alpha')), 'MU');
1669
1670 if (GETPOSTINT('socid') < 1) {
1671 $error++;
1672 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
1673 $action = 'create';
1674 }
1675
1676 if (empty($dateinvoice)) {
1677 $error++;
1678 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1679 $action = 'create';
1680 } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1681 $error++;
1682 setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1683 $action = 'create';
1684 }
1685
1686
1687 if (GETPOST('type') == Facture::TYPE_STANDARD) {
1688 if ($valuestandardinvoice < 0 || $valuestandardinvoice > 100) {
1689 setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
1690 $error++;
1691 $action = 'create';
1692 }
1693 } elseif (GETPOST('type') == Facture::TYPE_DEPOSIT) {
1694 if ($typeamount && !empty($origin) && !empty($originid)) {
1695 if ($typeamount == 'amount' && $valuedeposit <= 0) {
1696 setEventMessages($langs->trans("ErrorAnAmountWithoutTaxIsRequired"), null, 'errors');
1697 $error++;
1698 $action = 'create';
1699 }
1700 if ($typeamount == 'variable' && $valuedeposit <= 0) {
1701 setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
1702 $error++;
1703 $action = 'create';
1704 }
1705 if ($typeamount == 'variablealllines' && $valuedeposit <= 0) {
1706 setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
1707 $error++;
1708 $action = 'create';
1709 }
1710 }
1711 }
1712
1713
1714 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED') && empty(GETPOST("subtype"))) {
1715 $error++;
1716 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSubtype")), null, 'errors');
1717 $action = 'create';
1718 }
1719
1720 if (!$error) {
1721 $object->socid = GETPOSTINT('socid');
1722 $object->type = GETPOSTINT('type');
1723 $object->subtype = GETPOSTINT('subtype');
1724 $object->ref = GETPOST('ref');
1725 $object->date = $dateinvoice;
1726 $object->date_pointoftax = $date_pointoftax;
1727 $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1728 $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
1729 $object->ref_client = GETPOST('ref_client');
1730 $object->ref_customer = GETPOST('ref_client');
1731 $object->model_pdf = GETPOST('model');
1732 $object->fk_project = GETPOSTINT('projectid');
1733 $object->cond_reglement_id = (GETPOSTINT('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
1734 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
1735 $object->fk_account = GETPOSTINT('fk_account');
1736 $object->amount = price2num(GETPOST('amount'));
1737 $object->fk_incoterms = GETPOSTINT('incoterm_id');
1738 $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1739 $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1740 $object->multicurrency_tx = GETPOSTFLOAT('originmulticurrency_tx');
1741
1742 if (GETPOST('type') == Facture::TYPE_SITUATION) {
1743 $object->situation_counter = 1;
1744 $object->situation_final = 0;
1745 $object->situation_cycle_ref = $object->newCycle();
1746 }
1747
1748 if (in_array($object->type, $retainedWarrantyInvoiceAvailableType)) {
1749 $object->retained_warranty = GETPOSTINT('retained_warranty');
1750 $object->retained_warranty_fk_cond_reglement = GETPOSTINT('retained_warranty_fk_cond_reglement');
1751 } else {
1752 $object->retained_warranty = 0;
1753 $object->retained_warranty_fk_cond_reglement = 0;
1754 }
1755
1756 $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
1757 if (!empty($retained_warranty_date_limit) && dol_stringtotime($retained_warranty_date_limit)) {
1758 $object->retained_warranty_date_limit = dol_stringtotime($retained_warranty_date_limit);
1759 }
1760 $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
1761
1762 $object->fetch_thirdparty();
1763
1764 // If creation from another object of another module (Example: origin=propal, originid=1)
1765 if (!empty($origin) && !empty($originid)) {
1766 $regs = array();
1767 // Parse element/subelement (ex: project_task)
1768 $element = $subelement = $origin;
1769 if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
1770 $element = $regs[1];
1771 $subelement = $regs[2];
1772 }
1773
1774 // For compatibility
1775 if ($element == 'order') {
1776 $element = $subelement = 'commande';
1777 }
1778 if ($element == 'propal') {
1779 $element = 'comm/propal';
1780 $subelement = 'propal';
1781 }
1782 if ($element == 'contract') {
1783 $element = $subelement = 'contrat';
1784 }
1785 if ($element == 'inter') {
1786 $element = $subelement = 'fichinter';
1787 }
1788 if ($element == 'shipping') {
1789 $element = $subelement = 'expedition';
1790 }
1791
1792 $object->origin = $origin; // deprecated
1793 $object->origin_type = $origin;
1794 $object->origin_id = $originid;
1795
1796 // Possibility to add external linked objects with hooks
1797 $object->linked_objects[$object->origin_type] = $object->origin_id;
1798 // link with order if it is a shipping invoice
1799 if ($object->origin == 'shipping') {
1800 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1801 $exp = new Expedition($db);
1802 $exp->fetch($object->origin_id);
1803 $exp->fetchObjectLinked();
1804 if (is_array($exp->linkedObjectsIds['commande']) && count($exp->linkedObjectsIds['commande']) > 0) {
1805 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1806 $object->linked_objects['commande'] = $value;
1807 }
1808 }
1809 }
1810
1811 if (GETPOSTISARRAY('other_linked_objects')) {
1812 $object->linked_objects = array_merge($object->linked_objects, GETPOST('other_linked_objects', 'array:int'));
1813 }
1814
1815 $id = $object->create($user); // This include class to add_object_linked() and add add_contact()
1816
1817 if ($id > 0) {
1818 dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1819
1820 $classname = ucfirst($subelement);
1821 $srcobject = new $classname($db);
1822 '@phan-var-force CommonObject $srcobject';
1823
1824 dol_syslog("Try to find source object origin_type=".$object->origin_type." origin_id=".$object->origin_id." to add lines or deposit lines");
1825 $result = $srcobject->fetch($object->origin_id);
1826
1827 $i = -1; // Ensure initialised for static analysis, but with invalid idx.
1828 // If deposit invoice - down payment with 1 line (fixed amount or percent)
1829 if (GETPOST('type') == Facture::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) {
1830 // Define the array $amountdeposit
1831 $amountdeposit = array();
1832 $lines = array();
1833 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA')) { // We want to split the discount line into several lines, one per vat rate.
1834 if ($typeamount == 'amount') {
1835 $amount = (float) $valuedeposit;
1836 } else {
1837 $amount = $srcobject->total_ttc * ((float) $valuedeposit / 100);
1838 }
1839
1840 $TTotalByTva = array();
1841 foreach ($srcobject->lines as &$line) {
1842 if (empty($line->qty)) {
1843 continue; // We discard qty=0, it is an option
1844 }
1845 if (!empty($line->special_code)) {
1846 continue;
1847 }
1848 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1849 }
1850 '@phan-var-force array<string,float> $TTotalByTva';
1851
1852 $amount_ttc_diff = 0.;
1853 foreach ($TTotalByTva as $tva => &$total) {
1854 if (empty($amountdeposit[$tva])) {
1855 $amountdeposit[$tva] = 0;
1856 }
1857 $coef = $total / $srcobject->total_ttc; // Calc coef
1858 $am = $amount * $coef;
1859 $amount_ttc_diff += $am;
1860 $amountdeposit[$tva] += $am / (1 + (float) $tva / 100); // Convert into HT for the addline
1861 }
1862 } else {
1863 if ($typeamount == 'amount') {
1864 $amountdeposit[0] = $valuedeposit;
1865 } elseif ($typeamount == 'variable') {
1866 if ($result > 0) {
1867 $totalamount = 0;
1868 $lines = $srcobject->lines;
1869 $numlines = count($lines);
1870 for ($i = 0; $i < $numlines; $i++) {
1871 $qualified = 1;
1872 if (empty($lines[$i]->qty)) {
1873 $qualified = 0; // We discard qty=0, it is an option
1874 }
1875 if (!empty($lines[$i]->special_code)) {
1876 $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...)
1877 }
1878 if ($qualified) {
1879 $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1880 $tva_tx = $lines[$i]->tva_tx;
1881
1882 if (empty($amountdeposit[$tva_tx])) {
1883 $amountdeposit[$tva_tx] = 0;
1884 }
1885 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * (float) $valuedeposit) / 100;
1886 }
1887 }
1888
1889 if ($totalamount == 0) {
1890 $amountdeposit[0] = 0;
1891 }
1892 } else {
1893 setEventMessages($srcobject->error, $srcobject->errors, 'errors');
1894 $error++;
1895 }
1896 }
1897
1898 $amount_ttc_diff = $amountdeposit[0];
1899 }
1900
1901 foreach ($amountdeposit as $tva => $amount) {
1902 if (empty($amount)) {
1903 continue;
1904 }
1905
1906 // Cost price of the line: cost of the source lines with the same vat rate (all lines for a fixed amount), prorated
1907 // to the amount of the line, like a down payment from a percent of all lines that keeps the cost price of each line.
1908 $totalhtofsource = 0;
1909 $totalcostofsource = 0;
1910 foreach ((is_array($srcobject->lines) ? $srcobject->lines : array()) as $srcline) {
1911 if (empty($srcline->qty) || !empty($srcline->special_code)) {
1912 continue;
1913 }
1914 if (($typeamount == 'amount' && !getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA')) || price2num($srcline->tva_tx) == price2num(preg_replace('/\s*\‍(.*\‍)/', '', (string) $tva))) {
1915 $totalhtofsource += (float) $srcline->total_ht;
1916 $totalcostofsource += (float) $srcline->qty * (float) $srcline->pa_ht;
1917 }
1918 }
1919 $pa_ht = ($totalhtofsource != 0 ? (float) price2num($amount * $totalcostofsource / $totalhtofsource, 'MU') : 0);
1920
1921 $arraylist = array(
1922 'amount' => 'FixAmount',
1923 'variable' => 'VarAmount'
1924 );
1925 $descline = '(DEPOSIT)';
1926 //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
1927 if ($typeamount == 'amount') {
1928 $descline .= ' ('.price($valuedeposit, 0, $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')';
1929 } elseif ($typeamount == 'variable') {
1930 $descline .= ' ('.$valuedeposit.'%)';
1931 }
1932
1933 $descline .= ' - '.$srcobject->ref;
1934 $result = $object->addline(
1935 $descline,
1936 (float) $amount, // subprice
1937 1, // quantity
1938 $tva, // vat rate
1939 0, // localtax1_tx
1940 0, // localtax2_tx
1941 getDolGlobalInt('INVOICE_PRODUCTID_DEPOSIT'), // fk_product
1942 0, // remise_percent
1943 0, // date_start
1944 0, // date_end
1945 0,
1946 isset($lines[$i]) ? $lines[$i]->info_bits : 0, // info_bits
1947 0,
1948 'HT',
1949 0,
1950 0, // product_type
1951 1,
1952 isset($lines[$i]) ? $lines[$i]->special_code : 0,
1953 $object->origin_type,
1954 0,
1955 0,
1956 0,
1957 $pa_ht, // pa_ht
1958 '',
1959 array(), // array_options
1960 100,
1961 0,
1962 null,
1963 0,
1964 '',
1965 (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA') ? 0 : 1)
1966 );
1967 }
1968
1969 $diff = $object->total_ttc - $amount_ttc_diff;
1970
1971 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA') && $diff != 0) {
1972 $object->fetch_lines();
1973 $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
1974 $object->updateline($object->lines[0]->id, $object->lines[0]->desc, $subprice_diff, $object->lines[0]->qty, $object->lines[0]->remise_percent, $object->lines[0]->date_start, $object->lines[0]->date_end, $object->lines[0]->tva_tx, 0, 0, 'HT', $object->lines[0]->info_bits, $object->lines[0]->product_type, 0, 0, 0, $object->lines[0]->pa_ht, $object->lines[0]->label, 0, array(), 100);
1975 }
1976 }
1977
1978 // standard invoice, credit note, or down payment from a percent of all lines
1979 if (GETPOST('type') != Facture::TYPE_DEPOSIT || (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines')) {
1980 $lines = array();
1981
1982 if ($result > 0) {
1983 $lines = $srcobject->lines;
1984 if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
1985 $srcobject->fetch_lines();
1986 $lines = $srcobject->lines;
1987 }
1988
1989 // If we create a standard invoice with a percent, we change amount by changing the qty
1990 if (GETPOST('type') == Facture::TYPE_STANDARD && $valuestandardinvoice > 0 && $valuestandardinvoice < 100) {
1991 if (is_array($lines)) {
1992 foreach ($lines as $line) {
1993 // We keep ->subprice and ->pa_ht, but we change the qty
1994 $line->qty = (float) price2num((float) $line->qty * (float) $valuestandardinvoice / 100, 'MS');
1995 }
1996 }
1997 }
1998 // If we create a down payment with a percent on all lines, we change amount by changing the qty
1999 if (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines') {
2000 if (is_array($lines)) {
2001 foreach ($lines as $line) {
2002 // We keep ->subprice and ->pa_ht, but we change the qty
2003 $line->qty = (float) price2num((float) $line->qty * (float) $valuedeposit / 100, 'MS');
2004 }
2005 }
2006 }
2007
2008 $fk_parent_line = 0;
2009 $num = count($lines);
2010
2011 for ($i = 0; $i < $num; $i++) {
2012 if (!in_array($lines[$i]->id, $selectedLines)) {
2013 continue; // Skip unselected lines
2014 }
2015
2016 // Don't add lines with qty 0 when coming from a shipment including all order lines
2017 if ($srcobject->element == 'shipping' && getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS') && $lines[$i]->qty == 0) {
2018 continue;
2019 }
2020 // Don't add closed lines when coming from a contract (Set constant to '0,5' to exclude also inactive lines)
2021 if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) {
2022 $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5';
2023 }
2024 if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', getDolGlobalString('CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE')))) {
2025 continue;
2026 }
2027
2028 $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
2029 $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : '');
2030
2031 if ($object->situation_counter == 1) {
2032 $lines[$i]->situation_percent = 0;
2033 }
2034
2035 if ($lines[$i]->subprice < 0 && !getDolGlobalString('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN')) {
2036 // Negative line, we create a discount line
2037 if (empty($desc)) {
2038 $desc = $label ? $label : $langs->trans('Discount');
2039 }
2040
2041 $discount = new DiscountAbsolute($db);
2042 $discount->fk_soc = $object->socid;
2043 $discount->socid = $object->socid;
2044 $discount->amount_ht = abs($lines[$i]->total_ht);
2045 $discount->amount_tva = abs($lines[$i]->total_tva);
2046 $discount->amount_ttc = abs($lines[$i]->total_ttc);
2047 $discount->total_ht = abs($lines[$i]->total_ht);
2048 $discount->total_tva = abs($lines[$i]->total_tva);
2049 $discount->total_ttc = abs($lines[$i]->total_ttc);
2050 $discount->tva_tx = $lines[$i]->tva_tx;
2051 $discount->localtax1_tx = $lines[$i]->localtax1_tx;
2052 $discount->localtax2_tx = $lines[$i]->localtax2_tx;
2053 $discount->localtax1_type = $lines[$i]->localtax1_type;
2054 $discount->localtax2_type = $lines[$i]->localtax2_type;
2055 $discount->total_localtax1 = abs($lines[$i]->total_localtax1);
2056 $discount->total_localtax2 = abs($lines[$i]->total_localtax2);
2057 $discount->fk_user = $user->id;
2058 $discount->description = $desc;
2059 $discount->multicurrency_subprice = abs($lines[$i]->multicurrency_subprice);
2060 $discount->multicurrency_amount_ht = abs($lines[$i]->multicurrency_total_ht);
2061 $discount->multicurrency_amount_tva = abs($lines[$i]->multicurrency_total_tva);
2062 $discount->multicurrency_amount_ttc = abs($lines[$i]->multicurrency_total_ttc);
2063 $discount->multicurrency_total_ht = abs($lines[$i]->multicurrency_total_ht);
2064 $discount->multicurrency_total_tva = abs($lines[$i]->multicurrency_total_tva);
2065 $discount->multicurrency_total_ttc = abs($lines[$i]->multicurrency_total_ttc);
2066
2067 $discountid = $discount->create($user);
2068 if ($discountid > 0) {
2069 $result = $object->insert_discount($discountid); // This include link_to_invoice
2070 } else {
2071 setEventMessages($discount->error, $discount->errors, 'errors');
2072 $error++;
2073 break;
2074 }
2075 } else {
2076 // Positive line
2077 // we keep first type from product if exist, otherwise we keep type from line (free line) and at last default Product
2078 $product_type = $lines[$i]->product_type ?? ($lines[$i]->type ?? Product::TYPE_PRODUCT);
2079
2080 // Date start
2081 $date_start = false;
2082 if (isset($lines[$i]->date_debut_prevue)) {
2083 $date_start = $lines[$i]->date_debut_prevue;
2084 }
2085 if (isset($lines[$i]->date_debut_reel)) {
2086 $date_start = $lines[$i]->date_debut_reel;
2087 }
2088 if (isset($lines[$i]->date_start)) {
2089 $date_start = $lines[$i]->date_start;
2090 }
2091
2092 // Date end
2093 $date_end = false;
2094 if (isset($lines[$i]->date_fin_prevue)) {
2095 $date_end = $lines[$i]->date_fin_prevue;
2096 }
2097 if (isset($lines[$i]->date_fin_reel)) {
2098 $date_end = $lines[$i]->date_fin_reel;
2099 }
2100 if (isset($lines[$i]->date_end)) {
2101 $date_end = $lines[$i]->date_end;
2102 }
2103
2104 // Reset fk_parent_line for no child products and special product
2105 if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
2106 $fk_parent_line = 0;
2107 }
2108
2109 $array_options = array();
2110 // Extrafields
2111 if (method_exists($lines[$i], 'fetch_optionals')) {
2112 $lines[$i]->fetch_optionals();
2113 $array_options = $lines[$i]->array_options;
2114 }
2115
2116 $tva_tx = $lines[$i]->tva_tx;
2117 if (!empty($lines[$i]->vat_src_code) && !preg_match('/\‍(/', (string) $tva_tx)) {
2118 $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
2119 }
2120
2121 // View third's localtaxes for NOW and do not use value from origin.
2122 // TODO Is this really what we want ? Yes if source is template invoice but what if proposal or order ?
2123 $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
2124 $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
2125
2126 $result = $object->addline(
2127 $desc,
2128 $lines[$i]->subprice,
2129 $lines[$i]->qty,
2130 $tva_tx,
2131 $localtax1_tx,
2132 $localtax2_tx,
2133 $lines[$i]->fk_product,
2134 $lines[$i]->remise_percent,
2136 $date_end,
2137 0,
2138 (int) $lines[$i]->info_bits,
2139 isset($lines[$i]->fk_remise_except) ? $lines[$i]->fk_remise_except : null,
2140 'HT',
2141 0,
2142 $product_type,
2143 $lines[$i]->rang,
2144 $lines[$i]->special_code,
2145 $object->origin_type,
2146 $lines[$i]->rowid,
2147 $fk_parent_line,
2148 isset($lines[$i]->fk_fournprice) ? $lines[$i]->fk_fournprice : null,
2149 $lines[$i]->pa_ht,
2150 $label,
2151 $array_options,
2152 $lines[$i]->situation_percent ?? 100,
2153 $lines[$i]->fk_prev_id ?? 0,
2154 $lines[$i]->fk_unit,
2155 0,
2156 '',
2157 1 // noupdateafterinsertline: update_price() is called once after the loop, calling it per line is quadratic
2158 );
2159
2160 if ($result > 0) {
2161 foreach ($object->lines as $line) {
2162 if ($line->id == $result) {
2163 $line->extraparams = $lines[$i]->extraparams;
2164 $line->setExtraParameters();
2165 }
2166 }
2167
2168 $lineid = $result;
2169 } else {
2170 $lineid = 0;
2171 $error++;
2172 break;
2173 }
2174
2175 // Defined the new fk_parent_line
2176 if ($result > 0 && $lines[$i]->product_type == 9) {
2177 $fk_parent_line = $result;
2178 }
2179 }
2180 }
2181 } else {
2182 setEventMessages($srcobject->error, $srcobject->errors, 'errors');
2183 $error++;
2184 }
2185 }
2186
2187 $object->update_price(1, 'auto', 0, $mysoc);
2188
2189 $object->line_order(true, 'DESC');
2190
2191 // Now we create same links to contact than the ones found on origin object
2192 /* Useless, already into the create
2193 if (getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN')) {
2194 $originforcontact = $object->origin;
2195 $originidforcontact = $object->origin_id;
2196 if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
2197 {
2198 $originforcontact=$srcobject->origin;
2199 $originidforcontact=$srcobject->origin_id;
2200 }
2201 $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
2202 $sqlcontact.= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'";
2203
2204 $resqlcontact = $db->query($sqlcontact);
2205 if ($resqlcontact)
2206 {
2207 while($objcontact = $db->fetch_object($resqlcontact))
2208 {
2209 //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
2210 $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
2211 }
2212 }
2213 else dol_print_error($resqlcontact);
2214 }*/
2215
2216 // Hooks
2217 $parameters = array('origin_type' => $object->origin_type, 'origin_id' => $object->origin_id, 'objFrom' => $srcobject);
2218 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
2219 // modified by hook
2220 if ($reshook < 0) {
2221 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2222 $error++;
2223 }
2224 } else {
2225 setEventMessages($object->error, $object->errors, 'errors');
2226 $error++;
2227 }
2228 } else { // If some invoice's lines coming from page
2229 $id = $object->create($user);
2230
2231 for ($i = 1; $i <= $NBLINES; $i++) {
2232 if (GETPOSTINT('idprod'.$i)) {
2233 $product = new Product($db);
2234 $product->fetch(GETPOSTINT('idprod'.$i));
2235 $startday = dol_mktime(12, 0, 0, GETPOSTINT('date_start'.$i.'month'), GETPOSTINT('date_start'.$i.'day'), GETPOSTINT('date_start'.$i.'year'));
2236 $endday = dol_mktime(12, 0, 0, GETPOSTINT('date_end'.$i.'month'), GETPOSTINT('date_end'.$i.'day'), GETPOSTINT('date_end'.$i.'year'));
2237 $result = $object->addline($product->description, $product->price, (float) price2num(GETPOST('qty'.$i), 'MS'), $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, GETPOSTINT('idprod'.$i), (float) price2num(GETPOST('remise_percent'.$i), '', 2), $startday, $endday, 0, 0, 0, $product->price_base_type, $product->price_ttc, $product->type, -1, 0, '', 0, 0, 0, 0, '', array(), 100, 0, $product->fk_unit, 0, '', 1);
2238 }
2239 }
2240
2241 $object->update_price(1, 'auto', 0, $mysoc);
2242 }
2243 }
2244 }
2245
2246 // Situation invoices
2247 if (GETPOST('type') == Facture::TYPE_SITUATION && GETPOSTINT('situations') > 0) {
2248 if (empty($dateinvoice)) {
2249 $error++;
2250 $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date"));
2251 setEventMessages($mesg, null, 'errors');
2252 } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
2253 $error++;
2254 setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
2255 $action = 'create';
2256 }
2257
2258 if (!(GETPOSTINT('situations') > 0)) {
2259 $error++;
2260 $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSituation"));
2261 setEventMessages($mesg, null, 'errors');
2262 $action = 'create';
2263 }
2264
2265 if (!$error) {
2266 $result = $object->fetch(GETPOSTINT('situations'));
2267 $object->fk_facture_source = GETPOSTINT('situations');
2269
2270 if (!empty($origin) && !empty($originid)) {
2271 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2272
2273 $object->origin = $origin; // deprecated
2274 $object->origin_type = $origin;
2275 $object->origin_id = $originid;
2276
2277 // retained warranty
2278 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
2279 $retained_warranty = GETPOSTINT('retained_warranty');
2280 if (price2num($retained_warranty) > 0) {
2281 $object->retained_warranty = (float) price2num($retained_warranty);
2282 }
2283
2284 if (GETPOSTINT('retained_warranty_fk_cond_reglement') > 0) {
2285 $object->retained_warranty_fk_cond_reglement = GETPOSTINT('retained_warranty_fk_cond_reglement');
2286 }
2287
2288 $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
2289 if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) {
2290 $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit);
2291 }
2292 $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
2293 }
2294
2295 foreach ($object->lines as $i => &$line) {
2296 $line->fk_prev_id = $line->id;
2297 $line->fetch_optionals();
2298 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
2299 $line->situation_percent = 0; // New situation percent must be 0 (No cumulative)
2300 } else {
2301 $line->situation_percent = $line->get_prev_progress($object->id); // get good progress including credit note
2302 }
2303
2304 // The $line->situation_percent has been modified, so we must recalculate all amounts
2305 $tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0, 'HT', 0, $line->product_type, $mysoc, array(), $line->situation_percent);
2306 $line->total_ht = (float) $tabprice[0];
2307 $line->total_tva = (float) $tabprice[1];
2308 $line->total_ttc = (float) $tabprice[2];
2309 $line->total_localtax1 = (float) $tabprice[9];
2310 $line->total_localtax2 = (float) $tabprice[10];
2311 $line->multicurrency_total_ht = (float) $tabprice[16];
2312 $line->multicurrency_total_tva = (float) $tabprice[17];
2313 $line->multicurrency_total_ttc = (float) $tabprice[18];
2314
2315 // If fk_remise_except defined we check if the reduction has already been applied
2316 if ($line->fk_remise_except) {
2317 $discount = new DiscountAbsolute($line->db);
2318 $result = $discount->fetch($line->fk_remise_except);
2319 if ($result > 0) {
2320 // Check if discount not already affected to another invoice
2321 if ($discount->fk_facture_line > 0) {
2322 $line->fk_remise_except = 0;
2323 }
2324 }
2325 }
2326 }
2327 }
2328
2329 $object->fetch_thirdparty();
2330 $object->date = $dateinvoice;
2331 $object->date_pointoftax = $date_pointoftax;
2332 $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
2333 $object->note = trim(GETPOST('note', 'restricthtml'));
2334 $object->note_private = trim(GETPOST('note', 'restricthtml'));
2335 $object->ref_client = GETPOST('ref_client', 'alpha');
2336 $object->ref_customer = GETPOST('ref_client', 'alpha');
2337 $object->model_pdf = GETPOST('model', 'alpha');
2338 $object->fk_project = GETPOSTINT('projectid');
2339 $object->cond_reglement_id = GETPOSTINT('cond_reglement_id');
2340 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
2341 $object->fk_account = GETPOSTINT('fk_account');
2342
2343
2344 // Special properties of replacement invoice
2345
2346 $object->situation_counter += 1;
2347
2348 // Set extrafields from the create form BEFORE createFromCurrent(), so they are already
2349 // present when create() inserts them and fires the BILL_CREATE trigger. This avoids firing
2350 // BILL_CREATE a second time just to expose the extrafields (#32217).
2351 $extrafields->fetch_name_optionals_label($object->table_element);
2352 $extrafields->setOptionalsFromPost(null, $object);
2353
2354 $id = $object->createFromCurrent($user);
2355 if ($id <= 0) {
2356 $mesg = $object->error;
2357 } else {
2358 $nextSituationInvoice = new Facture($db);
2359 $nextSituationInvoice->fetch($id);
2360
2361 // Hooks
2362 $parameters = array('origin_type' => $object->origin_type, 'origin_id' => $object->origin_id);
2363 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $nextSituationInvoice, $action); // Note that $action and $object may have been
2364 // modified by hook
2365 if ($reshook < 0) {
2366 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2367 $error++;
2368 }
2369 }
2370 }
2371 }
2372
2373 // End of object creation, we show it
2374 if ($id > 0 && !$error) {
2375 if (isModEnabled('category')) {
2376 $categories = GETPOST('categories', 'array');
2377 if (method_exists($object, 'setCategories')) {
2378 $object->setCategories($categories);
2379 }
2380 }
2381
2382 $db->commit();
2383
2384 // Define output language
2385 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE') && count($object->lines)) {
2386 $outputlangs = $langs;
2387 $newlang = '';
2388 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
2389 $newlang = GETPOST('lang_id', 'aZ09');
2390 }
2391 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2392 if (empty($object->thirdparty)) {
2393 $object->fetch_thirdparty();
2394 }
2395 $newlang = $object->thirdparty->default_lang;
2396 }
2397 if (!empty($newlang)) {
2398 $outputlangs = new Translate("", $conf);
2399 $outputlangs->setDefaultLang($newlang);
2400 $outputlangs->load('products');
2401 }
2402 $model = $object->model_pdf;
2403 $ret = $object->fetch($id); // Reload to get new records
2404
2405 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
2406 if ($result < 0) {
2407 setEventMessages($object->error, $object->errors, 'errors');
2408 }
2409 }
2410
2411 header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
2412 exit();
2413 } else {
2414 $db->rollback();
2415 $action = 'create';
2416 $_GET["origin"] = GETPOST("origin", 'alpha');
2417 $_GET["originid"] = GETPOSTINT("originid");
2418 setEventMessages($object->error, $object->errors, 'errors');
2419 }
2420 } elseif ($action == 'addline' && GETPOST('submitforalllines', 'aZ09') && (GETPOST('alldate_start', 'alpha') || GETPOST('alldate_end', 'alpha')) && $usercancreate) {
2421 // Define date start and date end for all line
2422 $alldate_start = dol_mktime(GETPOSTINT('alldate_starthour'), GETPOSTINT('alldate_startmin'), 0, GETPOSTINT('alldate_startmonth'), GETPOSTINT('alldate_startday'), GETPOSTINT('alldate_startyear'));
2423 $alldate_end = dol_mktime(GETPOSTINT('alldate_endhour'), GETPOSTINT('alldate_endmin'), 0, GETPOSTINT('alldate_endmonth'), GETPOSTINT('alldate_endday'), GETPOSTINT('alldate_endyear'));
2424 foreach ($object->lines as $line) {
2425 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
2426 continue;
2427 }
2428 if ($line->product_type == 1) { // only service line
2429 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $alldate_start, $alldate_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
2430 }
2431 }
2432 } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '' && $usercancreate) {
2433 // Define vat_rate
2434 $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
2435 $vat_rate = str_replace('*', '', $vat_rate);
2436 $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
2437 $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
2438 foreach ($object->lines as $line) {
2439 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
2440 continue;
2441 }
2442 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
2443 }
2444 } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('remiseforalllines', 'alpha') !== '' && $usercancreate) {
2445 // Define vat_rate
2446 $remise_percent = (GETPOST('remiseforalllines') ? GETPOST('remiseforalllines') : 0);
2447 $remise_percent = str_replace('*', '', $remise_percent);
2448 foreach ($object->lines as $line) {
2449 if ($line->special_code == SUBTOTALS_SPECIAL_CODE || !empty($line->fk_remise_except)) {
2450 continue;
2451 }
2452 $tvatx = $line->tva_tx;
2453 if (!empty($line->vat_src_code)) {
2454 $tvatx .= ' ('.$line->vat_src_code.')';
2455 }
2456 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, (float) $remise_percent, $line->date_start, $line->date_end, $tvatx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
2457 }
2458 } elseif ($action == 'confirm_addtitleline' && $usercancreate) {
2459 // Handling adding a new title line for subtotals module
2460
2461 $langs->load('subtotals');
2462
2463 $desc = GETPOST('subtotallinedesc', 'alphanohtml');
2464 $depth = GETPOSTINT('subtotallinelevel') ?? 1;
2465
2466 $subtotal_options = array();
2467
2468 foreach (Facture::$TITLE_OPTIONS as $option) {
2469 $value = GETPOST($option, 'alphanohtml');
2470 if ($value) {
2471 $subtotal_options[$option] = $value == 'on' ? 1 : $value;
2472 }
2473 }
2474
2475 // Insert line
2476 $result = $object->addSubtotalLine($langs, $desc, (int) $depth, $subtotal_options);
2477
2478 if ($result >= 0) {
2479 if ($result == 0) {
2480 setEventMessages($object->error, $object->errors, 'warnings');
2481 }
2482 $ret = $object->fetch($object->id); // Reload to get new records
2483 $object->fetch_thirdparty();
2484
2485 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
2486 // Define output language
2487 $outputlangs = $langs;
2488 $newlang = GETPOST('lang_id', 'alpha');
2489 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2490 $newlang = $object->thirdparty->default_lang;
2491 }
2492 if (!empty($newlang)) {
2493 $outputlangs = new Translate("", $conf);
2494 $outputlangs->setDefaultLang($newlang);
2495 }
2496
2497 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2498 }
2499 } else {
2500 setEventMessages($object->error, $object->errors, 'errors');
2501 }
2502 header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
2503 exit();
2504 } elseif ($action == 'confirm_addsubtotalline' && $usercancreate) {
2505 // Handling adding a new subtotal line for subtotals module
2506
2507 $langs->load('subtotals');
2508
2509 $choosen_line = GETPOST('subtotaltitleline', 'alphanohtml');
2510 foreach ($object->lines as $line) {
2511 if ($line->desc == $choosen_line && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
2512 $desc = $line->desc;
2513 $depth = -$line->qty;
2514 }
2515 }
2516
2517 $subtotal_options = array();
2518
2519 foreach (Facture::$SUBTOTAL_OPTIONS as $option) {
2520 $value = GETPOST($option, 'alphanohtml');
2521 if ($value) {
2522 $subtotal_options[$option] = $value == 'on' ? 1 : $value;
2523 }
2524 }
2525
2526 // Insert line
2527 if (isset($desc) && isset($depth)) {
2528 $result = $object->addSubtotalLine($langs, $desc, (int) $depth, $subtotal_options);
2529 } else {
2530 $result = -1;
2531 $object->errors[] = $langs->trans("CorrespondingTitleNotFound");
2532 }
2533
2534 if ($result >= 0) {
2535 $ret = $object->fetch($object->id); // Reload to get new records
2536 $object->fetch_thirdparty();
2537
2538 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
2539 // Define output language
2540 $outputlangs = $langs;
2541 $newlang = GETPOST('lang_id', 'alpha');
2542 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2543 $newlang = $object->thirdparty->default_lang;
2544 }
2545 if (!empty($newlang)) {
2546 $outputlangs = new Translate("", $conf);
2547 $outputlangs->setDefaultLang($newlang);
2548 }
2549
2550 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2551 }
2552 } else {
2553 setEventMessages($object->error, $object->errors, 'errors');
2554 }
2555 header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
2556 exit();
2557 } elseif ($action == 'addline' && GETPOST('updateallvatlinesblock', 'alpha') && GETPOST('vatforblocklines', 'alpha') !== '' && $usercancreate) {
2558 $tx_tva = GETPOST('vatforblocklines') ? GETPOST('vatforblocklines') : 0;
2559 $object->updateSubtotalLineBlockLines($langs, $object->getRangOfLine($lineid), 'tva', $tx_tva);
2560 } elseif ($action == 'addline' && GETPOST('updatealldiscountlinesblock', 'alpha') && GETPOST('discountforblocklines', 'alpha') !== '' && $usercancreate) {
2561 $discount = GETPOST('discountforblocklines') ? GETPOST('discountforblocklines') : 0;
2562 $object->updateSubtotalLineBlockLines($langs, $object->getRangOfLine($lineid), 'discount', $discount);
2563 } elseif ($action == 'addline' && !GETPOST('submitforalllines', 'alpha') && !GETPOST('submitforallmargins', 'alpha') && !GETPOST('submitforallmark', 'alpha') && $usercancreate) { // Add a new line
2564 $langs->load('errors');
2565 $error = 0;
2566
2567 // Set if we used free entry or predefined product
2568 $predef = '';
2569 $line_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
2570
2571 $price_ht = '';
2572 $price_ht_devise = '';
2573 $price_ttc = '';
2574 $price_ttc_devise = '';
2575
2576 $price_min = '';
2577 $price_min_ttc = '';
2578
2579 if (GETPOST('price_ht') !== '') {
2580 $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
2581 }
2582 if (GETPOST('multicurrency_price_ht') !== '') {
2583 $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
2584 }
2585 if (GETPOST('price_ttc') !== '') {
2586 $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
2587 }
2588 if (GETPOST('multicurrency_price_ttc') !== '') {
2589 $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
2590 }
2591
2592 $prod_entry_mode = GETPOST('prod_entry_mode', 'aZ09');
2593 if ($prod_entry_mode == 'free') {
2594 $idprod = 0;
2595 } else {
2596 $idprod = GETPOSTINT('idprod');
2597
2598 if (getDolGlobalString('MAIN_DISABLE_FREE_LINES') && $idprod <= 0) {
2599 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
2600 $error++;
2601 }
2602 }
2603
2604 $tva_tx = GETPOST('tva_tx', 'alpha');
2605
2606 $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS', 2);
2607 $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef, 'alpha'), '', 2) : 0);
2608 if (empty($remise_percent)) {
2609 $remise_percent = 0;
2610 }
2611
2612 // Extrafields
2613 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
2614 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
2615 // Unset extrafield
2616 if (is_array($extralabelsline)) {
2617 // Get extra fields
2618 foreach ($extralabelsline as $key => $value) {
2619 unset($_POST["options_".$key.$predef]);
2620 }
2621 }
2622
2623 if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
2624 setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
2625 $error++;
2626 }
2627 if (!$prod_entry_mode) {
2628 if (GETPOST('type') < 0 && !GETPOST('search_idprod')) {
2629 setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors');
2630 $error++;
2631 }
2632 }
2633 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
2634 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
2635 $error++;
2636 }
2637
2638 // Do not allow negative lines for free products (invite to enter a discount instead)
2639 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0)
2640 && (((float) $price_ht < 0 && !getDolGlobalString('FACTURE_ENABLE_NEGATIVE_LINES')) || $price_ht === '')
2641 && (((float) $price_ht_devise < 0 && !getDolGlobalString('FACTURE_ENABLE_NEGATIVE_LINES')) || $price_ht_devise === '')
2642 && ((float) $price_ttc < 0 && !getDolGlobalString('FACTURE_ENABLE_NEGATIVE_LINES') || $price_ttc === '')
2643 && ((float) $price_ttc_devise < 0 && !getDolGlobalString('FACTURE_ENABLE_NEGATIVE_LINES') || $price_ttc_devise === '')
2644 && $object->type != $object::TYPE_CREDIT_NOTE) { // Unit price can be 0 but not ''
2645 if (((float) $price_ht < 0 || (float) $price_ttc < 0) && !getDolGlobalString('FACTURE_ENABLE_NEGATIVE_LINES')) {
2646 $langs->load("errors");
2647 if ($object->type == $object::TYPE_DEPOSIT) {
2648 // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
2649 setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
2650 } else {
2651 setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
2652 }
2653 $error++;
2654 }
2655 }
2656 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not ''
2657 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors');
2658 $error++;
2659 }
2660
2661 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && empty($line_desc)) {
2662 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
2663 $error++;
2664 }
2665 if ($qty == '') {
2666 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
2667 $error++;
2668 }
2669 if ($qty < 0 && !getDolGlobalString('INVOICE_ENABLE_NEGATIVE_QTY')) {
2670 $langs->load("errors");
2671 setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
2672 $error++;
2673 }
2674
2675 if (!$error && isModEnabled('variants') && $prod_entry_mode != 'free') {
2676 if ($combinations = GETPOST('combinations', 'array:alphanohtml')) {
2677 //Check if there is a product with the given combination
2678 $prodcomb = new ProductCombination($db);
2679
2680 if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
2681 $idprod = $res->fk_product_child;
2682 } else {
2683 setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
2684 $error++;
2685 }
2686 }
2687 }
2688
2689 $price_base_type = null;
2690 if (!$error && (!empty($line_desc) || (!empty($idprod) && $idprod > 0))) {
2691 $ret = $object->fetch($id);
2692 if ($ret < 0) {
2693 dol_print_error($db, $object->error);
2694 exit();
2695 }
2696 $ret = $object->fetch_thirdparty();
2697
2698 // Clean parameters
2699 $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'));
2700 $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'));
2701 $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
2702 $tva_npr = "";
2703
2704 // Define special_code for special lines
2705 $special_code = 0;
2706 // if (!GETPOST(qty)) $special_code=3; // Options should not exists on invoices
2707
2708 // Replaces $pu with that of the product
2709 // Replaces $desc with that of the product
2710 // Replaces $base_price_type with that of the product
2711 // Replaces $fk_unit with that of the product
2712 if (!empty($idprod) && $idprod > 0) {
2713 $prod = new Product($db);
2714 $prod->fetch($idprod);
2715
2716 $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
2717
2718 // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
2719 $pqp = (GETPOSTINT('pbq') ? GETPOSTINT('pbq') : 0);
2720
2721 $datapriceofproduct = $prod->getSellPrice($mysoc, $object->thirdparty, $pqp);
2722
2723 $pu_ht = $datapriceofproduct['pu_ht'];
2724 $pu_ttc = $datapriceofproduct['pu_ttc'];
2725 $price_min = $datapriceofproduct['price_min'];
2726 $price_min_ttc = (isset($datapriceofproduct['price_min_ttc'])) ? $datapriceofproduct['price_min_ttc'] : null;
2727 $price_base_type = empty($datapriceofproduct['price_base_type']) ? 'HT' : $datapriceofproduct['price_base_type'];
2728
2729 //$tva_tx = $datapriceofproduct['tva_tx'];
2730 //$tva_npr = $datapriceofproduct['tva_npr'];
2731 $tmpvat = (float) price2num(preg_replace('/\s*\‍(.*\‍)/', '', $tva_tx));
2732 $tmpprodvat = price2num(preg_replace('/\s*\‍(.*\‍)/', '', (string) $prod->tva_tx));
2733
2734 // Set unit price to use
2735 // TODO We should not have this
2736 if (!empty($price_ht) || $price_ht === '0') {
2737 $pu_ht = price2num($price_ht, 'MU');
2738 $pu_ttc = price2num((float) $pu_ht * (1 + ($tmpvat / 100)), 'MU');
2739 } elseif (!empty($price_ht_devise) || $price_ht_devise === '0') {
2740 $pu_ht_devise = price2num($price_ht_devise, 'MU');
2741 $pu_ttc_devise = (float) price2num((float) $pu_ht_devise * (1 + ((float) $tmpvat / 100)), 'MU');
2742 $pu_ht = '';
2743 $pu_ttc = '';
2744 } elseif (!empty($price_ttc) || $price_ttc === '0') {
2745 $pu_ttc = price2num($price_ttc, 'MU');
2746 $pu_ht = price2num((float) $pu_ttc / (1 + ($tmpvat / 100)), 'MU');
2747 } elseif (!empty($price_ttc_devise) || (string) $price_ttc_devise === '0') {
2748 $pu_ttc_devise = (float) price2num($price_ttc_devise, 'MU');
2749 $pu_ht_devise = (float) price2num((float) $pu_ttc_devise / (1 + ((float) $tmpvat / 100)), 'MU');
2750 $pu_ht = '';
2751 $pu_ttc = '';
2752 } elseif ($tmpvat != $tmpprodvat) {
2753 // Is this still used ?
2754 if ($price_base_type != 'HT') {
2755 $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
2756 } else {
2757 $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
2758 }
2759 }
2760
2761 $outputlangs = $langs;
2762 $newlang = '';
2763 $desc = '';
2764
2765 // Define output language
2766 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
2767 if (/* empty($newlang) && */ GETPOST('lang_id', 'aZ09')) {
2768 $newlang = GETPOST('lang_id', 'aZ09');
2769 }
2770 if (empty($newlang)) {
2771 $newlang = $object->thirdparty->default_lang;
2772 }
2773 if (!empty($newlang)) {
2774 $outputlangs = new Translate("", $conf);
2775 $outputlangs->setDefaultLang($newlang);
2776 $outputlangs->load('products');
2777 }
2778
2779 $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
2780 } else {
2781 $desc = $prod->description;
2782 }
2783
2784 if (getDolGlobalInt('PRODUIT_AUTOFILL_DESC') == 0) {
2785 // 'DoNotAutofillButAutoConcat'
2786 $desc = dol_concatdesc($desc, $line_desc, false, getDolGlobalString('MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION') ? true : false);
2787 } else {
2788 //'AutoFillFormFieldBeforeSubmit' or 'DoNotUseDescriptionOfProdut' => User has already done the modification they want
2789 $desc = $line_desc;
2790 }
2791
2792 // Add custom code and origin country into description
2793 if (!getDolGlobalString('MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE') && (!empty($prod->customcode) || !empty($prod->country_code))) {
2794 $tmptxt = '(';
2795 // Define output language
2796 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
2797 if (!empty($prod->customcode)) {
2798 $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomsCode").': '.$prod->customcode;
2799 }
2800 if (!empty($prod->customcode) && !empty($prod->country_code)) {
2801 $tmptxt .= ' - ';
2802 }
2803 if (!empty($prod->country_code)) {
2804 $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, '', $db, $outputlangs, 0);
2805 }
2806 } else {
2807 if (!empty($prod->customcode)) {
2808 $tmptxt .= $langs->transnoentitiesnoconv("CustomsCode").': '.$prod->customcode;
2809 }
2810 if (!empty($prod->customcode) && !empty($prod->country_code)) {
2811 $tmptxt .= ' - ';
2812 }
2813 if (!empty($prod->country_code)) {
2814 $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, '', $db, $langs, 0);
2815 }
2816 }
2817 $tmptxt .= ')';
2818 $desc = dol_concatdesc($desc, $tmptxt);
2819 }
2820
2821 $type = $prod->type;
2822 $fk_unit = $prod->fk_unit;
2823 } else {
2824 if (!empty($price_ht)) {
2825 $pu_ht = price2num($price_ht, 'MU');
2826 } else {
2827 $pu_ht = '';
2828 }
2829 if (!empty($price_ttc)) {
2830 $pu_ttc = price2num($price_ttc, 'MU');
2831 } else {
2832 $pu_ttc = '';
2833 }
2834 $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
2835 $tva_tx = str_replace('*', '', $tva_tx);
2836 if (empty($tva_tx)) {
2837 $tva_npr = 0;
2838 }
2839 $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
2840 $desc = $line_desc;
2841 $type = GETPOST('type');
2842 $fk_unit = GETPOST('units', 'alpha');
2843
2844 if ($pu_ttc && !$pu_ht) {
2845 $price_base_type = 'TTC';
2846 }
2847 }
2848
2849 // Define info_bits
2850 $info_bits = 0;
2851 if ($tva_npr) {
2852 $info_bits |= 0x01;
2853 }
2854
2855 // Local Taxes
2856 $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
2857 $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
2858
2859 $pu_ht_devise = price2num($price_ht_devise, '', 2);
2860 $pu_ttc_devise = price2num($price_ttc_devise, '', 2);
2861
2862 // Prepare a price equivalent for minimum price check
2863 $pu_equivalent = $pu_ht;
2864 $pu_equivalent_ttc = $pu_ttc;
2865
2866 $currency_tx = $object->multicurrency_tx;
2867
2868 // Check if we have a foreign currency
2869 // If so, we update the pu_equiv as the equivalent price in base currency
2870 if ($pu_ht == '' && $pu_ht_devise != '' && $currency_tx != '' && !empty((float) $currency_tx)) {
2871 $pu_equivalent = (float) $pu_ht_devise / (float) $currency_tx;
2872 }
2873 if ($pu_ttc == '' && $pu_ttc_devise != '' && $currency_tx != '' && !empty((float) $currency_tx)) {
2874 $pu_equivalent_ttc = (float) $pu_ttc_devise / (float) $currency_tx;
2875 }
2876
2877 // TODO $pu_equivalent or $pu_equivalent_ttc must be calculated from the one not null taking into account all taxes
2878 /*
2879 if ($pu_equivalent) {
2880 $tmp = calcul_price_total(1, $pu_equivalent, 0, $tva_tx, -1, -1, 0, 'HT', $info_bits, $type);
2881 $pu_equivalent_ttc = ...
2882 } else {
2883 $tmp = calcul_price_total(1, $pu_equivalent_ttc, 0, $tva_tx, -1, -1, 0, 'TTC', $info_bits, $type);
2884 $pu_equivalent_ht = ...
2885 }
2886 */
2887
2888 // Margin
2889 $fournprice = (int) (GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : ''); // This can be id of supplier price, or 'pmpprice' or 'costprice', or 'inputprice', we force to keep ID only
2890 $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we must keep this value
2891
2892
2893 $price2num_pu_ht = price2num($pu_ht);
2894 $price2num_remise_percent = price2num($remise_percent);
2895 $price2num_price_min = price2num($price_min);
2896 $price2num_price_min_ttc = price2num($price_min_ttc);
2897 if (empty($price2num_pu_ht)) {
2898 $price2num_pu_ht = 0;
2899 }
2900 if (empty($price2num_remise_percent)) {
2901 $price2num_remise_percent = 0;
2902 }
2903 if (empty($price2num_price_min)) {
2904 $price2num_price_min = 0;
2905 }
2906 if (empty($price2num_price_min_ttc)) {
2907 $price2num_price_min_ttc = 0;
2908 }
2909
2910 // Check price is not lower than minimum (check is done only for standard or replacement invoices)
2911 if ($usermustrespectpricemin && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)) {
2912 if ($pu_equivalent && $price_min && (((float) price2num($pu_equivalent) * (1 - $remise_percent / 100)) < (float) price2num($price_min)) && $price_base_type == 'HT') {
2913 $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2914 setEventMessages($mesg, null, 'errors');
2915 $error++;
2916 } elseif ($pu_equivalent_ttc && $price_min_ttc && (((float) price2num($pu_equivalent_ttc) * (1 - $remise_percent / 100)) < (float) price2num($price_min_ttc)) && $price_base_type == 'TTC') {
2917 $mesg = $langs->trans("CantBeLessThanMinPriceInclTax", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2918 setEventMessages($mesg, null, 'errors');
2919 $error++;
2920 }
2921 }
2922
2923 if (!$error) {
2924 /* Disable strange code that use $lines[$i] that is not defined
2925 '@phan-var-force CommonObjectLine[] $lines';
2926 // Add batchinfo if the detail_batch array is defined
2927 if (isModEnabled('productbatch') && !empty($lines[$i]->detail_batch) && is_array($lines[$i]->detail_batch) && getDolGlobalString('INVOICE_INCUDE_DETAILS_OF_LOTS_SERIALS')) {
2928 $langs->load('productbatch');
2929 foreach ($lines[$i]->detail_batch as $batchline) {
2930 $desc .= ' '.$langs->trans('Batch').' '.$batchline->batch.' '.$langs->trans('printQty', $batchline->qty).' ';
2931 }
2932 }
2933 */
2934
2935 // Insert line
2936 $situation_percent = (GETPOSTISSET('progress') ? GETPOSTINT('progress') : 100);
2937
2938 $result = $object->addline($desc, $pu_ht, (float) $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $date_start, $date_end, 0, $info_bits, 0, $price_base_type, $pu_ttc, $type, min($rank, count($object->lines) + 1), $special_code, '', 0, GETPOSTINT('fk_parent_line'), (int) $fournprice, $buyingprice, $label, $array_options, $situation_percent, 0, $fk_unit, (float) $pu_ht_devise);
2939
2940 if ($result > 0) {
2941 $ret = $object->fetch($id); // Reload to get new records
2942 $object->fetch_thirdparty();
2943 // Define output language and generate document
2944 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
2945 $outputlangs = $langs;
2946 $newlang = '';
2947 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
2948 $newlang = GETPOST('lang_id', 'aZ09');
2949 }
2950 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2951 $newlang = $object->thirdparty->default_lang;
2952 }
2953 if (!empty($newlang)) {
2954 $outputlangs = new Translate("", $conf);
2955 $outputlangs->setDefaultLang($newlang);
2956 $outputlangs->load('products');
2957 }
2958 $model = $object->model_pdf;
2959 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
2960 if ($result < 0) {
2961 setEventMessages($object->error, $object->errors, 'errors');
2962 }
2963 }
2964
2965 unset($_POST['prod_entry_mode']);
2966 unset($_POST['qty']);
2967 unset($_POST['type']);
2968 unset($_POST['remise_percent']);
2969 unset($_POST['price_ht']);
2970 unset($_POST['multicurrency_price_ht']);
2971 unset($_POST['price_ttc']);
2972 unset($_POST['tva_tx']);
2973 unset($_POST['product_ref']);
2974 unset($_POST['product_label']);
2975 unset($_POST['product_desc']);
2976 unset($_POST['fournprice']);
2977 unset($_POST['buying_price']);
2978 unset($_POST['np_marginRate']);
2979 unset($_POST['np_markRate']);
2980 unset($_POST['dp_desc']);
2981 unset($_POST['idprod']);
2982 unset($_POST['units']);
2983 unset($_POST['date_starthour']);
2984 unset($_POST['date_startmin']);
2985 unset($_POST['date_startsec']);
2986 unset($_POST['date_startday']);
2987 unset($_POST['date_startmonth']);
2988 unset($_POST['date_startyear']);
2989 unset($_POST['date_endhour']);
2990 unset($_POST['date_endmin']);
2991 unset($_POST['date_endsec']);
2992 unset($_POST['date_endday']);
2993 unset($_POST['date_endmonth']);
2994 unset($_POST['date_endyear']);
2995 unset($_POST['situations']);
2996 unset($_POST['progress']);
2997 } else {
2998 setEventMessages($object->error, $object->errors, 'errors');
2999 }
3000
3001 $action = '';
3002 }
3003 }
3004 } elseif ($action == 'addline' && $usercancreate && (
3005 (GETPOST('submitforallmargins', 'alpha') && GETPOST('marginforalllines', 'alpha') !== '') ||
3006 (GETPOST('submitforallmark', 'alpha') && GETPOST('markforalllines', 'alpha') !== '')
3007 )) {
3008 $outlangs = $langs;
3009 $margin_rate = GETPOSTISSET('marginforalllines') ? GETPOST('marginforalllines', 'int') : '';
3010 $mark_rate = GETPOSTISSET('markforalllines') ? GETPOST('markforalllines', 'int') : '';
3011 foreach ($object->lines as &$line) {
3012 if ($line->subprice > 0) {
3013 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
3014 continue;
3015 }
3016 $subprice_multicurrency = $line->subprice;
3017 if (is_numeric($margin_rate) && $margin_rate > 0) {
3018 $line->subprice = (float) price2num((float) $line->pa_ht * (1 + (float) $margin_rate / 100), 'MU');
3019 } elseif (is_numeric($mark_rate) && $mark_rate > 0) {
3020 $line->subprice = (float) ($line->pa_ht / (1 - ((float) $mark_rate / 100)));
3021 } else {
3022 $line->subprice = (float) $line->pa_ht;
3023 }
3024
3025 if ($line->fk_product > 0) {
3026 $prod = new Product($db);
3027 $res = $prod->fetch($line->fk_product);
3028 if ($res > 0) {
3029 if ($prod->price_min > $line->subprice) {
3030 $price_subprice = price($line->subprice, 0, $outlangs, 1, -1, -1, 'auto');
3031 $price_price_min = price($prod->price_min, 0, $outlangs, 1, -1, -1, 'auto');
3032 setEventMessages($prod->ref . ' - ' . $prod->label . ' (' . $price_subprice . ' < ' . $price_price_min . ' ' . strtolower($langs->trans("MinPrice")) . ')' . "\n", null, 'warnings');
3033 } else {
3034 setEventMessages($prod->error, $prod->errors, 'errors');
3035 }
3036 } else {
3037 setEventMessages($prod->error, $prod->errors, 'errors');
3038 }
3039 }
3040 // Manage $line->subprice and $line->multicurrency_subprice
3041 $multicurrency_subprice = (float) $line->subprice * $line->multicurrency_subprice / $subprice_multicurrency;
3042 // Update DB
3043 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->product_ref, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $multicurrency_subprice);
3044 // Update $object with new margin info
3045 if ($result > 0) {
3046 if (is_numeric($margin_rate) && empty($mark_rate)) {
3047 $line->marge_tx = $margin_rate;
3048 } elseif (is_numeric($mark_rate) && empty($margin_rate)) {
3049 $line->marque_tx = $mark_rate;
3050 }
3051 $line->total_ht = $line->qty * (float) $line->subprice;
3052 $line->total_tva = $line->tva_tx * $line->qty * (float) $line->subprice;
3053 $line->total_ttc = (1 + $line->tva_tx) * $line->qty * (float) $line->subprice;
3054 // Manage $line->subprice and $line->multicurrency_subprice
3055 $line->multicurrency_total_ht = $line->qty * (float) $subprice_multicurrency * $line->multicurrency_subprice / $line->subprice;
3056 $line->multicurrency_total_tva = $line->tva_tx * $line->qty * (float) $subprice_multicurrency * $line->multicurrency_subprice / $line->subprice;
3057 $line->multicurrency_total_ttc = (1 + $line->tva_tx) * $line->qty * (float) $subprice_multicurrency * $line->multicurrency_subprice / $line->subprice;
3058 // Used previous $line->subprice and $line->multicurrency_subprice above, now they can be set to their new values
3059 $line->multicurrency_subprice = $multicurrency_subprice;
3060 } else {
3061 setEventMessages($object->error, $object->errors, 'errors');
3062 }
3063 }
3064 }
3065 } elseif ($action == 'updatetitleline' && GETPOSTISSET("save") && $usercancreate && !GETPOST('cancel', 'alpha')) {
3066 // Handling updating a title line for subtotals module
3067
3068 $langs->load('subtotals');
3069
3070 $desc = GETPOST('line_desc', 'alphanohtml') ?? $langs->trans("Title");
3071 $depth = GETPOSTINT('line_depth') ?? 1;
3072
3073 $subtotal_options = array();
3074
3075 foreach (Facture::$TITLE_OPTIONS as $option) {
3076 $value = GETPOST($option, 'alphanohtml');
3077 if ($value) {
3078 $subtotal_options[$option] = $value == 'on' ? 1 : $value;
3079 }
3080 }
3081
3082 // Update line
3083 $result = $object->updateSubtotalLine($langs, GETPOSTINT('lineid'), $desc, $depth, $subtotal_options);
3084
3085 if ($result >= 0) {
3086 if ($result == 0) {
3087 setEventMessages($object->error, $object->errors, 'warnings');
3088 }
3089 $ret = $object->fetch($object->id); // Reload to get new records
3090 $object->fetch_thirdparty();
3091
3092 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
3093 // Define output language
3094 $outputlangs = $langs;
3095 $newlang = GETPOST('lang_id', 'alpha');
3096 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
3097 $newlang = $object->thirdparty->default_lang;
3098 }
3099 if (!empty($newlang)) {
3100 $outputlangs = new Translate("", $conf);
3101 $outputlangs->setDefaultLang($newlang);
3102 }
3103
3104 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
3105 }
3106 } else {
3107 setEventMessages($object->error, $object->errors, 'errors');
3108 }
3109 } elseif ($action == 'updatesubtotalline' && GETPOSTISSET("save") && $usercancreate && !GETPOST('cancel', 'alpha')) {
3110 // Handling updating a subtotal line for subtotals module
3111
3112 $langs->load('subtotals');
3113
3114 $desc = GETPOST('line_desc', 'alphanohtml');
3115 $depth = GETPOSTINT('line_depth');
3116
3117 $subtotal_options = array();
3118
3119 foreach (Facture::$SUBTOTAL_OPTIONS as $option) {
3120 $value = GETPOST($option, 'alphanohtml');
3121 if ($value) {
3122 $subtotal_options[$option] = $value == 'on' ? 1 : $value;
3123 }
3124 }
3125
3126 // Update line
3127 $result = $object->updateSubtotalLine($langs, GETPOSTINT('lineid'), $desc, $depth, $subtotal_options);
3128
3129 if ($result > 0) {
3130 $ret = $object->fetch($object->id); // Reload to get new records
3131 $object->fetch_thirdparty();
3132
3133 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
3134 // Define output language
3135 $outputlangs = $langs;
3136 $newlang = GETPOST('lang_id', 'alpha');
3137 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
3138 $newlang = $object->thirdparty->default_lang;
3139 }
3140 if (!empty($newlang)) {
3141 $outputlangs = new Translate("", $conf);
3142 $outputlangs->setDefaultLang($newlang);
3143 }
3144
3145 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
3146 }
3147 } else {
3148 setEventMessages($object->error, $object->errors, 'errors');
3149 }
3150 } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) {
3151 if (!$object->fetch($id) > 0) {
3153 }
3154 $object->fetch_thirdparty();
3155
3156 // Clean parameters
3157 $date_start = '';
3158 $date_end = '';
3159 $date_start = dol_mktime(GETPOSTINT('date_starthour'), GETPOSTINT('date_startmin'), GETPOSTINT('date_startsec'), GETPOSTINT('date_startmonth'), GETPOSTINT('date_startday'), GETPOSTINT('date_startyear'));
3160 $date_end = dol_mktime(GETPOSTINT('date_endhour'), GETPOSTINT('date_endmin'), GETPOSTINT('date_endsec'), GETPOSTINT('date_endmonth'), GETPOSTINT('date_endday'), GETPOSTINT('date_endyear'));
3161 $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml'));
3162 $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
3163
3164 $pu_ht = price2num(GETPOST('price_ht'), '', 2);
3165 $pu_ttc = price2num(GETPOST('price_ttc'), '', 2);
3166
3167 $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
3168 $pu_ttc_devise = price2num(GETPOST('multicurrency_subprice_ttc'), '', 2);
3169
3170 $qty = price2num(GETPOST('qty', 'alpha'), 'MS');
3171
3172 // Define info_bits
3173 $info_bits = 0;
3174 if (preg_match('/\*/', $vat_rate)) {
3175 $info_bits |= 0x01;
3176 }
3177
3178 // Define vat_rate
3179 $vat_rate = str_replace('*', '', $vat_rate);
3180 $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
3181 $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
3182
3183 // Add buying price
3184 $fournprice = (int) (GETPOST('fournprice') ? GETPOST('fournprice') : ''); // This can be id of supplier price, or 'pmpprice' or 'costprice', or 'inputprice', we force to keep ID only
3185 $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we must keep this value
3186
3187 // Prepare a price equivalent for minimum price check
3188 $pu_equivalent = $pu_ht;
3189 $pu_equivalent_ttc = $pu_ttc;
3190
3191 $currency_tx = $object->multicurrency_tx;
3192
3193 // Check if we have a foreign currency
3194 // If so, we update the pu_equiv as the equivalent price in base currency
3195 if ($pu_ht == '' && $pu_ht_devise != '' && $currency_tx != '' && !empty((float) $currency_tx)) {
3196 $pu_equivalent = (float) $pu_ht_devise / (float) $currency_tx;
3197 }
3198 if ($pu_ttc == '' && $pu_ttc_devise != '' && $currency_tx != '' && !empty((float) $currency_tx)) {
3199 $pu_equivalent_ttc = (float) $pu_ttc_devise / (float) $currency_tx;
3200 }
3201
3202 // TODO $pu_equivalent or $pu_equivalent_ttc must be calculated from the one not null taking into account all taxes
3203 /*
3204 if ($pu_equivalent) {
3205 $tmp = calcul_price_total(1, $pu_equivalent, 0, $vat_rate, -1, -1, 0, 'HT', $info_bits, $type);
3206 $pu_equivalent_ttc = ...
3207 } else {
3208 $tmp = calcul_price_total(1, $pu_equivalent_ttc, 0, $vat_rate, -1, -1, 0, 'TTC', $info_bits, $type);
3209 $pu_equivalent_ht = ...
3210 }
3211 */
3212
3213 // Extrafields
3214 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
3215 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
3216 // Unset extrafield
3217 if (is_array($extralabelsline)) {
3218 // Get extra fields
3219 foreach ($extralabelsline as $key => $value) {
3220 unset($_POST["options_".$key]);
3221 }
3222 }
3223
3224 // Define special_code for special lines
3225 $special_code = GETPOSTINT('special_code');
3226 if ($special_code == 3) {
3227 $special_code = 0; // Options should not exists on invoices
3228 }
3229
3230 $line = new FactureLigne($db);
3231 $line->fetch(GETPOSTINT('lineid'));
3232 $percent = $line->get_prev_progress($object->id);
3233 $progress = price2num(GETPOST('progress', 'alpha'));
3234
3235 if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref > 0) {
3236 // in case of situation credit note
3237 if ($progress >= 0) {
3238 $mesg = $langs->trans("CantBeNullOrPositive");
3239 setEventMessages($mesg, null, 'warnings');
3240 $error++;
3241 $result = -1;
3242 } elseif ($progress < $line->situation_percent) { // TODO : use a modified $line->get_prev_progress($object->id) result
3243 $mesg = $langs->trans("CantBeLessThanMinPercent");
3244 setEventMessages($mesg, null, 'warnings');
3245 $error++;
3246 $result = -1;
3247 } elseif ($progress < $percent) {
3248 $mesg = '<div class="warning">'.$langs->trans("CantBeLessThanMinPercent").'</div>';
3249 setEventMessages($mesg, null, 'warnings');
3250 $error++;
3251 $result = -1;
3252 }
3253 }
3254
3255 $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
3256 if (empty($remise_percent)) {
3257 $remise_percent = 0;
3258 }
3259
3260 $price_base_type = 'HT';
3261 $pu = $pu_ht;
3262 if (empty($pu) && !empty($pu_ttc)) {
3263 $pu = $pu_ttc;
3264 $price_base_type = 'TTC';
3265 }
3266
3267 // Check minimum price
3268 $productid = GETPOSTINT('productid');
3269 if (!empty($productid)) {
3270 $product = new Product($db);
3271 $product->fetch($productid);
3272
3273 $type = $product->type;
3274
3275 $price_min = $product->price_min;
3276 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && !empty($object->thirdparty->price_level)) {
3277 $price_min = $product->multiprices_min[$object->thirdparty->price_level];
3278 }
3279 $price_min_ttc = $product->price_min_ttc;
3280 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && !empty($object->thirdparty->price_level)) {
3281 $price_min_ttc = $product->multiprices_min_ttc[$object->thirdparty->price_level];
3282 }
3283
3284 $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
3285
3286 // Check price is not lower than minimum (check is done only for standard or replacement invoices)
3287 if ($usermustrespectpricemin && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)) {
3288 if ($pu_equivalent && $price_min && (((float) price2num($pu_equivalent) * (1 - (float) $remise_percent / 100)) < (float) price2num($price_min)) && $price_base_type == 'HT') {
3289 $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
3290 setEventMessages($mesg, null, 'errors');
3291 $error++;
3292 $action = 'editline';
3293 } elseif ($pu_equivalent_ttc && $price_min_ttc && (((float) price2num($pu_equivalent_ttc) * (1 - (float) $remise_percent / 100)) < (float) price2num($price_min_ttc)) && $price_base_type == 'TTC') {
3294 $mesg = $langs->trans("CantBeLessThanMinPriceInclTax", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
3295 setEventMessages($mesg, null, 'errors');
3296 $error++;
3297 $action = 'editline';
3298 }
3299 }
3300 } else {
3301 $type = GETPOST('type');
3302 $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
3303
3304 // Check parameters
3305 if (GETPOST('type') < 0) {
3306 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
3307 $error++;
3308 }
3309 }
3310 if ($qty < 0 && !getDolGlobalString('INVOICE_ENABLE_NEGATIVE_QTY')) {
3311 $langs->load("errors");
3312 setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
3313 $error++;
3314 }
3315 if (empty($productid) && (($pu_ht < 0 && !getDolGlobalString('FACTURE_ENABLE_NEGATIVE_LINES')) || $pu_ht == '') && (($pu_ht_devise < 0 && !getDolGlobalString('FACTURE_ENABLE_NEGATIVE_LINES')) || $pu_ht_devise == '') && $pu_ttc === '' && $pu_ttc_devise === '' && $object->type != Facture::TYPE_CREDIT_NOTE) { // Unit price can be 0 but not ''
3316 if (($pu_ht < 0 || $pu_ttc < 0) && !getDolGlobalString('FACTURE_ENABLE_NEGATIVE_LINES')) {
3317 $langs->load("errors");
3318 if ($object->type == $object::TYPE_DEPOSIT) {
3319 // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
3320 setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
3321 } else {
3322 setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
3323 }
3324 $error++;
3325 } else {
3326 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
3327 $error++;
3328 }
3329 }
3330
3331 // Invoice situation
3332 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
3333 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3334 $fullprogress = (float) price2num(GETPOST('progress', 'alpha'), 2);
3335
3336 if ($fullprogress < $previousprogress) {
3337 $error++;
3338 setEventMessages($langs->trans('CantBeLessThanMinPercent'), null, 'errors');
3339 }
3340
3341 // Max 100%
3342 if ($fullprogress > 100) {
3343 $fullprogress = 100;
3344 }
3345 $addprogress = $fullprogress - $previousprogress;
3346 } else {
3347 $addprogress = price2num(GETPOST('progress', 'alpha'));
3348 }
3349
3350 // Update line
3351 if (!$error) {
3352 if (empty($usercancreatemargin)) {
3353 foreach ($object->lines as &$line) {
3354 if ($line->id == GETPOSTINT('lineid')) {
3355 $fournprice = $line->fk_fournprice;
3356 $buyingprice = $line->pa_ht;
3357 break;
3358 }
3359 }
3360 }
3361
3362 $result = $object->updateline(
3363 GETPOSTINT('lineid'),
3364 $description,
3365 (float) $pu,
3366 (float) $qty,
3367 (float) $remise_percent,
3369 $date_end,
3370 $vat_rate,
3371 $localtax1_rate,
3372 $localtax2_rate,
3373 $price_base_type,
3374 $info_bits,
3375 $type,
3376 GETPOSTINT('fk_parent_line'),
3377 0,
3378 (int) $fournprice,
3379 $buyingprice,
3380 $label,
3381 $special_code,
3382 $array_options,
3383 $addprogress,
3384 GETPOSTINT('units'),
3385 (float) $pu_ht_devise
3386 );
3387
3388 if ($result >= 0) {
3389 $ret = $object->fetch($id); // Reload to get new records
3390 $object->fetch_thirdparty();
3391 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
3392 // Define output language
3393 $outputlangs = $langs;
3394 $newlang = '';
3395 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
3396 $newlang = GETPOST('lang_id', 'aZ09');
3397 }
3398 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
3399 $newlang = $object->thirdparty->default_lang;
3400 }
3401 if (!empty($newlang)) {
3402 $outputlangs = new Translate("", $conf);
3403 $outputlangs->setDefaultLang($newlang);
3404 $outputlangs->load('products');
3405 }
3406 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
3407 }
3408
3409 unset($_POST['qty']);
3410 unset($_POST['type']);
3411 unset($_POST['productid']);
3412 unset($_POST['remise_percent']);
3413 unset($_POST['price_ht']);
3414 unset($_POST['multicurrency_price_ht']);
3415 unset($_POST['price_ttc']);
3416 unset($_POST['tva_tx']);
3417 unset($_POST['product_ref']);
3418 unset($_POST['product_label']);
3419 unset($_POST['product_desc']);
3420 unset($_POST['fournprice']);
3421 unset($_POST['buying_price']);
3422 unset($_POST['np_marginRate']);
3423 unset($_POST['np_markRate']);
3424 unset($_POST['dp_desc']);
3425 unset($_POST['idprod']);
3426 unset($_POST['units']);
3427 unset($_POST['date_starthour']);
3428 unset($_POST['date_startmin']);
3429 unset($_POST['date_startsec']);
3430 unset($_POST['date_startday']);
3431 unset($_POST['date_startmonth']);
3432 unset($_POST['date_startyear']);
3433 unset($_POST['date_endhour']);
3434 unset($_POST['date_endmin']);
3435 unset($_POST['date_endsec']);
3436 unset($_POST['date_endday']);
3437 unset($_POST['date_endmonth']);
3438 unset($_POST['date_endyear']);
3439 unset($_POST['situations']);
3440 unset($_POST['progress']);
3441 } else {
3442 setEventMessages($object->error, $object->errors, 'errors');
3443 }
3444 }
3445 } elseif ($action == 'updatealllines' && $usercancreate && GETPOSTISSET('all_percent')) { // Update all lines of situation invoice
3446 if (!$object->fetch($id) > 0) {
3448 }
3449 if (GETPOST('all_progress') != "") {
3450 $all_progress = GETPOSTFLOAT('all_progress');
3451 if ($all_progress > 100) {
3452 $all_progress = 100;
3453 }
3454
3455 foreach ($object->lines as $line) {
3456 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
3457 $percent = $line->getAllPrevProgress($object->id);
3458 } else {
3459 $percent = $line->get_prev_progress($object->id);
3460 }
3461 if ($object->type != $object::TYPE_CREDIT_NOTE && (float) $all_progress < (float) $percent) {
3462 $mesg = $langs->trans("Line").' '.$line->rang.' : '.$langs->trans("CantBeLessThanMinPercent");
3463 setEventMessages($mesg, null, 'warnings');
3464 $result = -1;
3465 } elseif ($object->type == $object::TYPE_CREDIT_NOTE && (float) $all_progress > (float) $percent) {
3466 $mesg = $langs->trans("Line").' '.$line->rang.' : '.$langs->trans("CantBeMoreThanMinPercent");
3467 setEventMessages($mesg, null, 'warnings');
3468 $result = -1;
3469 } else {
3470 $object->update_percent($line, $all_progress, false);
3471 }
3472 }
3473 $object->update_price(1);
3474 }
3475 } elseif ($action == 'updateline' && $usercancreate && !$cancel) {
3476 header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); // To show again edited page
3477 exit();
3478 } elseif ($action == 'confirm_situationout' && $confirm == 'yes' && $usercancreate) {
3479 // Outing situation invoice from cycle
3480 $object->fetch($id, '', '', 0, true);
3481
3482 if (in_array($object->status, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
3483 && $object->isSituationInvoice()
3484 && $usercancreate
3485 && !$objectidnext
3486 && $object->is_last_in_cycle()
3487 && $usercanunvalidate
3488 ) {
3489 $outingError = 0;
3490 $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle
3491 if ($newCycle > 1) {
3492 // Search credit notes
3493 $lastCycle = $object->situation_cycle_ref;
3494 $lastSituationCounter = $object->situation_counter;
3495 $linkedCreditNotesList = array();
3496
3497 if (count($object->tab_next_situation_invoice) > 0) {
3498 foreach ($object->tab_next_situation_invoice as $next_invoice) {
3499 if ($next_invoice->type == Facture::TYPE_CREDIT_NOTE
3500 && $next_invoice->situation_counter == $object->situation_counter
3501 && $next_invoice->fk_facture_source == $object->id
3502 ) {
3503 $linkedCreditNotesList[] = $next_invoice->id;
3504 }
3505 }
3506 }
3507
3508 $object->situation_cycle_ref = $newCycle;
3509 $object->situation_counter = 1;
3510 $object->situation_final = 0;
3511 if ($object->update($user) > 0) {
3512 $errors = 0;
3513 if (count($linkedCreditNotesList) > 0) {
3514 // now, credit note must follow
3515 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3516 $sql .= ' SET situation_cycle_ref = '.((int) $newCycle);
3517 $sql .= ' , situation_final=0';
3518 $sql .= ' , situation_counter='.((int) $object->situation_counter);
3519 $sql .= ' WHERE rowid IN ('.$db->sanitize(implode(',', $linkedCreditNotesList)).')';
3520
3521 $resql = $db->query($sql);
3522 if (!$resql) {
3523 $errors++;
3524 }
3525
3526 // Change each progression percent on each lines
3527 foreach ($object->lines as $line) {
3528 // no processing for special product
3529 if ($line->product_type == 9) {
3530 continue;
3531 }
3532
3533
3534 if (!empty($object->tab_previous_situation_invoice)) {
3535 // search the last invoice in cycle
3536 $lineIndex = count($object->tab_previous_situation_invoice) - 1;
3537 $searchPreviousInvoice = true;
3538 while ($searchPreviousInvoice) {
3539 if ($object->tab_previous_situation_invoice[$lineIndex]->isSituationInvoice() || $lineIndex < 1) {
3540 $searchPreviousInvoice = false; // find, exit;
3541 break;
3542 } else {
3543 $lineIndex--; // go to previous invoice in cycle
3544 }
3545 }
3546
3547
3548 $maxPrevSituationPercent = 0;
3549 foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
3550 if ($prevLine->id == $line->fk_prev_id) {
3551 $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
3552 }
3553 }
3554
3555
3556 $line->situation_percent -= $maxPrevSituationPercent;
3557
3558 if ($line->update() < 0) {
3559 $errors++;
3560 }
3561 }
3562 }
3563 }
3564
3565 if (!$errors) {
3566 setEventMessages($langs->trans('Updated'), null, 'mesgs');
3567 header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
3568 } else {
3569 setEventMessages($langs->trans('ErrorOutingSituationInvoiceCreditNote'), array(), 'errors');
3570 }
3571 } else {
3572 setEventMessages($langs->trans('ErrorOutingSituationInvoiceOnUpdate'), array(), 'errors');
3573 }
3574 } else {
3575 setEventMessages($langs->trans('ErrorFindNextSituationInvoice'), array(), 'errors');
3576 }
3577 }
3578 } elseif ($action == 'import_lines_from_object' && $usercancreate && $object->status == Facture::STATUS_DRAFT
3580 // add lines from objectlinked
3581 $fromElement = GETPOST('fromelement');
3582 $fromElementid = GETPOSTINT('fromelementid');
3583 $importLines = GETPOST('line_checkbox');
3584
3585 if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) {
3586 $lineClassName = '';
3587 $lineParentField = '';
3588 if ($fromElement == 'commande') {
3589 dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php');
3590 $lineClassName = 'OrderLine';
3591 $lineParentField = 'fk_commande';
3592 } elseif ($fromElement == 'propal') {
3593 dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php');
3594 $lineClassName = 'PropaleLigne';
3595 $lineParentField = 'fk_propal';
3596 }
3597 $nextRang = count($object->lines) + 1;
3598 $importCount = 0;
3599 $error = 0;
3600 // Check user can read the source object (permission, thirdparty and entity)
3601 $fromElementAllowed = ($lineParentField && $fromElementid > 0 && restrictedArea($user, $fromElement, $fromElementid, '', '', 'fk_soc', 'rowid', 0, 1));
3602 foreach ($importLines as $lineId) {
3603 if ($lineClassName === '') {
3604 // No class
3605 if ($error === 0) {
3606 // Log only once
3607 dol_syslog('compta/facture/card - No lineClassName - skip import', LOG_ERR);
3608 }
3609 // Ensure we report that all line failed (see error message below)
3610 $error++;
3611 break;
3612 }
3613
3614 $lineId = intval($lineId);
3615 $originLine = new $lineClassName($db);
3616 if ($fromElementAllowed && $originLine->fetch($lineId) > 0 && $originLine->$lineParentField == $fromElementid) {
3617 $originLine->fetch_optionals();
3618 $desc = $originLine->desc;
3619 $pu_ht = $originLine->subprice;
3620 $qty = $originLine->qty;
3621 $txtva = $originLine->tva_tx;
3622 $txlocaltax1 = $originLine->localtax1_tx;
3623 $txlocaltax2 = $originLine->localtax2_tx;
3624 $fk_product = $originLine->fk_product;
3625 $remise_percent = $originLine->remise_percent;
3626 $date_start = $originLine->date_start;
3627 $date_end = $originLine->date_end;
3628 $fk_code_ventilation = 0;
3629 $info_bits = $originLine->info_bits;
3630 $fk_remise_except = $originLine->fk_remise_except;
3631 $price_base_type = 'HT';
3632 $pu_ttc = 0;
3633 $type = $originLine->product_type;
3634 $rang = $nextRang++;
3635 $special_code = $originLine->special_code;
3636 $origin = $originLine->element;
3637 $origin_id = $originLine->id;
3638 $fk_parent_line = 0;
3639 $fk_fournprice = $originLine->fk_fournprice;
3640 $pa_ht = $originLine->pa_ht;
3641 $label = $originLine->label;
3642 $array_options = $originLine->array_options;
3643 if ($object->isSituationInvoice()) {
3644 $situation_percent = 0;
3645 } else {
3646 $situation_percent = 100;
3647 }
3648 $fk_prev_id = 0;
3649 $fk_unit = $originLine->fk_unit;
3650 $pu_ht_devise = $originLine->multicurrency_subprice;
3651
3652 $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $fk_code_ventilation, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $type, $rang, $special_code, $origin, $origin_id, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $situation_percent, $fk_prev_id, $fk_unit, $pu_ht_devise);
3653
3654 if ($res > 0) {
3655 $importCount++;
3656 } else {
3657 $error++;
3658 }
3659 } else {
3660 $error++;
3661 }
3662 }
3663
3664 if ($error) {
3665 setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors');
3666 }
3667 }
3668 }
3669
3670
3671 // Actions when printing a doc from card
3672 include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
3673
3674 // Actions to send emails
3675 if (empty($id)) {
3676 $id = $facid;
3677 }
3678 if (!empty($object->id) && $action == 'send') { // Test on permission not required
3679 // load totalpaid, totaldeposits, totalcreditnotes that can be used in email templates
3680 $object->getSommePaiement(-1);
3681 $object->getSumCreditNotesUsed(-1);
3682 $object->getSumDepositsUsed(-1);
3683 }
3684 $triggersendname = 'BILL_SENTBYMAIL';
3685 $paramname = 'id';
3686 $autocopy = 'MAIN_MAIL_AUTOCOPY_INVOICE_TO';
3687 $trackid = 'inv'.$object->id;
3688 include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
3689
3690 // Actions to build doc
3691 $upload_dir = $conf->invoice->multidir_output[!empty($object->entity) ? $object->entity : $conf->entity];
3692 $permissiontoadd = $usercancreate;
3693 include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
3694
3695
3696 if ($action == 'update_extras' && $permissiontoeditextra) {
3697 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
3698
3699 $attribute_name = GETPOST('attribute', 'aZ09');
3700
3701 // Fill array 'array_options' with data from add form
3702 $ret = $extrafields->setOptionalsFromPost(null, $object, $attribute_name);
3703 if ($ret < 0) {
3704 $error++;
3705 }
3706
3707 if (!$error) {
3708 // Actions on extra fields
3709 $result = $object->updateExtraField($attribute_name, 'BILL_MODIFY');
3710 if ($result < 0) {
3711 setEventMessages($object->error, $object->errors, 'errors');
3712 $error++;
3713 }
3714 }
3715
3716 if ($error) {
3717 $action = 'edit_extras';
3718 }
3719 }
3720
3721 if (getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB')) {
3722 if ($action == 'addcontact' && $usercancreate) {
3723 $result = $object->fetch($id);
3724
3725 if ($result > 0 && $id > 0) {
3726 $contactid = (GETPOST('userid') ? GETPOSTINT('userid') : GETPOSTINT('contactid'));
3727 $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
3728 $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
3729 }
3730
3731 if ($result >= 0) {
3732 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
3733 exit();
3734 } else {
3735 if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
3736 $langs->load("errors");
3737 setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
3738 } else {
3739 setEventMessages($object->error, $object->errors, 'errors');
3740 }
3741 }
3742 } elseif ($action == 'swapstatut' && $usercancreate) {
3743 // toggle the status of a contact
3744 if ($object->fetch($id)) {
3745 $result = $object->swapContactStatus(GETPOSTINT('ligne'));
3746 } else {
3748 }
3749 } elseif ($action == 'deletecontact' && $usercancreate) {
3750 // Delete a contact
3751 $object->fetch($id);
3752 $result = $object->delete_contact($lineid);
3753
3754 if ($result >= 0) {
3755 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
3756 exit();
3757 } else {
3759 }
3760 }
3761
3762 if ($error) {
3763 $action = 'edit_extras';
3764 }
3765 }
3766}
3767
3768
3769/*
3770 * View
3771 */
3772
3773$form = new Form($db);
3774$formother = new FormOther($db);
3775$formfile = new FormFile($db);
3776$formmargin = new FormMargin($db);
3777$soc = new Societe($db);
3778$paymentstatic = new Paiement($db);
3779$bankaccountstatic = new Account($db);
3780$formproject = null;
3781if (isModEnabled('project')) {
3782 $formproject = new FormProjets($db);
3783}
3784
3785$now = dol_now();
3786
3787$title = $object->ref." - ".$langs->trans('Card');
3788if ($action == 'create') {
3789 $title = $langs->trans("NewBill");
3790}
3791$help_url = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
3792
3793llxHeader('', $title, $help_url);
3794
3795// Mode creation
3796
3797if ($action == 'create') {
3798 $facturestatic = new Facture($db);
3799 $extrafields->fetch_name_optionals_label($facturestatic->table_element);
3800
3801 print load_fiche_titre($langs->trans('NewBill'), '', 'bill');
3802
3803 if ($socid > 0) {
3804 $res = $soc->fetch($socid);
3805 }
3806
3807 $currency_code = $conf->currency;
3808
3809 $cond_reglement_id = GETPOSTINT('cond_reglement_id');
3810 $mode_reglement_id = GETPOSTINT('mode_reglement_id');
3811 $fk_account = GETPOSTINT('fk_account');
3812
3813 $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
3814 if (empty($dateinvoice)) {
3815 $dateinvoice = (getDolGlobalString('MAIN_DO_NOT_AUTOFILL_DATE_INVOICE') ? -1 : ''); // By default '' so we will autofill date. -1 means keep empty.
3816 }
3817
3818 // Load objectsrc
3819 $objectsrc = null;
3820 if (!empty($origin) && !empty($originid)) {
3821 // Parse element/subelement (ex: project_task)
3822 $element = $subelement = $origin;
3823 $regs = array();
3824 if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
3825 $element = $regs[1];
3826 $subelement = $regs[2];
3827 }
3828
3829 $date_pointoftax = dol_mktime(0, 0, 0, GETPOSTINT('date_pointoftaxmonth'), GETPOSTINT('date_pointoftaxday'), GETPOSTINT('date_pointoftaxyear'), 'tzserver');
3830
3831 if ($element == 'project') {
3832 $projectid = $originid;
3833
3834 if (empty($cond_reglement_id)) {
3835 $cond_reglement_id = $soc->cond_reglement_id;
3836 }
3837 if (empty($mode_reglement_id)) {
3838 $mode_reglement_id = $soc->mode_reglement_id;
3839 }
3840 if (empty($fk_account)) {
3841 $fk_account = $soc->fk_account;
3842 }
3843 } else {
3844 // For compatibility
3845 if ($element == 'order' || $element == 'commande') {
3846 $element = $subelement = 'commande';
3847 }
3848 if ($element == 'propal') {
3849 $element = 'comm/propal';
3850 $subelement = 'propal';
3851 }
3852 if ($element == 'contract') {
3853 $element = $subelement = 'contrat';
3854 }
3855 if ($element == 'shipping') {
3856 $element = $subelement = 'expedition';
3857 }
3858
3859 dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
3860
3861 $classname = ucfirst($subelement);
3862 $objectsrc = new $classname($db);
3863 '@phan-var-force Commande|Propal|Contrat|Expedition|Facture $objectsrc';
3865 $objectsrc->fetch($originid);
3866 if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
3867 $objectsrc->fetch_lines();
3868 }
3869 $objectsrc->fetch_thirdparty();
3870
3871 $projectid = (!empty($projectid) ? $projectid : $objectsrc->fk_project);
3872
3873 // Propagate ref customer of src object to the invoice ?
3874 if (getDolGlobalString("INVOICE_DO_NOT_PROPAGATE_REF_CUSTOMER_OF_SRC_TO_INVOICE")) {
3875 $ref_client = "";
3876 } else {
3877 $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : ''));
3878 }
3879
3880 // Only if socid not filled else it's already done above
3881 if (empty($socid)) {
3882 $soc = $objectsrc->thirdparty;
3883 }
3884
3885 if ($element == 'expedition') {
3886 $elem = $subelem = $objectsrc->origin_type;
3887 $expeoriginid = $objectsrc->origin_id;
3888 dol_include_once('/'.$elem.'/class/'.$subelem.'.class.php');
3889 $classname = ucfirst($subelem);
3890
3891 $expesrc = new $classname($db);
3892 '@phan-var-force Expedition $expesrc';
3894 dol_syslog("Is type Facture|Commande or Expedition: $element...expesrc($classname)=".get_class($expesrc));
3895 $expesrc->fetch($expeoriginid);
3896
3897 $cond_reglement_id = (!empty($expesrc->cond_reglement_id) ? $expesrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 1));
3898 $mode_reglement_id = (!empty($expesrc->mode_reglement_id) ? $expesrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
3899 $fk_account = (!empty($expesrc->fk_account) ? $expesrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
3900
3901 if (isModEnabled('multicurrency')) {
3902 $currency_code = (!empty($expesrc->multicurrency_code) ? $expesrc->multicurrency_code : (!empty($soc->multicurrency_code) ? $soc->multicurrency_code : $objectsrc->multicurrency_code));
3903 $currency_tx = (!empty($expesrc->multicurrency_tx) ? $expesrc->multicurrency_tx : (!empty($soc->multicurrency_tx) ? $soc->multicurrency_tx : $objectsrc->multicurrency_tx));
3904 }
3905
3906 // replicate input reason
3907 $inputReasonId = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0));
3908
3909 //Replicate extrafields
3910 $expesrc->fetch_optionals();
3911 $object->array_options = $expesrc->array_options;
3912 } else {
3913 $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : (!empty($cond_reglement_id) ? $cond_reglement_id : 0)));
3914 $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : (!empty($mode_reglement_id) ? $mode_reglement_id : 0)));
3915 $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : (!empty($fk_account) ? $fk_account : 0)));
3916
3917 if (isModEnabled('multicurrency')) {
3918 if (!empty($objectsrc->multicurrency_code)) {
3919 $currency_code = $objectsrc->multicurrency_code;
3920 }
3921 if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($objectsrc->multicurrency_tx)) {
3922 $currency_tx = $objectsrc->multicurrency_tx;
3923 }
3924 }
3925
3926 // replicate input reason
3927 $inputReasonId = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0));
3928
3929 // Replicate extrafields
3930 $objectsrc->fetch_optionals();
3931 $object->array_options = $objectsrc->array_options;
3932 }
3933 }
3934 } else {
3935 $cond_reglement_id = empty($soc->cond_reglement_id) ? $cond_reglement_id : $soc->cond_reglement_id;
3936 $mode_reglement_id = empty($soc->mode_reglement_id) ? $mode_reglement_id : $soc->mode_reglement_id;
3937 $fk_account = empty($soc->fk_account) ? $fk_account : $soc->fk_account;
3938 $inputReasonId = empty($soc->demand_reason_id) ? $inputReasonId : $soc->demand_reason_id;
3939
3940 if (isModEnabled('multicurrency') && !empty($soc->multicurrency_code)) {
3941 $currency_code = $soc->multicurrency_code;
3942 }
3943 }
3944
3945 // If form was posted (but error returned), we must reuse the value posted in priority (standard Dolibarr behaviour)
3946 if (!GETPOST('changecompany')) {
3947 if (GETPOSTISSET('cond_reglement_id')) {
3948 $cond_reglement_id = GETPOSTINT('cond_reglement_id');
3949 }
3950 if (GETPOSTISSET('mode_reglement_id')) {
3951 $mode_reglement_id = GETPOSTINT('mode_reglement_id');
3952 }
3953 if (GETPOSTISSET('cond_reglement_id')) {
3954 $fk_account = GETPOSTINT('fk_account');
3955 }
3956 }
3957
3958 // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value
3959 if (empty($cond_reglement_id)) {
3960 $cond_reglement_id = GETPOSTINT("cond_reglement_id");
3961 }
3962
3963 // when payment mode is empty (means not override by payment mode form a other object, like third-party), try to use default value
3964 if (empty($mode_reglement_id)) {
3965 $mode_reglement_id = GETPOSTINT("mode_reglement_id");
3966 }
3967
3968 // when bank account is empty (means not override by payment mode form a other object, like third-party), try to use default value
3969 // if ($socid > 0 && $fk_account) { // A company has already been set and it has a default fk_account
3970 // $fk_account = GETPOSTISSET('fk_account') ? GETPOST("fk_account", 'int') : $fk_account; // The GETPOST is used only if form was posted to avoid to take default value, because in such case, the default must be the one of the company
3971 // } else { // No company forced
3972 // $fk_account = GETPOST("fk_account", 'int');
3973 // }
3974
3975 if (!empty($soc->id)) {
3976 $absolute_discount = $soc->getAvailableDiscounts();
3977 }
3978 $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && getDolGlobalString('FACTURE_REUSE_NOTES_ON_CREATE_FROM')) ? $objectsrc->note_public : null));
3979 $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && getDolGlobalString('FACTURE_REUSE_NOTES_ON_CREATE_FROM')) ? $objectsrc->note_private : null));
3980
3981 if (!empty($conf->use_javascript_ajax)) {
3982 require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
3983 print ajax_combobox('fac_replacement');
3984 print ajax_combobox('fac_avoir');
3985 print ajax_combobox('situations');
3986 }
3987
3988 if ($origin == 'contrat') {
3989 $langs->load("admin");
3990 $text = $langs->trans("ToCreateARecurringInvoice");
3991 $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates"));
3992 if (!getDolGlobalString('INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE')) {
3993 $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name'));
3994 }
3995 print info_admin($text, 0, 0, 'info', '').'<br>';
3996 }
3997
3998 print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="POST" id="formtocreate" name="formtocreate">';
3999 print '<input type="hidden" name="token" value="'.newToken().'">';
4000 print '<input type="hidden" name="action" id="formtocreateaction" value="add">';
4001 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
4002 if ($soc->id > 0) {
4003 print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
4004 }
4005 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
4006 print '<input name="ref" type="hidden" value="provisoire">';
4007 print '<input name="ref_client" type="hidden" value="'.$ref_client.'">';
4008 print '<input name="force_cond_reglement_id" type="hidden" value="0">';
4009 print '<input name="force_mode_reglement_id" type="hidden" value="0">';
4010 print '<input name="force_fk_account" type="hidden" value="0">';
4011 print '<input type="hidden" name="origin" value="'.$origin.'">';
4012 print '<input type="hidden" name="originid" value="'.$originid.'">';
4013 print '<input type="hidden" name="originentity" value="'.GETPOSTINT('originentity').'">';
4014 if (!empty($currency_tx)) {
4015 print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
4016 }
4017
4018 print dol_get_fiche_head();
4019
4020 // Call Hook tabContentCreateInvoice
4021 $parameters = array();
4022 // Note that $action and $object may be modified by hook
4023 $reshook = $hookmanager->executeHooks('tabContentCreateInvoice', $parameters, $object, $action);
4024 if (empty($reshook)) {
4025 print '<table class="border centpercent">';
4026
4027 $exampletemplateinvoice = new FactureRec($db);
4028 $invoice_predefined = new FactureRec($db);
4029 if (empty($origin) && empty($originid) && GETPOSTINT('fac_rec') > 0) {
4030 $invoice_predefined->fetch(GETPOSTINT('fac_rec'));
4031 }
4032
4033 // Ref
4034 /*
4035 print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans('Ref').'</td>';
4036 print '<td colspan="2">';
4037 print $langs->trans("Draft");
4038 print '</td>';
4039 print '</tr>'."\n";
4040 */
4041
4042 // Thirdparty
4043 if ($soc->id > 0 && (!GETPOSTINT('fac_rec') || !empty($invoice_predefined->frequency))) {
4044 // If thirdparty known and not a predefined invoiced without a recurring rule
4045 print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans('Customer').'</td>';
4046 print '<td colspan="2">';
4047 print $soc->getNomUrl(1, 'customer');
4048 print '<input type="hidden" name="socid" value="'.$soc->id.'">';
4049 // Outstanding Bill
4050 $arrayoutstandingbills = $soc->getOutstandingBills();
4051 $outstandingBills = $arrayoutstandingbills['opened'];
4052 print ' - <span class="opacitymedium valignmiddle">'.$langs->trans('CurrentOutstandingBill').':</span> ';
4053 print '<span class="amount valignmiddle">'.price($outstandingBills, 0, $langs, 0, 0, -1, $conf->currency).'</span>';
4054 if ($soc->outstanding_limit != '') {
4055 if ($outstandingBills > $soc->outstanding_limit) {
4056 print img_warning($langs->trans("OutstandingBillReached"));
4057 }
4058 print ' / '.price($soc->outstanding_limit, 0, $langs, 0, 0, -1, $conf->currency);
4059 }
4060 print '</td>';
4061 print '</tr>'."\n";
4062 } else {
4063 print '<tr><td class="fieldrequired">'.$langs->trans('Customer').'</td>';
4064 print '<td colspan="2">';
4065 $filter = '((s.client:IN:1,2,3) AND (s.status:=:1))';
4066 print img_picto('', 'company', 'class="pictofixedwidth"').$form->select_company($soc->id, 'socid', $filter, 'SelectThirdParty', 1, 0, array(), 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
4067 // Option to reload page to retrieve customer information.
4068 if (!getDolGlobalString('RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED')) {
4069 print '<script>
4070 $(document).ready(function() {
4071 $("#socid").change(function() {
4072 /*
4073 console.log("Submit page");
4074 $(\'input[name="action"]\').val(\'create\');
4075 $(\'input[name="force_cond_reglement_id"]\').val(\'1\');
4076 $(\'input[name="force_mode_reglement_id"]\').val(\'1\');
4077 $(\'input[name="force_fk_account"]\').val(\'1\');
4078 $("#formtocreate").submit(); */
4079
4080 // For company change, we must submit page with action=create instead of action=add
4081 console.log("We have changed the company - Resubmit page");
4082 jQuery("input[name=changecompany]").val("1");
4083 jQuery("#formtocreateaction").val("create");
4084 jQuery("#formtocreate").submit();
4085 });
4086 });
4087 </script>';
4088 }
4089 if (!GETPOSTINT('fac_rec')) {
4090 print ' <a class="valignmiddle" href="'.DOL_URL_ROOT.'/societe/card.php?action=create&customer=3&fournisseur=0&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
4091 }
4092 print '</td>';
4093 print '</tr>'."\n";
4094 }
4095
4096 // Overwrite some values if creation of invoice is from a predefined invoice
4097 if (empty($origin) && empty($originid) && GETPOSTINT('fac_rec') > 0) {
4098 //$invoice_predefined->fetch(GETPOSTINT('fac_rec'));
4099 foreach ($invoice_predefined->array_options as $key => $option) {
4100 if (!isset($object->array_options[$key])) {
4101 $object->array_options[$key] = $invoice_predefined->array_options[$key];
4102 }
4103 }
4104
4105 $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
4106 if (empty($projectid)) {
4107 $projectid = $invoice_predefined->fk_project;
4108 }
4109 $cond_reglement_id = $invoice_predefined->cond_reglement_id;
4110 $mode_reglement_id = $invoice_predefined->mode_reglement_id;
4111 $fk_account = $invoice_predefined->fk_account;
4112 $note_public = $invoice_predefined->note_public;
4113 $note_private = $invoice_predefined->note_private;
4114
4115 if (!empty($invoice_predefined->multicurrency_code)) {
4116 $currency_code = $invoice_predefined->multicurrency_code;
4117 }
4118 if (!empty($invoice_predefined->multicurrency_tx)) {
4119 $currency_tx = $invoice_predefined->multicurrency_tx;
4120 }
4121
4122 $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc';
4123 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as r';
4124 $sql .= ' WHERE r.fk_soc = '.((int) $invoice_predefined->socid);
4125
4126 $resql = $db->query($sql);
4127 if ($resql) {
4128 $num = $db->num_rows($resql);
4129 $i = 0;
4130
4131 if ($num > 0) {
4132 print '<tr><td>'.$langs->trans('CreateFromRepeatableInvoice').'</td><td>';
4133 //print '<input type="hidden" name="fac_rec" id="fac_rec" value="'.GETPOST('fac_rec', 'int').'">';
4134 print '<select class="flat" id="fac_rec" name="fac_rec">'; // We may want to change the template to use
4135 print '<option value="0" selected></option>';
4136 while ($i < $num) {
4137 $objp = $db->fetch_object($resql);
4138 print '<option value="'.$objp->rowid.'"';
4139 if (GETPOSTINT('fac_rec') == $objp->rowid) {
4140 print ' selected';
4141 $exampletemplateinvoice->fetch(GETPOSTINT('fac_rec'));
4142 }
4143 print '>'.$objp->title.' ('.price($objp->total_ttc).' '.$langs->trans("TTC").')</option>';
4144 $i++;
4145 }
4146 print '</select>';
4147
4148 print ajax_combobox("fac_rec");
4149
4150 // Option to reload page to retrieve customer information. Note, this clear other input
4151 if (!getDolGlobalString('RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED')) {
4152 print '<script type="text/javascript">
4153 $(document).ready(function() {
4154 $("#fac_rec").change(function() {
4155 console.log("We have changed the template invoice - Reload page");
4156 var fac_rec = $(this).val();
4157 var socid = $(\'#socid\').val();
4158 // For template invoice change, we must reuse data of template, not input already done, so we call a GET with action=create, not a POST submit.
4159 window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
4160 });
4161 });
4162 </script>';
4163 }
4164 print '</td></tr>';
4165 }
4166 $db->free($resql);
4167 } else {
4169 }
4170 }
4171
4172 print '<tr><td class="tdtop fieldrequired titlefieldcreate">'.$langs->trans('Type').'</td><td colspan="2">';
4173 print '<div class="listofinvoicetypetable">'."\n";
4174
4175 // Standard invoice
4176 print '<div class="listofinvoicetype"><div class="">';
4177 $tmp = '<input type="radio" id="radio_standard" name="type" value="0"'.(GETPOSTINT('type') ? '' : ' checked').'> ';
4178 $tmp .= '<label for="radio_standard" >'.$langs->trans("InvoiceStandardAsk");
4179 $tmp .= ' <span class="opacitymedium">'.$langs->trans("InvoiceStandardAsk2").'</span>';
4180 $tmp .= '</label>';
4181 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
4182 $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceStandardDesc").'<br><br>'.$langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', 'nowraponall', 0, 3, 'standardonsmartphone');
4183 print $desc;
4184 if ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid))) {
4185 /*print '<td class="nowrap" style="padding-left: 5px">';
4186 $arraylist = array(
4187 //'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
4188 //'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
4189 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
4190 );
4191 print $form->selectarray('typestandard', $arraylist, GETPOST('typestandard', 'aZ09'), 0, 0, 0, '', 1);
4192 print '</td>';*/
4193 if (!getDolGlobalInt('INVOICE_DEPOSIT_INVOICE_ONLY_SAME_LINES')) {
4194 print '<span class="opacitymedium marginleftonly">' . $langs->trans('PercentOfOriginalObject') . '</span>:<input class="right" placeholder="100%" type="text" id="valuestandardinvoice" name="valuestandardinvoice" size="3" value="' . (GETPOSTISSET('valuestandardinvoice') ? GETPOST('valuestandardinvoice', 'alpha') : '100%') . '"/>';
4195 }
4196 }
4197 print '</div></div>'."\n";
4198
4199 if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid)))) {
4200 // Deposit - Down payment
4201 if (!getDolGlobalString('INVOICE_DISABLE_DEPOSIT')) {
4202 print '<div class="listofinvoicetype"><div class="">';
4203 $tmp = '<input type="radio" id="radio_deposit" name="type" value="3"'.(GETPOSTINT('type') == 3 ? ' checked' : '').'> ';
4204 print '<script type="text/javascript">
4205 jQuery(document).ready(function() {
4206 jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
4207 jQuery("#radio_standard").prop("checked", true);
4208 });
4209 jQuery("#typedeposit, #valuedeposit").click(function() {
4210 jQuery("#radio_deposit").prop("checked", true);
4211 });
4212 jQuery("#typedeposit").change(function() {
4213 console.log("We change type of down payment: "+jQuery("#typedeposit").val());
4214
4215 if (jQuery("#typedeposit").val() == "amount") {
4216 jQuery("#valuedeposit").attr("placeholder", "'.$langs->getCurrencySymbol($conf->currency).'");
4217 jQuery("#valuedeposit").val("");
4218 } else {
4219 jQuery("#valuedeposit").attr("placeholder", "50%");
4220 jQuery("#valuedeposit").val("");
4221 }
4222
4223 jQuery("#radio_deposit").prop("checked", true);
4224 setRadioForTypeOfInvoice();
4225 });
4226 jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_creditnote, #radio_template").change(function() {
4227 setRadioForTypeOfInvoice();
4228 });
4229
4230 function setRadioForTypeOfInvoice() {
4231 console.log("Change radio for type of invoice");
4232 if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
4233 jQuery("#checkforselects").prop("disabled", true);
4234 jQuery("#checkforselects").prop("checked", false);
4235 jQuery(".checkforselect").prop("disabled", true);
4236 jQuery(".checkforselect").prop("checked", false);
4237 } else {
4238 jQuery("#checkforselects").prop("disabled", false);
4239 jQuery("#checkforselects").prop("checked", true);
4240 jQuery(".checkforselect").prop("disabled", false);
4241 jQuery(".checkforselect").prop("checked", true);
4242 }
4243 }
4244 });
4245 </script>';
4246
4247 $tmp = $tmp.'<label for="radio_deposit">'.$langs->trans("InvoiceDeposit").'</label>';
4248 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
4249 $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3, 'depositonsmartphone');
4250 print $desc;
4251 if (($origin == 'propal') || ($origin == 'commande')) {
4252 if (!getDolGlobalInt('INVOICE_DEPOSIT_INVOICE_ONLY_SAME_LINES')) {
4253 $arraylist = array(
4254 'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
4255 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
4256 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
4257 );
4258 } else {
4259 $arraylist = array(
4260 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
4261 );
4262 }
4263
4264 $typedeposit = GETPOST('typedeposit', 'aZ09');
4265 $valuedeposit = GETPOSTFLOAT('valuedeposit');
4266 if (empty($typedeposit) && !empty($objectsrc->deposit_percent)) {
4267 $origin_payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $objectsrc->cond_reglement_id);
4268 if (!empty($origin_payment_conditions_deposit_percent)) {
4269 $typedeposit = 'variable';
4270 }
4271 }
4272 if (empty($valuedeposit) && $typedeposit == 'variable' && !empty($objectsrc->deposit_percent)) {
4273 $valuedeposit = $objectsrc->deposit_percent;
4274 }
4275 print '<span class="marginleftonly">'.$form->selectarray('typedeposit', $arraylist, $typedeposit, 0, 0, 0, '', 1).'</span>';
4276 //print '<span class="opacitymedium paddingleft">'.$langs->trans("AmountOrPercent").'</span>';
4277 print '<input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="'.($valuedeposit ? $valuedeposit : '').'"'.($valuedeposit ? '' : 'placeholder="'.$langs->getCurrencySymbol($conf->currency).'"').'>';
4278 }
4279
4280 print '</div></div>'."\n";
4281 }
4282 }
4283
4284 if ($socid > 0) {
4285 if (getDolGlobalString('INVOICE_USE_SITUATION')) {
4286 // First situation invoice
4287 print '<div class="listofinvoicetype"><div class="">';
4288 $tmp = '<input id="radio_situation" type="radio" name="type" value="5"'.(GETPOST('type') == 5 ? ' checked' : '').'> ';
4289 $tmp = $tmp.'<label for="radio_situation" >'.$langs->trans("InvoiceFirstSituationAsk").'</label>';
4290 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
4291 $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3, 'firstsituationonsmartphone');
4292 print $desc;
4293
4294 // Next situation invoice
4295 $opt = $form->selectSituationInvoices((string) GETPOSTINT('originid'), $socid);
4296
4297 //print ' &nbsp; ';
4298 print '</div></div><div class="listofinvoicetype"><div>';
4299
4300 $tmp = '<input id="radio_situation_bis" type="radio" name="type" value="5"'.(GETPOST('type') == 5 && GETPOSTINT('originid') ? ' checked' : '');
4301 if ($opt == ('<option value="0" selected>'.$langs->trans('NoSituations').'</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
4302 $tmp .= ' disabled';
4303 }
4304 $tmp .= '> ';
4305 $text = $tmp.'<label for="radio_situation_bis">'.$langs->trans("InvoiceSituationAsk").'</label> ';
4306
4307 $text .= '<select class="flat minwidth125" id="situations" name="situations"';
4308 if ($opt == ('<option value="0" selected>'.$langs->trans('NoSituations').'</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
4309 $text .= ' disabled';
4310 }
4311 $text .= '>';
4312 $text .= $opt;
4313 $text .= '</select>';
4314 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceSituationDesc"), 1, 'help', '', 0, 3);
4315 print $desc;
4316 print '</div></div>'."\n";
4317 }
4318
4319 // Replacement
4320 if (!getDolGlobalString('INVOICE_DISABLE_REPLACEMENT')) {
4321 // Type de facture
4322 $facids = $facturestatic->list_replacable_invoices($soc->id);
4323 if ($facids < 0) {
4324 dol_print_error($db, $facturestatic->error, $facturestatic->errors);
4325 exit();
4326 }
4327 $options = "";
4328 if (is_array($facids)) {
4329 foreach ($facids as $facparam) {
4330 $options .= '<option value="'.$facparam ['id'].'"';
4331 if ($facparam['id'] == GETPOSTINT('fac_replacement')) {
4332 $options .= ' selected';
4333 }
4334 $options .= '>'.$facparam['ref'];
4335 $options .= ' ('.$facturestatic->LibStatut($facparam['paid'], $facparam['status'], 0, $facparam['alreadypaid']).')';
4336 $options .= '</option>';
4337 }
4338 }
4339
4340 print '<!-- replacement line -->';
4341 print '<div class="listofinvoicetype"><div class="">';
4342 $tmp = '<input type="radio" name="type" id="radio_replacement" value="1"'.(GETPOST('type') == 1 ? ' checked' : '');
4343 if (!$options || $invoice_predefined->id > 0) {
4344 $tmp .= ' disabled';
4345 }
4346 $tmp .= '> ';
4347 print '<script type="text/javascript">
4348 jQuery(document).ready(function() {
4349 jQuery("#fac_replacement").change(function() {
4350 console.log("We change fac_replacement");
4351 jQuery("#radio_replacement").prop("checked", true);
4352 });
4353 });
4354 </script>';
4355 $text = $tmp.'<label for="radio_replacement">'.$langs->trans("InvoiceReplacementAsk").'</label>';
4356 $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
4357 if (!$options || $invoice_predefined->id > 0) {
4358 $text .= ' disabled';
4359 }
4360 $text .= '>';
4361 if ($options) {
4362 $text .= '<option value="-1">&nbsp;</option>';
4363 $text .= $options;
4364 } else {
4365 $text .= '<option value="-1">'.$langs->trans("NoReplacableInvoice").'</option>';
4366 }
4367 $text .= '</select>';
4368 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
4369 print $desc;
4370 print '</div></div>'."\n";
4371 }
4372 } else {
4373 if (getDolGlobalString('INVOICE_USE_SITUATION')) {
4374 print '<div class="listofinvoicetype"><div class="">';
4375 $tmp = '<input type="radio" name="type" id="radio_situation" value="0" disabled> ';
4376 $text = $tmp.'<label class="opacitymedium">'.$langs->trans("InvoiceSituationAsk").'</label> ';
4377 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceFirstSituationDesc").'<br><br>'.$langs->trans("YouMustCreateInvoiceFromThird"), 1, 'help', 'nowraponall', 0, 3, 'firstsituationonsmartphone');
4378 print $desc;
4379 print '</div></div>'."\n";
4380 }
4381
4382 print '<div class="listofinvoicetype"><div class="">';
4383 $tmp = '<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
4384 $text = $tmp.'<label for="radio_replacement" class="opacitymedium">'.$langs->trans("InvoiceReplacement").'</label> ';
4385 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc").'<br><br>'.$langs->trans("YouMustCreateInvoiceFromThird"), 1, 'help', 'nowraponall', 0, 3, 'replacementonsmartphone');
4386 print $desc;
4387 print '</div></div>'."\n";
4388 }
4389
4390 if (empty($origin)) {
4391 if ($socid > 0) {
4392 // Credit note
4393 if (!getDolGlobalString('INVOICE_DISABLE_CREDIT_NOTE')) {
4394 // Show link for credit note
4395 $facids = $facturestatic->list_qualified_avoir_invoices($soc->id);
4396 if ($facids < 0) {
4397 dol_print_error($db, $facturestatic->error, $facturestatic->errors);
4398 exit;
4399 }
4400 $optionsav = "";
4401 $newinvoice_static = new Facture($db);
4402 foreach ($facids as $key => $valarray) {
4403 $newinvoice_static->id = $key;
4404 $newinvoice_static->ref = $valarray ['ref'];
4405 $newinvoice_static->statut = $valarray ['status'];
4406 $newinvoice_static->status = $valarray ['status'];
4407 $newinvoice_static->type = $valarray ['type'];
4408 $newinvoice_static->paye = $valarray ['paye'];
4409 $newinvoice_static->paid = $valarray ['paye'];
4410
4411 $optionsav .= '<option value="'.$key.'"';
4412 if ($key == GETPOST('fac_avoir')) {
4413 $optionsav .= ' selected';
4414
4415 // pre-filled extra fields with selected credit note
4416 $newinvoice_static->fetch_optionals($key);
4417 $object->array_options = $newinvoice_static->array_options;
4418 }
4419 $optionsav .= '>';
4420 $optionsav .= $newinvoice_static->ref;
4421 $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray ['paymentornot']).')';
4422 $optionsav .= '</option>';
4423 }
4424
4425 print '<div class="listofinvoicetype"><div class="">';
4426 $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST('type') == 2 ? ' checked' : '');
4427 if ((!$optionsav && !getDolGlobalString('INVOICE_CREDIT_NOTE_STANDALONE')) || $invoice_predefined->id > 0) {
4428 $tmp .= ' disabled';
4429 }
4430 $tmp .= '> ';
4431 // Show credit note options only if we checked credit note and disable standard invoice if "create credit note" button is pressed
4432 print '<script type="text/javascript">
4433 jQuery(document).ready(function() {
4434 if (jQuery("#radio_creditnote").is(":checked")) {
4435 jQuery("#radio_standard").prop("disabled", true);
4436 jQuery("#radio_deposit").prop("disabled", true);
4437 } else {
4438 jQuery("#radio_standard").prop("disabled", false);
4439 jQuery("#radio_deposit").prop("disabled", false);
4440 }
4441 if (! jQuery("#radio_creditnote").is(":checked")) {
4442 jQuery("#credit_note_options").hide();
4443 }
4444 jQuery("#radio_creditnote").click(function() {
4445 jQuery("#credit_note_options").show();
4446 });
4447 jQuery("#radio_standard, #radio_replacement, #radio_deposit, #radio_situation, #radio_situation_bis").click(function() {
4448 console.log("We click on a radio to close credit not options");
4449 jQuery("#credit_note_options").hide();
4450 });
4451 });
4452 </script>';
4453 $text = '<label>'.$tmp.$langs->transnoentities("InvoiceAvoirAsk").'</label> ';
4454 $text .= '<select class="flat valignmiddle minwidth200" name="fac_avoir" id="fac_avoir"';
4455 if (!$optionsav || $invoice_predefined->id > 0) {
4456 $text .= ' disabled';
4457 }
4458 $text .= '>';
4459 if ($optionsav) {
4460 $text .= '<option value="-1">'.$langs->trans("InvoiceAvoirAskCombo").'</option>';
4461 $text .= $optionsav;
4462 } else {
4463 $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
4464 }
4465 $text .= '</select>';
4466 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
4467 print $desc;
4468
4469 print '<div id="credit_note_options" class="clearboth paddingtop marginbottomonly">';
4470 print '<div class="marginleftlargeondesktop"><input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOSTINT('invoiceAvoirWithLines') > 0 ? 'checked' : '').' /> <label for="invoiceAvoirWithLines" class="small">'.$langs->trans('invoiceAvoirWithLines')."</label></div>";
4471 print '<div class="marginleftlargeondesktop"><input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOSTINT('invoiceAvoirWithPaymentRestAmount') > 0 ? 'checked' : '').' /> <label for="invoiceAvoirWithPaymentRestAmount" class="small">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label></div>";
4472 // Adding a checkbox: "Automatically consume the credit note to close the corrected invoice" is better to be into
4473 // the confirm popup when we validate the credit note
4474 print '</div>';
4475
4476 print '</div></div>'."\n";
4477 }
4478 } else {
4479 print '<div class="listofinvoicetype"><div class="">';
4480 if (!getDolGlobalString('INVOICE_CREDIT_NOTE_STANDALONE')) {
4481 $tmp = '<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
4482 } else {
4483 $tmp = '<input type="radio" name="type" id="radio_creditnote" value="2" > ';
4484 }
4485 $text = $tmp.'<label class="opacitymedium" for="radio_creditnote">'.$langs->trans("InvoiceAvoir").'</label> ';
4486 //$text .= '<span class="opacitymedium hideonsmartphone">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
4487 $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc").'<br><br>'.$langs->trans("CreateCreditNoteWhenClientInvoiceExists"), 1, 'help', '', 0, 3, 'creditnoteonsmartphone');
4488 print $desc;
4489 print '</div></div>'."\n";
4490 }
4491 }
4492
4493 // Template invoice
4494 /*
4495 print '<div class="listofinvoicetype"><div class="">';
4496 $tmp = '<input type="radio" name="type" id="radio_template" value="0" disabled> ';
4497 $text = $tmp.'<label class="opacitymedium" for="radio_template">'.$langs->trans("RepeatableInvoice").'</label> ';
4498 $desc = $form->textwithpicto($text, $langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', '', 0, 3, 'templateonsmartphone');
4499 print $desc;
4500 print '</div></div>'."\n";
4501 */
4502
4503 print '</div><br>';
4504
4505
4506 if (getDolGlobalString('INVOICE_USE_DEFAULT_DOCUMENT')) { // Hidden conf
4507 // Add auto select default document model
4509 $jsListType = '';
4510 foreach ($listtType as $type) {
4511 $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$type;
4512 $current = getDolGlobalString($thisTypeConfName, getDolGlobalString('FACTURE_ADDON_PDF'));
4513 $jsListType .= (!empty($jsListType) ? ',' : '').'"'.$type.'":"'.$current.'"';
4514 }
4515
4516 print '<script type="text/javascript">
4517 $(document).ready(function() {
4518 var listType = {'.$jsListType.'};
4519 $("[name=\'type\']").change(function() {
4520 console.log("change name=type");
4521 if ($( this ).prop("checked"))
4522 {
4523 if(($( this ).val() in listType))
4524 {
4525 $("#model").val(listType[$( this ).val()]).trigger("change");
4526 }
4527 else
4528 {
4529 $("#model").val("' . getDolGlobalString('FACTURE_ADDON_PDF').'").trigger("change");
4530 }
4531 }
4532 });
4533 });
4534 </script>';
4535 }
4536
4537
4538 print '</td></tr>';
4539
4540 // Invoice Subtype
4541 if (getDolGlobalInt('INVOICE_SUBTYPE_ENABLED')) {
4542 print '<tr><td class="fieldrequired">'.$langs->trans('InvoiceSubtype').'</td><td colspan="2">';
4543 print $form->getSelectInvoiceSubtype(GETPOSTINT('subtype'), 'subtype', 1, 0, '');
4544 print '</td></tr>';
4545 }
4546
4547 // Discounts for the known third party
4548 if ($socid > 0) {
4549 print '<tr><td>'.$langs->trans('DiscountStillRemaining').'</td><td colspan="2">';
4550
4551 $thirdparty = $soc; // used by object_discounts.tpl.php
4552 $discount_type = 0; // used by object_discounts.tpl.php
4553 $backtopage = $_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.urlencode((string) (GETPOST('origin'))).'&originid='.urlencode((string) (GETPOSTINT('originid')));
4554
4555 // loading object_discounts.tpl.php from module core/tpl if exists
4556 $defaulttpldir = '/core/tpl';
4557 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4558 foreach ($dirtpls as $module => $reldir) {
4559 $res = 0;
4560 if (!empty($module)) {
4561 $tpl = dol_buildpath($reldir.'/object_discounts.tpl.php');
4562 } else {
4563 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/object_discounts.tpl.php';
4564 }
4565 if (file_exists($tpl)) {
4566 if (empty($conf->file->strict_mode)) {
4567 $res = @include $tpl;
4568 } else {
4569 $res = include $tpl;
4570 }
4571 }
4572 if ($res) {
4573 break;
4574 }
4575 }
4576
4577 print '</td></tr>';
4578 }
4579
4580 $newdateinvoice = dol_mktime(0, 0, 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'), 'tzserver');
4581 $date_pointoftax = dol_mktime(0, 0, 0, GETPOSTINT('date_pointoftaxmonth'), GETPOSTINT('date_pointoftaxday'), GETPOSTINT('date_pointoftaxyear'), 'tzserver');
4582
4583 // Date invoice
4584 print '<tr><td class="fieldrequired">'.$langs->trans('DateInvoice').'</td><td colspan="2">';
4585 print img_picto('', 'action', 'class="pictofixedwidth"');
4586 print $form->selectDate($newdateinvoice ? $newdateinvoice : $dateinvoice, '', 0, 0, 0, "add", 1, 1);
4587 print '</td></tr>';
4588
4589 // Date point of tax
4590 if (getDolGlobalString('INVOICE_POINTOFTAX_DATE')) {
4591 print '<tr><td class="fieldrequired">'.$langs->trans('DatePointOfTax').'</td><td colspan="2">';
4592 print img_picto('', 'action', 'class="pictofixedwidth"');
4593 print $form->selectDate($date_pointoftax ? $date_pointoftax : -1, 'date_pointoftax', 0, 0, 0, "add", 1, 1);
4594 print '</td></tr>';
4595 }
4596
4597 // Payment term
4598 print '<tr><td class="nowrap fieldrequired">'.$langs->trans('PaymentConditionsShort').'</td><td colspan="2">';
4599 print img_picto('', 'payment', 'class="pictofixedwidth"');
4600 print $form->getSelectConditionsPaiements((int) $cond_reglement_id, 'cond_reglement_id', -1, 1, 0, 'maxwidth500 widthcentpercentminusx');
4601 print '</td></tr>';
4602
4603 // Retained warranty
4604 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
4605 $rwStyle = 'display:none;';
4606 if (in_array(GETPOSTINT('type'), $retainedWarrantyInvoiceAvailableType)) {
4607 $rwStyle = '';
4608 }
4609
4610 $retained_warranty = GETPOSTINT('retained_warranty');
4611 if (empty($retained_warranty)) {
4612 if ($objectsrc !== null && property_exists($objectsrc, 'retained_warranty') && !empty($objectsrc->retained_warranty)) { // use previous situation value
4613 // Facture->retained_warranty (does not exist on Expedition)
4614 $retained_warranty = $objectsrc->retained_warranty; // @phan-suppress-current-line PhanUndeclaredProperty
4615 }
4616 }
4617 $retained_warranty_js_default = !empty($retained_warranty) ? $retained_warranty : getDolGlobalString('INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_PERCENT');
4618
4619 print '<tr class="retained-warranty-line" style="'.$rwStyle.'" ><td class="nowrap">'.$langs->trans('RetainedWarranty').'</td><td colspan="2">';
4620 print '<input id="new-situation-invoice-retained-warranty" name="retained_warranty" type="number" value="'.$retained_warranty.'" step="0.01" min="0" max="100" />%';
4621
4622 // Retained warranty payment term
4623 print '<tr class="retained-warranty-line" style="'.$rwStyle.'" ><td class="nowrap">'.$langs->trans('PaymentConditionsShortRetainedWarranty').'</td><td colspan="2">';
4624 $retained_warranty_fk_cond_reglement = GETPOSTINT('retained_warranty_fk_cond_reglement');
4625 if (empty($retained_warranty_fk_cond_reglement)) {
4626 $retained_warranty_fk_cond_reglement = getDolGlobalString('INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID');
4627 if ($objectsrc instanceOf Facture && !empty($objectsrc->retained_warranty_fk_cond_reglement)) { // use previous situation value
4628 // Facture->retained_warranty_fk_cond_reglement (does not exist on Expedition)
4629 $retained_warranty_fk_cond_reglement = $objectsrc->retained_warranty_fk_cond_reglement; // @phan-suppress-current-line PhanUndeclaredProperty
4630 }
4631 }
4632 print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
4633 print '</td></tr>';
4634
4635 print '<script type="text/javascript">
4636 $(document).ready(function() {
4637 $("[name=\'type\']").change(function() {
4638 if($( this ).prop("checked") && $.inArray($( this ).val(), '.json_encode($retainedWarrantyInvoiceAvailableType).' ) !== -1)
4639 {
4640 $(".retained-warranty-line").show();
4641 $("#new-situation-invoice-retained-warranty").val("'.(float) $retained_warranty_js_default.'");
4642 }
4643 else{
4644 $(".retained-warranty-line").hide();
4645 $("#new-situation-invoice-retained-warranty").val("");
4646 }
4647 });
4648
4649 $("[name=\'type\']:checked").trigger("change");
4650 });
4651 </script>';
4652 }
4653
4654 // Payment mode
4655 print '<tr><td>'.$langs->trans('PaymentMode').'</td><td colspan="2">';
4656 print img_picto('', 'bank', 'class="pictofixedwidth"');
4657 print $form->select_types_paiements((string) $mode_reglement_id, 'mode_reglement_id', 'CRDT', 0, 1, 0, 0, 1, 'maxwidth250 widthcentpercentminusx', 1);
4658 print '</td></tr>';
4659
4660 // Bank Account
4661 if (isModEnabled("bank")) {
4662 print '<tr><td>'.$langs->trans('DefaultBankAccount').'</td><td colspan="2">';
4663 print img_picto('', 'bank_account', 'class="pictofixedwidth"');
4664 print $form->select_comptes((int) $fk_account, 'fk_account', 0, '', 1, '', 0, 'maxwidth250 widthcentpercentminusx', 1);
4665 print '</td></tr>';
4666 }
4667
4668 // Source / Channel - What trigger creation
4669 if (!getDolGlobalInt('INVOICE_DISABLE_SOURCE')) {
4670 print '<tr><td>'.$langs->trans('Source').'</td><td>';
4671 print img_picto('', 'question', 'class="pictofixedwidth"');
4672 $form->selectInputReason((string) $inputReasonId, 'input_reason_id', '', 1, 'maxwidth250 widthcentpercentminusx');
4673 print '</td></tr>';
4674 } else {
4675 print '<input type="hidden" name="input_reason_id" value="'.((string) $inputReasonId).'">';
4676 }
4677
4678 // Project
4679 if (isModEnabled('project') && is_object($formproject)) {
4680 $langs->load('projects');
4681 print '<tr><td>'.$langs->trans('Project').'</td><td colspan="2">';
4682 print img_picto('', 'project', 'class="pictofixedwidth"');
4683
4684 print $formproject->select_projects((($socid > 0 && !getDolGlobalString('PROJECT_CAN_ALWAYS_LINK_TO_ALL_CUSTOMERS')) ? $socid : -1), (string) $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
4685 print ' <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id.($fac_rec ? '&fac_rec='.$fac_rec : '')).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
4686 print '</td></tr>';
4687 }
4688
4689 // Incoterms
4690 if (isModEnabled('incoterm')) {
4691 print '<tr>';
4692 print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->label_incoterms) ? $objectsrc->label_incoterms : '', 1).'</label></td>';
4693 print '<td colspan="2" class="maxwidthonsmartphone">';
4694 $incoterm_id = GETPOST('incoterm_id');
4695 $location_incoterms = GETPOST('location_incoterms');
4696 if (empty($incoterm_id)) {
4697 $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
4698 $location_incoterms = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
4699 }
4700 print img_picto('', 'incoterm', 'class="pictofixedwidth"');
4701 print $form->select_incoterms($incoterm_id, $location_incoterms);
4702 print '</td></tr>';
4703 }
4704
4705 // Dispute
4706 /* Not necessary on creation
4707 print '<tr><td class="nowrap fieldrequired">'.$langs->trans('Dispute').'</td><td colspan="2">';
4708 //print yn($object->dispute_status);
4709 print '</td></tr>';
4710 */
4711
4712 // Category
4713 if (isModEnabled('category')) {
4714 // Categories
4715 print '<tr><td>'.$langs->trans("Categories").'</td><td colspan="3">';
4716 print $form->selectCategories(Categorie::TYPE_INVOICE, 'categories', $object);
4717 print "</td></tr>";
4718 }
4719
4720 // Other attributes
4721 $parameters = array('objectsrc' => !empty($objectsrc) ? $objectsrc : 0, 'colspan' => ' colspan="2"', 'cols' => '2', 'socid' => $socid);
4722 $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
4723 print $hookmanager->resPrint;
4724 if (empty($reshook)) {
4725 if (getDolGlobalString('THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE') && !empty($soc->id)) {
4726 // copy from thirdparty
4727 $tpExtrafields = new ExtraFields($db);
4728 $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
4729 if ($soc->fetch_optionals() > 0) {
4730 $object->array_options = array_merge($object->array_options, $soc->array_options);
4731 }
4732 }
4733
4734 print $object->showOptionals($extrafields, 'create', $parameters);
4735 }
4736
4737 // Template to use by default
4738 include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
4740 if (is_array($list) && count($list) > 0) {
4741 if (getDolGlobalString('INVOICE_USE_DEFAULT_DOCUMENT')) {
4742 $type = GETPOSTISSET('type') ? GETPOSTINT('type') : $object->type;
4743 // Hidden conf
4744 $paramkey = 'FACTURE_ADDON_PDF_'.$type;
4745 $preselected = getDolGlobalString($paramkey, getDolGlobalString('FACTURE_ADDON_PDF'));
4746 } else {
4747 $preselected = getDolGlobalString('FACTURE_ADDON_PDF');
4748 }
4749 if (count($list) > 1) {
4750 print '<tr><td>'.$langs->trans('Model').'</td>';
4751 print '<td colspan="2">';
4752 print img_picto('', 'pdf', 'class="pictofixedwidth"');
4753 print $form->selectarray('model', $list, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1);
4754 print "</td></tr>";
4755 } else {
4756 print '<input type="hidden" name="model" value="'.$preselected.'">';
4757 }
4758 }
4759
4760 // Multicurrency
4761 if (isModEnabled('multicurrency')) {
4762 print '<tr>';
4763 print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
4764 print '<td colspan="2" class="maxwidthonsmartphone">';
4765 print img_picto('', 'currency', 'class="pictofixedwidth"');
4766 print $form->selectMultiCurrency(((GETPOSTISSET('multicurrency_code') && !GETPOST('changecompany')) ? GETPOST('multicurrency_code') : $currency_code), 'multicurrency_code', 0, '', false, 'maxwidth200 widthcentpercentminusx');
4767 print '</td></tr>';
4768 }
4769
4770 // Help of substitution key
4771 $htmltext = '';
4772 if (GETPOSTINT('fac_rec') > 0) {
4773 $dateexample = ($newdateinvoice ? $newdateinvoice : $dateinvoice);
4774 if (empty($dateexample)) {
4775 $dateexample = dol_now();
4776 }
4777 $substitutionarray = array(
4778 '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')',
4779 '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')',
4780 '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m').')',
4781 '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%m').')',
4782 '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m').')',
4783 '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B').')',
4784 '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%B').')',
4785 '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')',
4786 '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y').')',
4787 '__INVOICE_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')',
4788 '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y').')'
4789 );
4790
4791 $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
4792 foreach ($substitutionarray as $key => $val) {
4793 $htmltext .= $key.' = '.$langs->trans($val).'<br>';
4794 }
4795 $htmltext .= '</i>';
4796 }
4797
4798 // Public note
4799 print '<tr>';
4800 print '<td class="tdtop">';
4801 print $form->textwithpicto($langs->trans('NotePublic'), $htmltext);
4802 print '</td>';
4803 print '<td valign="top" colspan="2">';
4804 $doleditor = new DolEditor('note_public', (string) $note_public, '', 80, 'dolibarr_notes', 'In', false, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PUBLIC') ? 0 : 1, ROWS_3, '90%');
4805 print $doleditor->Create(1);
4806
4807 // Private note
4808 if (empty($user->socid)) {
4809 print '<tr>';
4810 print '<td class="tdtop">';
4811 print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext);
4812 print '</td>';
4813 print '<td valign="top" colspan="2">';
4814 $doleditor = new DolEditor('note_private', (string) $note_private, '', 80, 'dolibarr_notes', 'In', false, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PRIVATE') ? 0 : 1, ROWS_3, '90%');
4815 print $doleditor->Create(1);
4816 // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
4817 print '</td></tr>';
4818 }
4819
4820 // Lines from source (TODO Show them also when creating invoice from template invoice)
4821 if (!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($classname)) {
4822 $langs->loadLangs(array('orders', 'propal'));
4823
4824 // TODO for compatibility
4825 if ($origin == 'contrat') {
4826 '@phan-var-force Contrat $objectsrc';
4827 // Recalculate contrat->price (excl. VAT), contrat->total (incl. VAT), contrat->tva
4828 $objectsrc->update_price(1, 'auto', 1);
4829 }
4830
4831 print "\n<!-- Show ref of origin ".$classname." -->\n";
4832 print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
4833 print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
4834 print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
4835 // The commented lines below are fields already added as hidden parameters before
4836 //print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
4837 //print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
4838
4839 switch (get_class($objectsrc)) {
4840 case 'Propal':
4841 $newclassname = 'CommercialProposal';
4842 break;
4843 case 'Commande':
4844 $newclassname = 'Order';
4845 break;
4846 case 'Expedition':
4847 $newclassname = 'Sending';
4848 break;
4849 case 'Contrat':
4850 $newclassname = 'Contract';
4851 break;
4852 case 'Fichinter':
4853 $newclassname = 'Intervention';
4854 break;
4855 default:
4856 $newclassname = get_class($objectsrc);
4857 }
4858
4859 // Ref of origin
4860 print '<tr><td>'.$langs->trans($newclassname).'</td>';
4861 print '<td colspan="2">';
4862 print $objectsrc->getNomUrl(1);
4863 // We check if Origin document (id and type is known) has already at least one invoice attached to it
4864 $objectsrc->fetchObjectLinked($originid, $origin, null, 'facture');
4865 if (isset($objectsrc->linkedObjects['facture']) && is_array($objectsrc->linkedObjects['facture']) && count($objectsrc->linkedObjects['facture']) >= 1) {
4866 setEventMessages('WarningBillExist', null, 'warnings');
4867 echo ' - '.$langs->trans('LatestRelatedBill').' '.end($objectsrc->linkedObjects['facture'])->getNomUrl(1);
4868 }
4869 echo '</td></tr>';
4870
4871 print '<tr><td>'.$langs->trans('AmountHT').'</td><td colspan="2">'.price($objectsrc->total_ht, 1, $langs, 1, -1, '', $conf->currency).'</td></tr>';
4872 print '<tr><td>'.$langs->trans('AmountVAT').'</td><td colspan="2">'.price($objectsrc->total_tva, 1, $langs, 1, -1, '', $conf->currency)."</td></tr>";
4873 if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1
4874 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax1, 1, $langs, 1, -1, '', $conf->currency)."</td></tr>";
4875 }
4876
4877 if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2
4878 print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax2, 1, $langs, 1, -1, '', $conf->currency)."</td></tr>";
4879 }
4880 print '<tr><td>'.$langs->trans('AmountTTC').'</td><td colspan="2">'.price($objectsrc->total_ttc, 1, $langs, 1, -1, '', $conf->currency)."</td></tr>";
4881
4882 if (isModEnabled('multicurrency') && $objectsrc->multicurrency_code != $conf->currency) {
4883 //var_dump($objectsrc);
4884 print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ht, 1, $langs, 1, -1, '', $objectsrc->multicurrency_code).'</td></tr>';
4885 print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_tva, 1, $langs, 1, -1, '', $objectsrc->multicurrency_code)."</td></tr>";
4886 print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ttc, 1, $langs, 1, -1, '', $objectsrc->multicurrency_code)."</td></tr>";
4887 }
4888 }
4889
4890 print "</table>\n";
4891 }
4892 print dol_get_fiche_end();
4893
4894 print $form->buttonsSaveCancel("CreateDraft");
4895
4896 // Show origin lines
4897 if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
4898 print '<br>';
4899
4900 $title = $langs->trans('ProductsAndServices');
4901 print load_fiche_titre($title);
4902
4903 print '<div class="div-table-responsive-no-min">';
4904 print '<table class="noborder centpercent">';
4905
4906 $objectsrc->printOriginLinesList('', $selectedLines);
4907
4908 print '</table>';
4909 print '</div>';
4910 }
4911
4912 print "</form>\n";
4913} elseif ($id > 0 || !empty($ref)) {
4914 if (empty($object->id)) {
4915 $langs->load('errors');
4916 echo '<div class="error">'.$langs->trans("ErrorRecordNotFound").'</div>';
4917 llxFooter();
4918 exit;
4919 }
4920
4921 /*
4922 * Show object in view mode
4923 */
4924
4925 if ($user->socid > 0 && $user->socid != $object->socid) {
4926 accessforbidden('', 0, 1);
4927 }
4928
4929 $result = $object->fetch_thirdparty();
4930
4931 $result = $soc->fetch($object->socid);
4932 if ($result < 0) {
4934 }
4935 $selleruserevenustamp = $mysoc->useRevenueStamp();
4936
4937 $totalpaid = $object->getSommePaiement();
4938 $totalcreditnotes = $object->getSumCreditNotesUsed();
4939 $totaldeposits = $object->getSumDepositsUsed();
4940 //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
4941 // selleruserrevenuestamp=".$selleruserevenustamp;
4942
4943 // We can also use bcadd to avoid pb with floating points
4944 // For example print 239.2 - 229.3 - 9.9; does not return 0.
4945 $resteapayer = price2num($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
4946
4947 // Multicurrency
4948 if (isModEnabled('multicurrency')) {
4949 $multicurrency_totalpaid = $object->getSommePaiement(1);
4950 $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
4951 $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
4952 $multicurrency_resteapayer = price2num($object->multicurrency_total_ttc - $multicurrency_totalpaid - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits, 'MT');
4953 // Code to fix case of corrupted data
4954 // TODO We should not need this. Also data comes from a not reliable value of $object->multicurrency_total_ttc that may be wrong if it was
4955 // 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)
4956 if ($resteapayer == 0 && $multicurrency_resteapayer != 0 && $object->multicurrency_code != $conf->currency) {
4957 $resteapayer = price2num((float) $multicurrency_resteapayer / $object->multicurrency_tx, 'MT');
4958 }
4959 }
4960
4961 if ($object->paye || $object->status == $object::STATUS_CLOSED) {
4962 $resteapayer = 0;
4963 }
4964 $resteapayeraffiche = $resteapayer;
4965
4966 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) { // Never use this
4967 $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
4968 $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
4969 } else {
4970 $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
4971 $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
4972 }
4973
4974 $absolute_discount = $soc->getAvailableDiscounts(null, $filterabsolutediscount);
4975 $absolute_creditnote = $soc->getAvailableDiscounts(null, $filtercreditnote);
4976 $absolute_discount = price2num($absolute_discount, 'MT');
4977 $absolute_creditnote = price2num($absolute_creditnote, 'MT');
4978
4979 $nb_creditnote_notyetavailable = $soc->getOpenCreditNotesNotYetConvertedIntoDiscount(0);
4980
4981 $author = new User($db);
4982 if ($object->user_creation_id) {
4983 $author->fetch($object->user_creation_id);
4984 }
4985
4986 $objectidnext = $object->getIdReplacingInvoice();
4987
4988 $head = facture_prepare_head($object);
4989
4990 print dol_get_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), -1, $object->picto, 0, '', '', 0, '', 1);
4991
4992 $formconfirm = '';
4993
4994 // Confirmation of the conversion of the credit into a reduction
4995 if ($action == 'converttoreduc') {
4997 $type_fac = 'ExcessReceived';
4998 } elseif ($object->type == Facture::TYPE_CREDIT_NOTE) {
4999 $type_fac = 'CreditNote';
5000 } elseif ($object->type == Facture::TYPE_DEPOSIT) {
5001 $type_fac = 'Deposit';
5002 } else {
5003 $type_fac = '';
5004 }
5005 $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac)));
5006 $text .= '<br>'.$langs->trans('ConfirmConvertToReduc2');
5007 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
5008 }
5009
5010 // Confirmation to delete invoice
5011 if ($action == 'delete') {
5012 $text = $langs->trans('ConfirmDeleteBill', $object->ref);
5013 $formquestion = array();
5014
5015 if ($object->type != Facture::TYPE_DEPOSIT && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $object->status >= 1) {
5016 $qualified_for_stock_change = 0;
5017 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
5018 $qualified_for_stock_change = $object->hasProductsOrServices(2);
5019 } else {
5020 $qualified_for_stock_change = $object->hasProductsOrServices(1);
5021 }
5022
5023 if ($qualified_for_stock_change) {
5024 $langs->load("stocks");
5025 require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
5026 $formproduct = new FormProduct($db);
5027 $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
5028 $forcecombo = 0;
5029 if ($conf->browser->name == 'ie') {
5030 $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
5031 }
5032 $formquestion = array(
5033 // 'text' => $langs->trans("ConfirmClone"),
5034 // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
5035 // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
5036 array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, $langs->trans("NoStockAction"), 0, $forcecombo))
5037 );
5038 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1);
5039 } else {
5040 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
5041 }
5042 } else {
5043 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
5044 }
5045 }
5046
5047 // Confirmation to remove invoice from cycle
5048 if ($action == 'situationout') {
5049 $text = $langs->trans('ConfirmRemoveSituationFromCycle', $object->ref);
5050 $label = $langs->trans("ConfirmOuting");
5051 $formquestion = array();
5052 // remove situation from cycle
5053 if (in_array($object->status, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
5054 && $usercancreate
5055 && !$objectidnext
5056 && $object->is_last_in_cycle()
5057 && $usercanunvalidate
5058 ) {
5059 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $label, $text, 'confirm_situationout', $formquestion, "yes", 1);
5060 }
5061 }
5062
5063 // Confirmation of validation
5064 if ($action == 'valid') {
5065 // we check object has a draft number
5066 $objectref = substr($object->ref, 1, 4);
5067 if ($objectref == 'PROV') {
5068 //$savdate = $object->date;
5069 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) {
5070 $object->date = dol_now();
5071 $object->date_lim_reglement = $object->calculate_date_lim_reglement();
5072 }
5073 $numref = $object->getNextNumRef($soc);
5074 // $object->date=$savdate;
5075 } else {
5076 $numref = (string) $object->ref;
5077 }
5078
5079 $text = $langs->trans('ConfirmValidateBill', $numref);
5080 if (getDolGlobalString('INVOICE_CAN_NEVER_BE_EDITED')) {
5081 $text .= '<br><br>';
5082 $text .= img_picto('', 'warning', 'class="pictofixedwidth"').' '.$langs->trans('WarningInvoiceCanNeverBeEdited');
5083 }
5084 if (isModEnabled('notification')) {
5085 require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
5086 $notify = new Notify($db);
5087 $text .= '<br>';
5088 $text .= $notify->confirmMessage('BILL_VALIDATE', $object->socid, $object);
5089 }
5090 $formquestion = array();
5091
5092 if ($object->type != Facture::TYPE_DEPOSIT && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
5093 $qualified_for_stock_change = 0;
5094 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
5095 $qualified_for_stock_change = $object->hasProductsOrServices(2);
5096 } else {
5097 $qualified_for_stock_change = $object->hasProductsOrServices(1);
5098 }
5099
5100 if ($qualified_for_stock_change) {
5101 $langs->load("stocks");
5102 require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
5103 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
5104 $formproduct = new FormProduct($db);
5105 $warehouse = new Entrepot($db);
5106 $warehouse_array = $warehouse->list_array();
5107 if (count($warehouse_array) == 1) {
5108 $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
5109 $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
5110 } else {
5111 $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
5112 $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
5113 }
5114 $formquestion = array(
5115 // 'text' => $langs->trans("ConfirmClone"),
5116 // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
5117 // 1),
5118 // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
5119 // => 1),
5120 array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value));
5121 }
5122 }
5123 if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) { // Can happen only if getDolGlobalString('FACTURE_ENABLE_NEGATIVE') is on
5124 $text .= '<br>'.img_warning().' '.$langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
5125 }
5126
5127 // mandatoryPeriod
5128 $nbMandated = 0;
5129 foreach ($object->lines as $line) {
5130 $res = $line->fetch_product();
5131 if ($res > 0) {
5132 if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end))) {
5133 $nbMandated++;
5134 break;
5135 }
5136 }
5137 }
5138 if ($nbMandated > 0) {
5139 if (getDolGlobalString('SERVICE_STRICT_MANDATORY_PERIOD')) {
5140 setEventMessages($langs->trans("mandatoryPeriodNeedTobeSetMsgValidate"), null, 'errors');
5141 $error++;
5142 } else {
5143 $text .= '<div><span class="clearboth nowraponall warning">'.img_warning().$langs->trans("mandatoryPeriodNeedTobeSetMsgValidate").'</span></div>';
5144 }
5145 }
5146
5147 if (!$error) {
5148 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, (($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) ? "no" : "yes"), 2, 0);
5149 }
5150 }
5151
5152 // Confirm back to draft status (action = 'modif')
5153 if ($action == 'modif') {
5154 $oktomodif = 1; // Assume we can modify by default
5155
5156 $testvalue = $object->isEditable();
5157 if ($testvalue < 0) {
5158 switch ($testvalue) {
5159 case -1:
5160 // Dispatched in bookkeeping
5161 setEventMessages($langs->trans("DisabledBecauseDispatchedInBookkeeping"), null, 'errors');
5162 break;
5163 case -2:
5164 // Not last invoice
5165 setEventMessages($langs->trans("DisabledBecauseNotLastInvoice"), null, 'errors');
5166 break;
5167 case -3:
5168 // Not last situation invoice
5169 setEventMessages($langs->trans("DisabledBecauseNotLastSituationInvoice"), null, 'errors');
5170 break;
5171 case -4:
5172 // At least one payment made
5173 setEventMessages($langs->trans("DisabledBecauseThereIsAPayment"), null, 'errors');
5174 break;
5175 case -5:
5176 // Already sent by email
5177 setEventMessages($langs->trans("DisabledBecauseAlreadySentByEmail"), null, 'errors');
5178 break;
5179 case -6:
5180 // Already printed once
5181 setEventMessages($langs->trans("DisabledBecauseAlreadyPrintedOnce"), null, 'errors');
5182 break;
5183 case -7:
5184 // Already validated
5185 setEventMessages($langs->trans("DisabledBecauseVersionProtected").(empty($object->error) ? '' : ': '.$object->error), null, 'errors');
5186 break;
5187 default:
5188 // Other error
5189 setEventMessages($langs->trans("DisabledBecauseNotEditable").(empty($object->error) ? ': UnknownReason' : ': '.$object->error), null, 'errors');
5190 break;
5191 }
5192 $oktomodif = 0;
5193 $action = '';
5194 }
5195
5196 if ($oktomodif) {
5197 $text = $langs->trans('ConfirmUnvalidateBill', $object->ref);
5198 $formquestion = array();
5199
5200 if ($object->type != Facture::TYPE_DEPOSIT && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
5201 $qualified_for_stock_change = 0;
5202 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
5203 $qualified_for_stock_change = $object->hasProductsOrServices(2);
5204 } else {
5205 $qualified_for_stock_change = $object->hasProductsOrServices(1);
5206 }
5207
5208 if ($qualified_for_stock_change) {
5209 $langs->load("stocks");
5210 require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
5211 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
5212 $formproduct = new FormProduct($db);
5213 $warehouse = new Entrepot($db);
5214 $warehouse_array = $warehouse->list_array();
5215 if (count($warehouse_array) == 1) {
5216 $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
5217 $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
5218 } else {
5219 $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
5220 $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
5221 }
5222 $formquestion = array(
5223 // 'text' => $langs->trans("ConfirmClone"),
5224 // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
5225 // 1),
5226 // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
5227 // => 1),
5228 array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value));
5229 }
5230 }
5231
5232 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('UnvalidateBill'), $text, 'confirm_modif', $formquestion, "yes", 1);
5233 }
5234 }
5235
5236 // Confirmation of status abandoned (when no payment never done)
5237 if ($action == 'canceled') {
5238 // If there is a replacement invoice not yet validated (draft state),
5239 // it is not allowed to classify the invoice as abandoned.
5240
5241 $statusreplacement = 0;
5242
5243 if ($objectidnext) {
5244 $facturereplacement = new Facture($db);
5245 $facturereplacement->fetch($objectidnext);
5246 $statusreplacement = $facturereplacement->status;
5247 }
5248 if ($objectidnext && $statusreplacement == 0) {
5249 print '<div class="error">'.$langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated").'</div>';
5250 } else {
5251 $close = array();
5252 // Code
5253 $close[1]['code'] = 'badcustomer';
5254 $close[2]['code'] = 'abandon';
5255 // Help
5256 $close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
5257 $close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
5258 // Text
5259 $close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close[1]['label'], 1);
5260 $close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
5261 // arrayreasons
5262 $arrayreasons = [];
5263 $arrayreasons[$close[1]['code']] = $close[1]['reason'];
5264 $arrayreasons[$close[2]['code']] = $close[2]['reason'];
5265
5266 // Create a form table
5267 $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'));
5268
5269 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 300);
5270 }
5271 }
5272
5273 // Confirmation of payment classification (when some payment started)
5274 if ($action == 'paid' && ($resteapayer <= 0 || (getDolGlobalString('INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') && $resteapayer == $object->total_ttc))) {
5275 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', "yes", 1);
5276 }
5277 if ($action == 'paid' && $resteapayer > 0 && (!getDolGlobalString('INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') || $resteapayer != $object->total_ttc)) {
5278 $close = array();
5279 // Code
5280 $i = 0;
5281 $close[$i]['code'] = $object::CLOSECODE_DISCOUNTVAT; // escompte
5282 $i++;
5283 $close[$i]['code'] = $object::CLOSECODE_BADDEBT;
5284 $i++;
5285 $close[$i]['code'] = $object::CLOSECODE_BANKCHARGE;
5286 $i++;
5287 $close[$i]['code'] = $object::CLOSECODE_WITHHOLDINGTAX;
5288 $i++;
5289 $close[$i]['code'] = $object::CLOSECODE_OTHER;
5290 $i++;
5291 // Help
5292 $i = 0;
5293 $close[$i]['label'] = $langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
5294 $i++;
5295 $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
5296 $i++;
5297 $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBankChargeDesc");
5298 $i++;
5299 $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonWithholdingTaxDesc");
5300 $i++;
5301 $close[$i]['label'] = $langs->trans("Other");
5302 $i++;
5303 // Texte
5304 $i = 0;
5305 $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
5306 $i++;
5307 $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
5308 $i++;
5309 $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBankCharge", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
5310 $i++;
5311 $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonWithholdingTax"), $close[$i]['label'], 1);
5312 $i++;
5313 $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("Other"), $close[$i]['label'], 1);
5314 $i++;
5315 // arrayreasons[code]=reason
5316 $arrayreasons = [];
5317 foreach ($close as $key => $val) {
5318 $arrayreasons[$close[$key]['code']] = '<span class="small">'.$close[$key]['reason'].'</span>';
5319 }
5320
5321 // Create a form table
5322 $formquestion = array(
5323 'text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"),
5324 0 => array('type' => 'radio', 'name' => 'close_code', 'label' => '', 'values' => $arrayreasons),
5325 1 => array('type' => 'text', 'name' => 'close_note', 'moreattr' => 'placeholder = "'.$langs->trans("Comment").'"', 'value' => '', 'morecss' => 'minwidth300'),
5326 2 => array('type' => 'separator')
5327 );
5328 // Incomplete payment. We ask if reason = discount or other
5329 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id.'&resteapayer='.((float) $resteapayer), $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 420, 600);
5330 }
5331
5332 if ($action == 'deletepayment') {
5333 $payment_id = GETPOST('paiement_id');
5334 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 'no', 1);
5335 }
5336
5337 // Confirm deletion of product line
5338 if ($action == 'ask_deleteline') {
5339 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
5340 }
5341
5342 // Confirm deletion of subtotal line
5343 if ($action == 'ask_subtotal_deleteline') {
5344 $langs->load("subtotals");
5345 $title = "DeleteSubtotalLine";
5346 $question = "ConfirmDeleteSubtotalLine";
5347 if (GETPOST('type') == 'title') {
5348 $formconfirm = array(array('type' => 'checkbox', 'name' => 'deletecorrespondingsubtotalline', 'label' => $langs->trans("DeleteCorrespondingSubtotalLine"), 'value' => 0));
5349 $title = "DeleteTitleLine";
5350 $question = "ConfirmDeleteTitleLine";
5351 }
5352 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id.'&lineid='.$lineid, $langs->trans($title), $langs->trans($question), 'confirm_delete_subtotalline', $formconfirm, 'no', 1);
5353 }
5354
5355 // Clone confirmation
5356 if ($action == 'clone') {
5357 $filter = '(s.client:IN:1,2,3)';
5358 // Create an array for form
5359 $formquestion = array(
5360 array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company($object->socid, 'socid', $filter, 1)),
5361 array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
5362 );
5363 // Request confirmation to clone
5364 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 0);
5365 }
5366
5367 // Subtotal line form
5368 if ($action == 'add_title_line') {
5369 $langs->load('subtotals');
5370 $type = 'title';
5371 $depth_array = $object->getPossibleLevels($langs);
5372 require dol_buildpath('/core/tpl/subtotal_create.tpl.php');
5373 } elseif ($action == 'add_subtotal_line') {
5374 $langs->load('subtotals');
5375 $type = 'subtotal';
5376 $titles = $object->getPossibleTitles();
5377 require dol_buildpath('/core/tpl/subtotal_create.tpl.php');
5378 }
5379
5380 if ($action == "remove_file_comfirm") {
5381 $file = GETPOST('file', 'alpha');
5382
5383 $formconfirm = $form->formconfirm(
5384 $_SERVER["PHP_SELF"].'?facid='.$object->id.'&file='.urlencode($file),
5385 $langs->trans('DeleteFileHeader'),
5386 $langs->trans('DeleteFileText')."<br><br>".$file,
5387 'remove_file',
5388 '',
5389 'no',
5390 1
5391 );
5392 }
5393
5394 // Call Hook formConfirm
5395 $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid, 'remainingtopay' => &$resteapayer);
5396 $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
5397 if (empty($reshook)) {
5398 $formconfirm .= $hookmanager->resPrint;
5399 } elseif ($reshook > 0) {
5400 $formconfirm = $hookmanager->resPrint;
5401 }
5402
5403 // Print form confirm
5404 print $formconfirm;
5405
5406 // Invoice content
5407
5408 $linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
5409
5410 $morehtmlref = '<div class="refidno">';
5411 // Ref invoice
5412 if ($object->status == $object::STATUS_DRAFT && !$mysoc->isInEEC() && getDolGlobalString('INVOICE_ALLOW_FREE_REF')) {
5413 $morehtmlref .= $form->editfieldkey("Ref", 'ref', $object->ref, $object, (int) $usercancreate, 'string', '', 0, 1);
5414 $morehtmlref .= $form->editfieldval("Ref", 'ref', $object->ref, $object, (int) $usercancreate, 'string', '', null, null, '', 1);
5415 $morehtmlref .= '<br>';
5416 }
5417 // Ref customer
5418 $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_customer, $object, (int) $usercancreate, 'string', '', 0, 1);
5419 $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_customer, $object, (int) $usercancreate, 'string'.(getDolGlobalString('THIRDPARTY_REF_INPUT_SIZE') ? ':' . getDolGlobalString('THIRDPARTY_REF_INPUT_SIZE') : ''), '', null, null, '', 1);
5420 // Thirdparty
5421 $morehtmlref .= '<br>'.$object->thirdparty->getNomUrl(1, 'customer');
5422 if (!getDolGlobalString('MAIN_DISABLE_OTHER_LINK') && $object->thirdparty->id > 0) {
5423 $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->thirdparty->id.'">'.$langs->trans("OtherBills").'</a>)';
5424 }
5425 // Project
5426 if (isModEnabled('project')) {
5427 $langs->load("projects");
5428 $morehtmlref .= '<br>';
5429 if ($usercancreate) {
5430 $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
5431 if ($action != 'classify') {
5432 $morehtmlref .= '<a class="editfielda" href="'.dolBuildUrl($_SERVER['PHP_SELF'], ['action' => 'classify', 'id' => $object->id], true).'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
5433 }
5434 $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, (string) $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
5435 } else {
5436 if (!empty($object->fk_project)) {
5437 $proj = new Project($db);
5438 $proj->fetch($object->fk_project);
5439 $morehtmlref .= $proj->getNomUrl(1);
5440 if ($proj->title) {
5441 $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
5442 }
5443 }
5444 }
5445 }
5446 $morehtmlref .= '</div>';
5447
5448 $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status
5449 $object->totalcreditnotes = $totalcreditnotes;
5450 $object->totaldeposits = $totaldeposits;
5451 $object->remaintopay = price2num($object->total_ttc - $object->totalpaid - $object->totalcreditnotes - $object->totaldeposits, 'MT');
5452
5453 dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '');
5454
5455 // Call Hook tabContentViewInvoice
5456 $parameters = array();
5457 // Note that $action and $object may be modified by hook
5458 $reshook = $hookmanager->executeHooks('tabContentViewInvoice', $parameters, $object, $action);
5459 if (empty($reshook)) {
5460 print '<div class="fichecenter">';
5461 print '<div class="fichehalfleft">';
5462 print '<div class="underbanner clearboth"></div>';
5463
5464 print '<table class="border centpercent tableforfield">';
5465
5466 // Type
5467 print '<tr><td class="fieldname_type">'.$langs->trans('Type').'</td><td class="valuefield fieldname_type">';
5468 print $object->getLibType(2);
5469 if ($object->subtype > 0) {
5470 print ' '.$object->getSubtypeLabel('facture');
5471 }
5472 if ($object->type == Facture::TYPE_REPLACEMENT) {
5473 $facreplaced = new Facture($db);
5474 $facreplaced->fetch($object->fk_facture_source);
5475 print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1, '', 32)).'</span>';
5476 }
5477 if ($object->type == Facture::TYPE_CREDIT_NOTE && !empty($object->fk_facture_source)) {
5478 $facusing = new Facture($db);
5479 $facusing->fetch($object->fk_facture_source);
5480 print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1, '', 32)).'</span>';
5481 }
5482
5483 // Retrieve credit note ids (credit notes generated from this invoice)
5484 $object->getListIdAvoirFromInvoice();
5485
5486 if (!empty($object->creditnote_ids)) {
5487 print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("InvoiceHasAvoir");
5488 $i = 0;
5489 foreach ($object->creditnote_ids as $invoiceid) {
5490 if ($i == 0) {
5491 print ' ';
5492 } else {
5493 print ',';
5494 }
5495 $creditnote = new Facture($db);
5496 $creditnote->fetch($invoiceid);
5497 print $creditnote->getNomUrl(1, '', 32);
5498 }
5499 print '</span>';
5500 }
5501 if ($objectidnext > 0) {
5502 $facthatreplace = new Facture($db);
5503 $facthatreplace->fetch($objectidnext);
5504 print ' <span class="opacitymediumbycolor paddingleft">'.str_replace('{s1}', $facthatreplace->getNomUrl(1), $langs->transnoentities("ReplacedByInvoice", '{s1}')).'</span>';
5505 }
5506
5508 $discount = new DiscountAbsolute($db);
5509 $result = $discount->fetch(0, $object->id);
5510 if ($result > 0) {
5511 print ' <span class="opacitymediumbycolor paddingleft">';
5512 $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}');
5513 $s = str_replace('{s1}', $object->getLibType(0), $s);
5514 $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s);
5515 print $s;
5516 print '</span><br>';
5517 }
5518 }
5519
5520 if ($object->fk_fac_rec_source > 0) {
5521 $tmptemplate = new FactureRec($db);
5522 $result = $tmptemplate->fetch($object->fk_fac_rec_source);
5523 if ($result > 0) {
5524 print ' <span class="opacitymediumbycolor paddingleft">';
5525 $s = $langs->transnoentities("GeneratedFromTemplate", '{s1}');
5526 $s = str_replace('{s1}', $tmptemplate->getNomUrl(1, '', 32), $s);
5527 print $s;
5528 print '</span>';
5529 } else {
5530 print ' <span class="opacitymediumbycolor paddingleft">';
5531 print $langs->transnoentities("GeneratedFromTemplate", $langs->trans("ObjectDeleted"));
5532 print '</span>';
5533 }
5534 }
5535 print '</td></tr>';
5536
5537 // POS
5538 if (isModEnabled('takepos') || $object->module_source || getDolGlobalString('INVOICE_ALLOW_POS_SOURCE_EDIT')) {
5539 $langs->load("cashdesk");
5540 print '<tr><td class="fieldname_type">';
5541 print '<table class="nobordernopadding centpercent"><tr><td>';
5542 print $form->textwithpicto($langs->trans('PointOfSale'), $langs->trans('POSInfo'));
5543 print '</td>';
5544 if ($action != 'editposinfo' && $usercancreate) {
5545 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editposinfo&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetPOSInfo'), 1).'</a></td>';
5546 }
5547 print '</tr></table>';
5548 print '</td><td class="valuefield fieldname_type">';
5549 print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" name="formposinfo">';
5550 print '<input type="hidden" name="action" value="setposinfo">';
5551 print '<input type="hidden" name="token" value="' . newToken() . '">';
5552 if ($action == 'editposinfo') {
5553 print '<input type="text" class="maxwidth150" name="posmodule" placeholder="'.$langs->trans("POSModule").'" value="'.$object->module_source.'"> ';
5554 print '<input type="text" class="maxwidth100" name="posterminal" placeholder="'.$langs->trans("Terminal").'" value="'.$object->pos_source.'">';
5555 print '<input type="submit" class="button" name="submitposinfo" value="'.$langs->trans("Submit").'">';
5556 } else {
5557 if ($object->module_source) {
5558 print '<span class="opacitymediumbycolor paddingleft">'.dolPrintHTML(ucfirst($object->module_source).' - '.$langs->transnoentitiesnoconv("Terminal").' '.$object->pos_source).'</span>';
5559 }
5560 }
5561 print '</form>';
5562 print '</td></tr>';
5563 }
5564
5565 // Relative and absolute discounts
5566 print '<!-- Discounts -->'."\n";
5567 print '<tr><td>'.$langs->trans('DiscountStillRemaining').'</td>';
5568 print '<td>';
5569 $thirdparty = $soc;
5570 $discount_type = 0;
5571 $backtopage = $_SERVER["PHP_SELF"].'?facid='.$object->id;
5572 $defaulttpldir = '/core/tpl';
5573 // loading object_discounts.tpl.php from module core/tpl if exists
5574 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5575 foreach ($dirtpls as $module => $reldir) {
5576 $res = 0;
5577 if (!empty($module)) {
5578 $tpl = dol_buildpath($reldir.'/object_discounts.tpl.php');
5579 } else {
5580 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/object_discounts.tpl.php';
5581 }
5582 if (file_exists($tpl)) {
5583 if (empty($conf->file->strict_mode)) {
5584 $res = @include $tpl;
5585 } else {
5586 $res = include $tpl;
5587 }
5588 }
5589 if ($res) {
5590 break;
5591 }
5592 }
5593
5594 print '</td></tr>';
5595
5596 // Date invoice
5597 print '<tr><td>';
5598 print '<table class="nobordernopadding centpercent"><tr><td>';
5599 print $langs->trans('DateInvoice');
5600 print '</td>';
5601 if ($action != 'editinvoicedate' && $object->status == $object::STATUS_DRAFT && $usercancreate && !getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) {
5602 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editinvoicedate&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
5603 }
5604 print '</tr></table>';
5605 print '</td><td>';
5606 if ($action == 'editinvoicedate') {
5607 $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->date, 'invoicedate');
5608 } else {
5609 print '<span class="valuedate">'.dol_print_date($object->date, 'day').'</span>';
5610 }
5611 print '</td>';
5612
5613 print '</tr>';
5614
5615 if (getDolGlobalString('INVOICE_POINTOFTAX_DATE')) {
5616 // Date invoice point of tax (Leistungsdatum / service date for tax).
5617 // Only editable while the invoice is a draft -- once validated, the
5618 // invoice is a legally issued document and date_pointoftax is the
5619 // basis for the VAT-return period assignment under accrual taxation
5620 // (Soll-Versteuerung). To correct, set the invoice back to draft or
5621 // issue a credit note.
5622 $editable = ($usercancreate && $object->status < Facture::STATUS_VALIDATED);
5623 print '<tr><td>';
5624 print '<table class="nobordernopadding centpercent"><tr><td>';
5625 print $langs->trans('DatePointOfTax');
5626 print '</td>';
5627 if ($editable) {
5628 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_pointoftax&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
5629 }
5630 print '</tr></table>';
5631 print '</td><td>';
5632 if ($action == 'editdate_pointoftax' && $editable) {
5633 $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->date_pointoftax, 'date_pointoftax');
5634 } else {
5635 print '<span class="valuedate">'.dol_print_date($object->date_pointoftax, 'day').'</span>';
5636 }
5637 print '</td></tr>';
5638 }
5639
5640 // Source reason (why we have an invoice)
5641 if (!getDolGlobalInt('INVOICE_DISABLE_SOURCE')) {
5642 print '<tr><td>';
5643 print $form->editfieldkey('Source', 'input_reason', '', $object, (int) $usercancreate);
5644 print '</td><td class="valuefield">';
5645 if ($action == 'editinput_reason') {
5646 $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->demand_reason_id, 'input_reason_id', 1, 'maxwidth250 widthcentpercentminusx');
5647 } else {
5648 $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->demand_reason_id, 'none');
5649 }
5650 print '</td></tr>';
5651 }
5652
5653 // Payment term
5654 print '<tr><td>';
5655 print '<table class="nobordernopadding centpercent"><tr><td>';
5656 print $langs->trans('PaymentConditionsShort');
5657 print '</td>';
5658 if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && $usercancreate) {
5659 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
5660 }
5661 print '</tr></table>';
5662 print '</td><td>';
5663 if ($object->type != Facture::TYPE_CREDIT_NOTE) {
5664 if ($action == 'editconditions') {
5665 $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, (string) $object->cond_reglement_id, 'cond_reglement_id');
5666 } else {
5667 $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, (string) $object->cond_reglement_id, 'none');
5668 }
5669 }
5670 print '</td></tr>';
5671
5672 // Date payment term
5673 print '<tr><td>';
5674 print '<table class="nobordernopadding centpercent"><tr><td>';
5675 print $langs->trans('DateMaxPayment');
5676 print '</td>';
5677 if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && $usercancreate) {
5678 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editpaymentterm&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
5679 }
5680 print '</tr></table>';
5681 print '</td><td>';
5682 if ($object->type != Facture::TYPE_CREDIT_NOTE) {
5683 if ($action == 'editpaymentterm') {
5684 $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->date_lim_reglement, 'paymentterm');
5685 } else {
5686 print '<span class="valuedate">'.dol_print_date($object->date_lim_reglement, 'day').'</span>';
5687 if ($object->hasDelay()) {
5688 print img_warning($langs->trans('Late'));
5689 }
5690 }
5691 }
5692 print '</td></tr>';
5693
5694 // Payment mode
5695 print '<tr><td>';
5696 print '<table class="nobordernopadding centpercent"><tr><td>';
5697 print $langs->trans('PaymentMode');
5698 print '</td>';
5699 if ($action != 'editmode' && $usercancreate) {
5700 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
5701 }
5702 print '</tr></table>';
5703 print '</td><td>';
5704 if ($action == 'editmode') {
5705 $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, (string) $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
5706 } else {
5707 $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, (string) $object->mode_reglement_id, 'none', 'CRDT');
5708 }
5709 print '</td></tr>';
5710
5711 // Bank Account
5712 if (isModEnabled("bank")) {
5713 print '<tr><td class="nowrap">';
5714 print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
5715 print $langs->trans('DefaultBankAccount');
5716 print '<td>';
5717 if (($action != 'editbankaccount') && $usercancreate) {
5718 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>';
5719 }
5720 print '</tr></table>';
5721 print '</td><td>';
5722 if ($action == 'editbankaccount') {
5723 $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->fk_account, 'fk_account', 1);
5724 } else {
5725 $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, (string) $object->fk_account, 'none');
5726 }
5727 print "</td>";
5728 print '</tr>';
5729 }
5730
5731 // Incoterms
5732 if (isModEnabled('incoterm')) {
5733 print '<tr><td>';
5734 print '<table class="nobordernopadding centpercent"><tr><td>';
5735 print $langs->trans('IncotermLabel');
5736 print '<td><td class="right">';
5737 if ($usercancreate) {
5738 print '<a class="editfielda" href="'.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$object->id.'&action=editincoterm&token='.newToken().'">'.img_edit().'</a>';
5739 }
5740 print '</td></tr></table>';
5741 print '</td>';
5742 print '<td>';
5743 if ($action != 'editincoterm') {
5744 print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
5745 } else {
5746 print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
5747 }
5748 print '</td></tr>';
5749 }
5750
5751 // Dispute open
5752 print '<tr><td>';
5753 print '<table class="nobordernopadding centpercent"><tr><td>';
5754 print $langs->trans('Dispute');
5755 print '<td><td class="right">';
5756 if ($usercancreate) {
5757 print '<a class="editfielda" href="'.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$object->id.'&action=editdispute_status&token='.newToken().'">'.img_edit().'</a>';
5758 }
5759 print '</td></tr></table>';
5760 print '</td><td>';
5761 $liststatus = Facture::ARRAY_OF_DISPUTE_STATUS;
5762 if ($action != 'editdispute_status') {
5763 if ($object->dispute_status) {
5764 print $langs->trans($liststatus[$object->dispute_status]['label']);
5765 }
5766 } else {
5767 print '<form enctype="multipart/form-data" action="'.DOL_URL_ROOT.'/compta/facture/card.php" method="POST">';
5768 print '<input type="hidden" name="action" value="set_dispute_status">';
5769 print '<input type="hidden" name="token" value="'.newToken().'">';
5770 print '<input type="hidden" name="id" value="'.$object->id.'">';
5771 print '<input type="hidden" name="page_y" value="">';
5772 print $form->selectarray('dispute_status', $liststatus, $object->dispute_status, 0, 0, 0, '', 1);
5773 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Save").'">';
5774 print '</form>';
5775 }
5776 print '</td></tr>';
5777
5778 // Categories
5779 if (isModEnabled('category')) {
5780 print '<tr><td>';
5781 print '<table class="nobordernopadding centpercent"><tr><td>';
5782 print $langs->trans("Categories");
5783 print '<td><td class="right">';
5784 if ($usercancreate) {
5785 print '<a class="editfielda" href="'.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$object->id.'&action=edittags&token='.newToken().'">'.img_edit().'</a>';
5786 } else {
5787 print '&nbsp;';
5788 }
5789 print '</td></tr></table>';
5790 print '</td>';
5791 print '<td>';
5792 if ($action == 'edittags') {
5793 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
5794 print '<input type="hidden" name="action" value="settags">';
5795 print '<input type="hidden" name="token" value="'.newToken().'">';
5796 print $form->selectCategories(Categorie::TYPE_INVOICE, 'categories', $object);
5797 print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
5798 print '</form>';
5799 } else {
5800 print $form->showCategories($object->id, Categorie::TYPE_INVOICE, 1);
5801 }
5802 print "</td></tr>";
5803 }
5804
5805 $displayWarranty = false;
5806
5807 if (!empty($object->retained_warranty) || getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
5808 $displayWarranty = true;
5809 if (!in_array($object->type, $retainedWarrantyInvoiceAvailableType) && empty($object->retained_warranty)) {
5810 $displayWarranty = false;
5811 }
5812
5813 if ($displayWarranty) {
5814 // Retained Warranty
5815 print '<tr class="retained-warranty-lines" ><td>';
5816 print '<table id="retained-warranty-table" class="nobordernopadding centpercent"><tr><td>';
5817 print $langs->trans('RetainedWarranty');
5818 print '</td>';
5819 if ($action != 'editretainedwarranty' && $user->hasRight('facture', 'creer') && $object->status == Facture::STATUS_DRAFT) {
5820 print '<td align="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editretainedwarranty&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('setRetainedWarranty'), 1).'</a></td>';
5821 }
5822
5823 print '</tr></table>';
5824 print '</td><td>';
5825 if ($action == 'editretainedwarranty' && $object->status == Facture::STATUS_DRAFT) {
5826 print '<form id="retained-warranty-form" method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
5827 print '<input type="hidden" name="action" value="setretainedwarranty">';
5828 print '<input type="hidden" name="token" value="'.newToken().'">';
5829 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
5830 print '<input name="retained_warranty" type="number" step="0.01" min="0" max="100" value="'.$object->retained_warranty.'" >';
5831 print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
5832 print '</form>';
5833 } else {
5834 print price($object->retained_warranty).'%';
5835 }
5836 print '</td></tr>';
5837
5838 // Retained warranty payment term
5839 print '<tr class="retained-warranty-lines" ><td>';
5840 print '<table id="retained-warranty-cond-reglement-table" class="nobordernopadding" width="100%"><tr><td>';
5841 print $langs->trans('PaymentConditionsShortRetainedWarranty');
5842 print '</td>';
5843 if ($action != 'editretainedwarrantypaymentterms' && $user->hasRight('facture', 'creer') && $object->status == Facture::STATUS_DRAFT) {
5844 print '<td align="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editretainedwarrantypaymentterms&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('setPaymentConditionsShortRetainedWarranty'), 1).'</a></td>';
5845 }
5846
5847 print '</tr></table>';
5848 print '</td><td>';
5849 $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
5850 if ($object->date > $defaultDate) {
5851 $defaultDate = $object->date;
5852 }
5853
5854 if ($action == 'editretainedwarrantypaymentterms' && $object->status == Facture::STATUS_DRAFT) {
5855 //date('Y-m-d',$object->date_lim_reglement)
5856 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
5857 print '<input type="hidden" name="action" value="setretainedwarrantyconditions">';
5858 print '<input type="hidden" name="token" value="'.newToken().'">';
5859 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
5860 $retained_warranty_fk_cond_reglement = GETPOSTINT('retained_warranty_fk_cond_reglement');
5861 $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $object->retained_warranty_fk_cond_reglement;
5862 $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : getDolGlobalString('INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID');
5863 print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
5864 print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
5865 print '</form>';
5866 } else {
5867 $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, (string) $object->retained_warranty_fk_cond_reglement, 'none');
5868 if (!$displayWarranty) {
5869 print img_picto($langs->trans('RetainedWarrantyNeed100Percent'), 'warning', 'class="pictowarning valignmiddle" ');
5870 }
5871 }
5872 print '</td></tr>';
5873
5874 // Retained Warranty payment date limit
5875 print '<tr class="retained-warranty-lines" ><td>';
5876 print '<table id="retained-warranty-date-limit-table" class="nobordernopadding" width="100%"><tr><td>';
5877 print $langs->trans('RetainedWarrantyDateLimit');
5878 print '</td>';
5879 if ($action != 'editretainedwarrantydatelimit' && $user->hasRight('facture', 'creer') && $object->status == Facture::STATUS_DRAFT) {
5880 print '<td align="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editretainedwarrantydatelimit&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('setRetainedWarrantyDateLimit'), 1).'</a></td>';
5881 }
5882
5883 print '</tr></table>';
5884 print '</td><td>';
5885 $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
5886 if ($object->date > $defaultDate) {
5887 $defaultDate = $object->date;
5888 }
5889
5890 if ($action == 'editretainedwarrantydatelimit' && $object->status == Facture::STATUS_DRAFT) {
5891 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
5892 print '<input type="hidden" name="action" value="setretainedwarrantydatelimit">';
5893 print '<input type="hidden" name="token" value="'.newToken().'">';
5894 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
5895 //print '<input name="retained_warranty_date_limit" type="date" step="1" min="'.dol_print_date($object->date, '%Y-%m-%d').'" value="'.dol_print_date($defaultDate, '%Y-%m-%d').'" >'; Time Input not standard
5896 print $form->selectDate($defaultDate, 'retained_warranty_date_limit');
5897 print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
5898 print '</form>';
5899 } else {
5900 print dol_print_date($object->retained_warranty_date_limit, 'day');
5901 }
5902 print '</td></tr>';
5903 }
5904 }
5905
5906
5907 // Other attributes
5908 $cols = 2;
5909 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
5910
5911 print '</table>';
5912
5913 print '</div>';
5914 print '<div class="fichehalfright">';
5915
5916 print '<!-- amounts -->'."\n";
5917 print '<div class="underbanner clearboth"></div>'."\n";
5918
5919 print '<table class="border tableforfield centpercent">';
5920
5921 include DOL_DOCUMENT_ROOT.'/core/tpl/object_currency_amount.tpl.php';
5922
5923 $sign = 1;
5924 if (getDolGlobalString('INVOICE_POSITIVE_CREDIT_NOTE_SCREEN') && $object->type == $object::TYPE_CREDIT_NOTE) {
5925 $sign = -1; // We invert sign for output
5926 }
5927 print '<tr>';
5928 // Amount HT
5929 print '<td class="titlefieldmiddle">' . $langs->trans('AmountHT') . '</td>';
5930 print '<td class="nowraponall amountcard right">' . price($sign * $object->total_ht, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
5931 if (isModEnabled("multicurrency") && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
5932 // Multicurrency Amount HT
5933 print '<td class="nowraponall amountcard right">' . price($sign * $object->multicurrency_total_ht, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
5934 }
5935 print '</tr>';
5936
5937 print '<tr>';
5938 // Amount VAT
5939 print '<td>' . $langs->trans('AmountVAT') . '</td>';
5940 print '<td class="nowraponall amountcard right">' . price($sign * $object->total_tva, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
5941 if (isModEnabled("multicurrency") && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
5942 // Multicurrency Amount VAT
5943 print '<td class="nowraponall amountcard right">' . price($sign * $object->multicurrency_total_tva, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
5944 }
5945 print '</tr>';
5946
5947 // Amount Local Taxes
5948 if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) {
5949 print '<tr>';
5950 print '<td class="titlefieldmiddle">' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
5951 print '<td class="nowraponall amountcard right">' . price($sign * $object->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
5952 if (isModEnabled("multicurrency") && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
5953 $object->multicurrency_total_localtax1 = (float) price2num($object->total_localtax1 * $object->multicurrency_tx, 'MT');
5954
5955 print '<td class="nowraponall amountcard right">' . price($sign * $object->multicurrency_total_localtax1, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
5956 }
5957 print '</tr>';
5958 }
5959
5960 if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) {
5961 print '<tr>';
5962 print '<td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
5963 print '<td class="nowraponall amountcard right">' . price($sign * $object->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
5964 if (isModEnabled("multicurrency") && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
5965 $object->multicurrency_total_localtax2 = (float) price2num($object->total_localtax2 * $object->multicurrency_tx, 'MT');
5966
5967 print '<td class="nowraponall amountcard right">' . price($sign * $object->multicurrency_total_localtax2, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
5968 }
5969 print '</tr>';
5970 }
5971
5972 // Add the revenue stamp
5973 if ($selleruserevenustamp) {
5974 print '<tr><td class="titlefieldmiddle">';
5975 print '<table class="nobordernopadding centpercent"><tr><td>';
5976 print $langs->trans('RevenueStamp');
5977 print '</td>';
5978 if ($action != 'editrevenuestamp' && $object->status == $object::STATUS_DRAFT && $usercancreate) {
5979 print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editrevenuestamp&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetRevenuStamp'), 1).'</a></td>';
5980 }
5981 print '</tr></table>';
5982 print '</td><td class="nowrap amountcard right">';
5983 if ($action == 'editrevenuestamp') {
5984 print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
5985 print '<input type="hidden" name="token" value="'.newToken().'">';
5986 print '<input type="hidden" name="action" value="setrevenuestamp">';
5987 print '<input type="hidden" name="revenuestamp" id="revenuestamp_val" value="'.price2num($object->revenuestamp).'">';
5988 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
5989 print $formother->select_revenue_stamp('', 'revenuestamp_type', $mysoc->country_code);
5990 print ' &rarr; <span id="revenuestamp_span"></span>';
5991 print ' <input type="submit" class="button buttongen button-save small" value="'.$langs->trans('Modify').'">';
5992 print '</form>';
5993 print " <script>
5994 $(document).ready(function(){
5995 js_recalculate_revenuestamp();
5996 $('select[name=revenuestamp_type]').on('change',function(){
5997 js_recalculate_revenuestamp();
5998 });
5999 });
6000 function js_recalculate_revenuestamp(){
6001 var valselected = $('select[name=revenuestamp_type]').val();
6002 console.log('Calculate revenue stamp from '+valselected);
6003 var revenue = 0;
6004 if (valselected.indexOf('%') == -1)
6005 {
6006 revenue = valselected;
6007 }
6008 else
6009 {
6010 var revenue_type = parseFloat(valselected);
6011 var amount_net = ".round($object->total_ht, 2).";
6012 revenue = revenue_type * amount_net / 100;
6013 revenue = revenue.toFixed(2);
6014 }
6015 $('#revenuestamp_val').val(revenue);
6016 $('#revenuestamp_span').html(revenue);
6017 }
6018 </script>";
6019 } else {
6020 print price($object->revenuestamp, 1, '', 1, -1, -1, $conf->currency);
6021 }
6022 print '</td></tr>';
6023 }
6024
6025 print '<tr>';
6026 // Amount TTC
6027 print '<td>' . $langs->trans('AmountTTC') . '</td>';
6028 print '<td class="nowraponall amountcard right">' . price($sign * $object->total_ttc, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
6029 if (isModEnabled("multicurrency") && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
6030 // Multicurrency Amount TTC
6031 print '<td class="nowrap amountcard right">' . price($sign * $object->multicurrency_total_ttc, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
6032 }
6033 print '</tr>';
6034
6035 print '</table>';
6036
6037 $nbrows = 8;
6038 $nbcols = 3;
6039 if (isModEnabled('project')) {
6040 $nbrows++;
6041 }
6042 if (isModEnabled("bank")) {
6043 $nbrows++;
6044 $nbcols++;
6045 }
6046 if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) {
6047 $nbrows++;
6048 }
6049 if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) {
6050 $nbrows++;
6051 }
6052 if ($selleruserevenustamp) {
6053 $nbrows++;
6054 }
6055 if (isModEnabled('multicurrency')) {
6056 $nbrows += 5;
6057 }
6058 if (isModEnabled('incoterm')) {
6059 $nbrows += 1;
6060 }
6061
6062 $total_prev_ht = $total_prev_ttc = 0;
6063 $total_global_ht = $total_global_ttc = 0;
6064
6065 // List of previous situation invoices
6066 if (($object->situation_cycle_ref > 0) && getDolGlobalString('INVOICE_USE_SITUATION')) {
6067 print '<!-- List of situation invoices -->';
6068 print '<div class="div-table-responsive-no-min">';
6069 print '<table class="noborder paymenttable centpercent situationstable">';
6070
6071 print '<tr class="liste_titre">';
6072 print '<td>'.$langs->trans('ListOfSituationInvoices').'</td>';
6073 print '<td></td>';
6074 print '<td class="center">'.$langs->trans('Situation').'</td>';
6075
6076 if (isModEnabled("bank")) {
6077 print '<td class="right"></td>';
6078 }
6079 print '<td class="right">'.$langs->trans('AmountHT').'</td>';
6080 print '<td class="right">'.$langs->trans('AmountTTC').'</td>';
6081 print '<td width="18">&nbsp;</td>';
6082 print '</tr>';
6083
6084 if (count($object->tab_previous_situation_invoice) > 0) {
6085 // List of previous invoices
6086
6087 $current_situation_counter = array();
6088 foreach ($object->tab_previous_situation_invoice as $prev_invoice) {
6089 $tmptotalallpayments = $prev_invoice->getSommePaiement(0);
6090 $tmptotalallpayments += $prev_invoice->getSumDepositsUsed(0);
6091 $tmptotalallpayments += $prev_invoice->getSumCreditNotesUsed(0);
6092
6093 $total_prev_ht += $prev_invoice->total_ht;
6094 $total_prev_ttc += $prev_invoice->total_ttc;
6095
6096 $current_situation_counter[] = (($prev_invoice->type == Facture::TYPE_CREDIT_NOTE) ? -1 : 1) * $prev_invoice->situation_counter;
6097 print '<tr class="oddeven">';
6098 print '<td>'.$prev_invoice->getNomUrl(1).'</td>';
6099 print '<td></td>';
6100 print '<td align="center" >'.(($prev_invoice->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$prev_invoice->situation_counter.'</td>';
6101 if (isModEnabled("bank")) {
6102 print '<td class="right"></td>';
6103 }
6104 print '<td class="right"><span class="amount">'.price($prev_invoice->total_ht).'</span></td>';
6105 print '<td class="right"><span class="amount">'.price($prev_invoice->total_ttc).'</span></td>';
6106 print '<td class="right">'.$prev_invoice->getLibStatut(3, $tmptotalallpayments).'</td>';
6107 print '</tr>';
6108 }
6109 }
6110
6111 $totalallpayments = $object->getSommePaiement(0);
6112 $totalallpayments += $object->getSumCreditNotesUsed(0);
6113 $totalallpayments += $object->getSumDepositsUsed(0);
6114
6115 $total_global_ht += $total_prev_ht;
6116 $total_global_ttc += $total_prev_ttc;
6117 $total_global_ht += $object->total_ht;
6118 $total_global_ttc += $object->total_ttc;
6119
6120 $current_situation_counter[] = (($object->type == Facture::TYPE_CREDIT_NOTE) ? -1 : 1) * $object->situation_counter;
6121
6122 print '<tr class="oddeven">';
6123 print '<td>'.$object->getNomUrl(1).'</td>';
6124 print '<td></td>';
6125 print '<td class="center">'.(($object->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$object->situation_counter.'</td>';
6126 if (isModEnabled("bank")) {
6127 print '<td class="right"></td>';
6128 }
6129 print '<td class="right"><span class="amount">'.price($object->total_ht).'</span></td>';
6130 print '<td class="right"><span class="amount">'.price($object->total_ttc).'</span></td>';
6131 print '<td class="right">'.$object->getLibStatut(3, $totalallpayments).'</td>';
6132 print '</tr>';
6133
6134
6135 print '<tr class="oddeven">';
6136 print '<td colspan="2" class="left"><b>'.$langs->trans('SituationTotalAfterInvoice').'</b></td>';
6137 print '<td>';
6138 $i = 0;
6139 foreach ($current_situation_counter as $sit) {
6140 $curSign = $sit > 0 ? '+' : '-';
6141 $curType = $sit > 0 ? $langs->trans('situationInvoiceShortcode_S') : $langs->trans('situationInvoiceShortcode_AS');
6142 if ($i > 0) {
6143 print ' '.$curSign.' ';
6144 }
6145 print $curType.abs($sit);
6146 $i++;
6147 }
6148 print '</td>';
6149 if (isModEnabled("bank")) {
6150 print '<td></td>';
6151 }
6152 print '<td class="right"><b>'.price($total_global_ht).'</b></td>';
6153 print '<td class="right"><b>'.price($total_global_ttc).'</b></td>';
6154 print '<td width="18">&nbsp;</td>';
6155 print '</tr>';
6156
6157
6158 if (count($object->tab_next_situation_invoice) > 0) {
6159 // List of next invoices
6160 $total_next_ht = $total_next_ttc = 0;
6161
6162 foreach ($object->tab_next_situation_invoice as $next_invoice) {
6163 $next_totalpaid = $next_invoice->getSommePaiement(0);
6164 $next_totalcreditnotes = $next_invoice->getSumCreditNotesUsed(0);
6165 $next_totaldeposits = $next_invoice->getSumDepositsUsed(0);
6166 $total_next_ht += $next_invoice->total_ht;
6167 $total_next_ttc += $next_invoice->total_ttc;
6168
6169 print '<tr class="oddeven">';
6170 print '<td>'.$next_invoice->getNomUrl(1).'</td>';
6171 print '<td></td>';
6172 print '<td class="center">'.(($next_invoice->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$next_invoice->situation_counter.'</td>';
6173 if (isModEnabled("bank")) {
6174 print '<td class="right"></td>';
6175 }
6176 print '<td class="right"><span class="amount">'.price($next_invoice->total_ht).'</span></td>';
6177 print '<td class="right"><span class="amount">'.price($next_invoice->total_ttc).'</span></td>';
6178 print '<td class="right">'.$next_invoice->getLibStatut(3, $next_totalpaid + $next_totalcreditnotes + $next_totaldeposits).'</td>';
6179 print '</tr>';
6180 }
6181
6182 $total_global_ht += $total_next_ht;
6183 $total_global_ttc += $total_next_ttc;
6184
6185 print '<tr class="oddeven">';
6186 print '<td colspan="3" class="right"></td>';
6187 if (isModEnabled("bank")) {
6188 print '<td class="right"></td>';
6189 }
6190 print '<td class="right"><b>'.price($total_global_ht).'</b></td>';
6191 print '<td class="right"><b>'.price($total_global_ttc).'</b></td>';
6192 print '<td width="18">&nbsp;</td>';
6193 print '</tr>';
6194 }
6195
6196 print '</table>';
6197 print '</div>';
6198 }
6199
6200 $sign = 1;
6201 if ($object->type == $object::TYPE_CREDIT_NOTE) {
6202 $sign = -1;
6203 }
6204
6205 // List of payments already done
6206
6207 print '<!-- List of payments already done -->';
6208 print '<div class="div-table-responsive-no-min">';
6209 print '<table class="noborder paymenttable centpercent">';
6210
6211 print '<tr class="liste_titre">';
6212 print '<td class="liste_titre">'.($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
6213 print '<td class="liste_titre"><span class="hideonsmartphone">'.$langs->trans('Date').'</span></td>';
6214 print '<td class="liste_titre"><span class="hideonsmartphone">'.$langs->trans('Type').'</span></td>';
6215 if (isModEnabled("bank")) {
6216 print '<td class="liste_titre"><span class="hideonsmartphone">'.$langs->trans('BankAccount').'</span></td>';
6217 }
6218 print '<td class="liste_titre"></td>';
6219 print '<td class="liste_titre right">'.$langs->trans('Amount').'</td>';
6220 print '</tr>';
6221
6222 // Payments already done (from payment on this invoice)
6223 $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
6224 $sql .= ' c.code as payment_code, c.libelle as payment_label,';
6225 $sql .= ' pf.amount,';
6226 $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal, ba.currency_code as bacurrency_code';
6227 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
6228 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
6229 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
6230 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
6231 $sql .= ' WHERE pf.fk_facture = '.((int) $object->id).' AND pf.fk_paiement = p.rowid';
6232 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
6233 $sql .= ' ORDER BY p.datep, p.tms';
6234
6235 $result = $db->query($sql);
6236 if ($result) {
6237 $num = $db->num_rows($result);
6238 $i = 0;
6239
6240 if ($num > 0) {
6241 while ($i < $num) {
6242 $objp = $db->fetch_object($result);
6243
6244 $paymentstatic->id = $objp->rowid;
6245 $paymentstatic->datepaye = $db->jdate($objp->dp);
6246 $paymentstatic->ref = $objp->ref;
6247 $paymentstatic->num_payment = $objp->num_payment;
6248 $paymentstatic->paiementcode = $objp->payment_code;
6249
6250 print '<tr class="oddeven">';
6251 print '<td class="nowraponall">';
6252 print $paymentstatic->getNomUrl(1);
6253 print '</td>';
6254 print '<td>';
6255 $dateofpayment = $db->jdate($objp->dp);
6256 $tmparray = dol_getdate($dateofpayment);
6257 if ($tmparray['seconds'] == 0 && $tmparray['minutes'] == 0 && ($tmparray['hours'] == 0 || $tmparray['hours'] == 12)) { // We set hours to 0:00 or 12:00 because we don't know it
6258 print dol_print_date($dateofpayment, 'day');
6259 } else { // Hours was set to real date of payment (special case for POS for example)
6260 print dol_print_date($dateofpayment, 'dayhour', 'tzuser');
6261 }
6262 print '</td>';
6263
6264 $label = ($langs->trans("PaymentType".$objp->payment_code) != "PaymentType".$objp->payment_code) ? $langs->trans("PaymentType".$objp->payment_code) : $objp->payment_label;
6265 print '<td class="tdoverflowmax80" title="'.dol_escape_htmltag($label.' '.$objp->num_payment).'">'.dol_escape_htmltag($label.' '.$objp->num_payment).'</td>';
6266 if (isModEnabled("bank")) {
6267 $bankaccountstatic->id = $objp->baid;
6268 $bankaccountstatic->ref = $objp->baref;
6269 $bankaccountstatic->label = $objp->baref;
6270 $bankaccountstatic->number = $objp->banumber;
6271 $bankaccountstatic->currency_code = $objp->bacurrency_code;
6272
6273 if (isModEnabled('accounting')) {
6274 $bankaccountstatic->account_number = $objp->account_number;
6275
6276 $accountingjournal = new AccountingJournal($db);
6277 $accountingjournal->fetch($objp->fk_accountancy_journal);
6278 $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
6279 }
6280
6281 print '<td class="nowraponall">';
6282 if ($bankaccountstatic->id) {
6283 print $bankaccountstatic->getNomUrl(1, 'transactions');
6284 }
6285 print '</td>';
6286 }
6287
6288 // Delete
6289 print '<td class="center">';
6290 $paiement = new Paiement($db);
6291 $paiement->fetch($objp->rowid);
6292 if ($object->status == Facture::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0 && !$paiement->isReconciled()) {
6293 print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepayment&token='.newToken().'&paiement_id='.$objp->rowid.'">';
6294 print img_delete();
6295 print '</a>';
6296 }
6297 print '</td>';
6298
6299 // Amount
6300 print '<td class="right"><span class="amount">'.price($sign * $objp->amount).'</span></td>';
6301
6302 print '</tr>';
6303 $i++;
6304 }
6305 }
6306
6307 $db->free($result);
6308 } else {
6310 }
6311
6312 if ($object->type != Facture::TYPE_CREDIT_NOTE) {
6313 // Total already paid
6314 print '<tr>';
6315 print '<td colspan="'.($nbcols + 1).'" class="right">';
6316 print '<span class="opacitymedium">';
6317 if ($object->type != Facture::TYPE_DEPOSIT) {
6318 print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
6319 } else {
6320 print $langs->trans('AlreadyPaid');
6321 }
6322 print '</span></td>';
6323 //print '<td></td>';
6324 print '<td class="right'.(($totalpaid > 0) ? ' amountalreadypaid' : '').'">'.price($totalpaid).'</td>';
6325 print '</tr>';
6326
6327 $resteapayeraffiche = $resteapayer;
6328 $cssforamountpaymentcomplete = 'amountpaymentcomplete';
6329 $cssforamountpaymentcompletenoresize = 'amountpaymentcompletenoresize';
6330
6331 // Loop on each credit note or deposit amount applied
6332 $creditnoteamount = 0;
6333 $depositamount = 0;
6334 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
6335 $sql .= " re.description, re.fk_facture_source";
6336 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
6337 $sql .= " WHERE fk_facture = ".((int) $object->id);
6338 $resql = $db->query($sql);
6339 if ($resql) {
6340 $num = $db->num_rows($resql);
6341 $i = 0;
6342 $invoice = new Facture($db);
6343 while ($i < $num) {
6344 $obj = $db->fetch_object($resql);
6345 $invoice->fetch($obj->fk_facture_source);
6346 print '<tr>';
6347 print '<td colspan="'.$nbcols.'" class="right">';
6348 print '<span class="opacitymedium">';
6349 if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
6350 print $langs->trans("CreditNote").' ';
6351 }
6352 if ($invoice->type == Facture::TYPE_DEPOSIT) {
6353 print $langs->trans("Deposit").' ';
6354 }
6355 print $invoice->getNomUrl(0);
6356 print '</span>';
6357 print '</td>';
6358 // Delete discount
6359 print '<td class="right">';
6360 print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&token='.newToken().'&discountid='.$obj->rowid.'">';
6361 print img_picto($langs->transnoentitiesnoconv("RemoveDiscount"), 'unlink');
6362 print '</a>';
6363 print '</td>';
6364 // Amount
6365 print '<td class="right"><span class="amount">'.price($obj->amount_ttc).'</span></td>';
6366 print '</tr>';
6367 $i++;
6368 if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
6369 $creditnoteamount += $obj->amount_ttc;
6370 }
6371 if ($invoice->type == Facture::TYPE_DEPOSIT) {
6372 $depositamount += $obj->amount_ttc;
6373 }
6374 }
6375 } else {
6377 }
6378
6379 // Partially paid 'discount'
6380 if (($object->status == Facture::STATUS_CLOSED || $object->status == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
6381 print '<tr>';
6382 print '<td colspan="'.$nbcols.'" class="nowrap right">';
6383 print '<span class="opacitymedium">';
6384 print $form->textwithpicto($langs->trans("Discount"), $langs->trans("HelpEscompte"), - 1);
6385 print '</span>';
6386 print '</td>';
6387 print '<td></td>';
6388 print '<td class="right"><span class="amount">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')).'</span></td>';
6389 print '</tr>';
6390 $resteapayeraffiche = 0;
6391 $cssforamountpaymentcomplete = 'amountpaymentneutral';
6392 $cssforamountpaymentcompletenoresize = 'amountpaymentneutralnoresize';
6393 }
6394 // Partially paid or abandoned 'badcustomer'
6395 if (($object->status == Facture::STATUS_CLOSED || $object->status == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') {
6396 print '<tr>';
6397 print '<td colspan="'.($nbcols + 1).'" class="nowrap right">';
6398 print '<span class="opacitymedium">';
6399 print $form->textwithpicto($langs->trans("Abandoned"), $langs->trans("HelpAbandonBadCustomer"), - 1);
6400 print '</span>';
6401 print '</td>';
6402 //print '<td></td>';
6403 print '<td class="right">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')).'</td>';
6404 print '</tr>';
6405 // $resteapayeraffiche=0;
6406 $cssforamountpaymentcomplete = 'amountpaymentneutral';
6407 $cssforamountpaymentcompletenoresize = 'amountpaymentneutralnoresize';
6408 }
6409 // Partially paid or abandoned 'product_returned'
6410 if (($object->status == Facture::STATUS_CLOSED || $object->status == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
6411 print '<tr>';
6412 print '<td colspan="'.($nbcols + 1).'" class="nowrap right">';
6413 print '<span class="opacitymedium">';
6414 print $form->textwithpicto($langs->trans("ProductReturned"), $langs->trans("HelpAbandonProductReturned"), - 1);
6415 print '</span>';
6416 print '</td>';
6417 //print '<td></td>';
6418 print '<td class="right"><span class="amount">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')).'</span></td>';
6419 print '</tr>';
6420 $resteapayeraffiche = 0;
6421 $cssforamountpaymentcomplete = 'amountpaymentneutral';
6422 $cssforamountpaymentcompletenoresize = 'amountpaymentneutralnoresize';
6423 }
6424 // Partially paid or abandoned 'abandoned'
6425 if (($object->status == Facture::STATUS_CLOSED || $object->status == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') {
6426 print '<tr>';
6427 print '<td colspan="'.($nbcols + 1).'" class="nowrap right">';
6428 $text = $langs->trans("HelpAbandonOther");
6429 if ($object->close_note) {
6430 $text .= '<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
6431 }
6432 print '<span class="opacitymedium">';
6433 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
6434 print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1);
6435 print '</span>';
6436 print '</td>';
6437 //print '<td></td>';
6438 print '<td class="right"><span class="amount">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')).'</span></td>';
6439 print '</tr>';
6440 $resteapayeraffiche = 0;
6441 $cssforamountpaymentcomplete = 'amountpaymentneutral';
6442 $cssforamountpaymentcompletenoresize = 'amountpaymentneutralnoresize';
6443 }
6444
6445 // Billed
6446 print '<tr>';
6447 print '<td colspan="'.($nbcols + 1).'" class="right">';
6448 print '<span class="opacitymedium">';
6449 print $langs->trans("Billed");
6450 print '</td>';
6451 //print '<td></td>';
6452 print '<td class="right">'.price($object->total_ttc).'</td>';
6453 print '</tr>';
6454
6455 // Remainder to pay
6456 print '<tr>';
6457 print '<td colspan="'.($nbcols + 1).'" class="right">';
6458 print '<span class="opacitymedium">';
6459 print $langs->trans('RemainderToPay');
6460 if ($resteapayeraffiche < 0) {
6461 print ' ('.$langs->trans('NegativeIfExcessReceived').')';
6462 }
6463 print '</span>';
6464 print '</td>';
6465 //print '<td></td>';
6466 print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td>';
6467 print '</tr>';
6468
6469 // Remainder to pay Multicurrency
6470 if (isModEnabled('multicurrency') && $object->multicurrency_code && ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1)) {
6471 print '<tr>';
6472 print '<td colspan="'.($nbcols + 1).'" class="right">';
6473 print '<span class="opacitymedium">';
6474 print $langs->trans('RemainderToPayMulticurrency');
6475 if ($resteapayeraffiche < 0) {
6476 print ' ('.$langs->trans('NegativeIfExcessReceived').')';
6477 }
6478 print '</span>';
6479 print '</td>';
6480 //print '<td></td>';
6481 print '<td class="right'.($resteapayeraffiche ? ' amountremaintopaynoresize' : (' '.$cssforamountpaymentcompletenoresize)).'">';
6482 //print (empty($object->multicurrency_code) ? $conf->currency : $object->multicurrency_code).' ';
6483 print price(price2num($object->multicurrency_tx * $resteapayeraffiche, 'MT'), 1, $langs, 1, -1, -1, (empty($object->multicurrency_code) ? $conf->currency : $object->multicurrency_code)).'</td>';
6484 print '</tr>';
6485 }
6486
6487 // Retained warranty : usually use on construction industry
6488 if (!empty($object->situation_final) && !empty($object->retained_warranty) && $displayWarranty) {
6489 // Billed - retained warranty
6490 if ($object->isSituationInvoice()) {
6491 $retainedWarranty = $total_global_ttc * $object->retained_warranty / 100;
6492 } else {
6493 // Because one day retained warranty could be used on standard invoices
6494 $retainedWarranty = $object->total_ttc * $object->retained_warranty / 100;
6495 }
6496
6497 $billedWithRetainedWarranty = $object->total_ttc - $retainedWarranty;
6498
6499 print '<tr>';
6500 print '<td colspan="'.($nbcols + 1).'" class="right">'.$langs->trans("ToPayOn", dol_print_date($object->date_lim_reglement, 'day')).' :</td>';
6501 //print '<td></td>';
6502 print '<td class="right">'.price($billedWithRetainedWarranty).'</td>';
6503 print '</tr>';
6504
6505 // retained warranty
6506 print '<tr>';
6507 print '<td colspan="'.($nbcols + 1).'" class="right">';
6508 print $langs->trans("RetainedWarranty").' ('.$object->retained_warranty.'%)';
6509 print !empty($object->retained_warranty_date_limit) ? ' '.$langs->trans("ToPayOn", dol_print_date($object->retained_warranty_date_limit, 'day')) : '';
6510 print '</td>';
6511 //print '<td></td>';
6512 print '<td class="right">'.price($retainedWarranty).'</td>';
6513 print '</tr>';
6514 }
6515 } else { // Credit note
6516 $resteapayeraffiche = $resteapayer;
6517 $cssforamountpaymentcomplete = 'amountpaymentneutral';
6518 $cssforamountpaymentcompletenoresize = 'amountpaymentneutralnoresize';
6519
6520 // Total already paid back
6521 print '<tr>';
6522 print '<td colspan="'.($nbcols + 1).'" class="right">';
6523 print '<span class="opacitymedium">'.$langs->trans('AlreadyPaidBack').'</span>';
6524 print '</td>';
6525 //print '<td></td>';
6526 print '<td class="right"><span class="amount">'.price($sign * $totalpaid).'</span></td>';
6527 print '</tr>';
6528
6529 // Billed
6530 print '<tr>';
6531 print '<td colspan="'.($nbcols + 1).'" class="right"><span class="opacitymedium">'.$langs->trans("Billed").'</span></td>';
6532 //print '<td></td>';
6533 print '<td class="right">'.price($sign * $object->total_ttc).'</td>';
6534 print '</tr>';
6535
6536 // Remainder to pay back
6537 print '<tr><td colspan="'.($nbcols + 1).'" class="right">';
6538 print '<span class="opacitymedium">'.$langs->trans('RemainderToPayBack');
6539 if ($resteapayeraffiche > 0) {
6540 print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
6541 }
6542 print '</span></td>';
6543 //print '<td class="nowrap"></td>';
6544 print '<td class="right'.($resteapayeraffiche ? ' amountremaintopayback' : (' '.$cssforamountpaymentcomplete)).'">'.price($sign * $resteapayeraffiche);
6545 // TODO If credit not was converted into discount, we should show a tooltip to explain that remain to pay
6546 // is zero because already converted into discount for a future use, so no need to refund.
6547 print '</td>';
6548 print '</tr>';
6549
6550 // Remainder to pay back Multicurrency
6551 if (isModEnabled('multicurrency') && (($object->multicurrency_code && $object->multicurrency_code != $conf->currency) || $object->multicurrency_tx != 1)) {
6552 print '<tr>';
6553 print '<td colspan="'.($nbcols + 1).'" class="right">';
6554 print '<span class="opacitymedium">'.$langs->trans('RemainderToPayBackMulticurrency');
6555 if ($resteapayeraffiche > 0) {
6556 print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
6557 }
6558 print '</span>';
6559 print '</td>';
6560 //print '<td></td>';
6561 print '<td class="right'.($resteapayeraffiche ? ' amountremaintopaybacknoresize' : (' '.$cssforamountpaymentcompletenoresize)).'">'.price(price2num($sign * $object->multicurrency_tx * $resteapayeraffiche, 'MT'), 1, $langs, 1, -1, -1, (empty($object->multicurrency_code) ? $conf->currency : $object->multicurrency_code)).'</td>';
6562 print '</tr>';
6563 }
6564
6565 // Sold credit note
6566 // print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('TotalTTC').' :</td>';
6567 // print '<td class="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
6568 // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
6569 }
6570
6571 print '</table>';
6572 print '</div>';
6573
6574 // Margin Infos
6575 if (isModEnabled('margin')) {
6576 $formmargin->displayMarginInfos($object);
6577 }
6578
6579 print '</div>';
6580 print '</div>';
6581
6582 print '<div class="clearboth"></div><br>';
6583
6584 if (getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB')) {
6585 $blocname = 'contacts';
6586 $title = $langs->trans('ContactsAddresses');
6587 include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
6588 }
6589
6590 if (getDolGlobalString('MAIN_DISABLE_NOTES_TAB')) {
6591 $blocname = 'notes';
6592 $title = $langs->trans('Notes');
6593 include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
6594 }
6595
6596 // Get object lines
6597 $result = $object->getLinesArray();
6598
6599 // Add products/services form
6600 //$forceall = 1;
6601 global $inputalsopricewithtax;
6602 $inputalsopricewithtax = 1;
6603
6604 // Show global modifiers for situation invoices
6605 if (getDolGlobalString('INVOICE_USE_SITUATION')) {
6606 if ($object->situation_cycle_ref && $object->status == 0) {
6607 print '<!-- Area to change globally the situation percent -->'."\n";
6608 print '<div class="div-table-responsive-no-min">';
6609
6610 print '<form name="updatealllines" id="updatealllines" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'#updatealllines" method="POST">';
6611 print '<input type="hidden" name="token" value="'.newToken().'" />';
6612 print '<input type="hidden" name="action" value="updatealllines" />';
6613 print '<input type="hidden" name="id" value="'.$object->id.'" />';
6614 print '<input type="hidden" name="page_y" value="" />';
6615 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
6616
6617 print '<table id="tablelines_all_progress" class="noborder noshadow centpercent">';
6618
6619 print '<tr class="liste_titre nodrag nodrop">';
6620
6621 // Adds a line numbering column
6622 if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER')) {
6623 print '<td align="center" width="5">&nbsp;</td>';
6624 }
6625 print '<td class="minwidth500imp">'.$langs->trans('ModifyAllLines').'</td>';
6626 print '<td class="right">'.$langs->trans('CumulativeProgression').'</td>';
6627 print '<td>&nbsp;</td>';
6628 print "</tr>\n";
6629
6630 print '<tr class="nodrag nodrop">';
6631 // Adds a line numbering column
6632 if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER')) {
6633 print '<td align="center" width="5">&nbsp;</td>';
6634 }
6635 print '<td>&nbsp;</td>';
6636 print '<td class="nowrap right"><input type="text" size="1" value="" name="all_progress">%</td>';
6637 print '<td class="right"><input type="submit" class="button reposition small" name="all_percent" value="'.$langs->trans("Modify").'" /></td>';
6638 print '</tr>';
6639
6640 print '</table>';
6641
6642 print '</form>';
6643
6644 print '</div>';
6645 }
6646 }
6647
6648 print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">
6649 <input type="hidden" name="token" value="' . newToken().'">
6650 <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
6651 <input type="hidden" name="mode" value="">
6652 <input type="hidden" name="page_y" value="">
6653 <input type="hidden" name="id" value="' . $object->id.'">
6654 <input type="hidden" name="backtopage" value="'.$backtopage.'">
6655 ';
6656
6657 if (!empty($conf->use_javascript_ajax) && $object->status == 0) {
6658 if (isModEnabled('subtotals')) {
6659 include DOL_DOCUMENT_ROOT.'/core/tpl/subtotal_ajaxrow.tpl.php';
6660 } else {
6661 include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
6662 }
6663 }
6664
6665 print '<div class="div-table-responsive-no-min">';
6666 print '<table id="tablelines" class="noborder noshadow centpercent nomarginbottom">';
6667
6668 // Show object lines
6669 if (!empty($object->lines)) {
6670 $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
6671 }
6672
6673 // Form to add new line
6674 if ($object->status == 0 && $usercancreate && $action != 'valid') {
6675 if ($action != 'editline' && $action != 'selectlines') {
6676 // Add free products/services
6677
6678 $parameters = array();
6679 $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
6680 if ($reshook < 0) {
6681 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
6682 }
6683 if (empty($reshook)) {
6684 $object->formAddObjectLine(1, $mysoc, $soc);
6685 }
6686 } else {
6687 $parameters = array();
6688 $reshook = $hookmanager->executeHooks('formEditObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
6689 }
6690 }
6691
6692 print "</table>\n";
6693 print "</div>";
6694
6695 print "</form>\n";
6696 }
6697 print dol_get_fiche_end();
6698
6699
6700 // Actions buttons
6701
6702 if ($action != 'prerelance' && $action != 'presend' && $action != 'valid' && $action != 'editline') {
6703 print '<div class="tabsAction">';
6704
6705 $parameters = array();
6706 $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
6707 if (empty($reshook)) {
6708 $params = array(
6709 'attr' => array(
6710 'class' => 'classfortooltip',
6711 'title' => ''
6712 )
6713 );
6714 // Edit a validated invoice without any payment and not transferred to accounting
6715 if ($object->status == Facture::STATUS_VALIDATED && !getDolGlobalString('INVOICE_CAN_NEVER_BE_EDITED')) {
6716 // We check if lines of invoice are not already transferred into accountancy
6717 $ventilExportCompta = $object->getVentilExportCompta();
6718
6719 if ($ventilExportCompta == 0) {
6720 if (getDolGlobalString('INVOICE_CAN_BE_EDITED_EVEN_IF_PAYMENT_DONE') || ($resteapayer == price2num($object->total_ttc, 'MT', 1) && empty($object->paye))) {
6721 if (!$objectidnext && $object->is_last_in_cycle()) {
6722 if ($usercanunvalidate) {
6723 unset($params['attr']['title']);
6724 print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=modif&token=' . newToken(), '', true, $params);
6725 } else {
6726 $params['attr']['title'] = $langs->trans('NotEnoughPermissions');
6727 print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=modif&token=' . newToken(), '', false, $params);
6728 }
6729 } elseif (!$object->is_last_in_cycle()) {
6730 $params['attr']['title'] = $langs->trans('NotLastInCycle');
6731 print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
6732 } else {
6733 $params['attr']['title'] = $langs->trans('DisabledBecauseReplacedInvoice');
6734 print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
6735 }
6736 }
6737 } else {
6738 $params['attr']['title'] = $langs->trans('DisabledBecauseDispatchedInBookkeeping');
6739 print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
6740 }
6741 }
6742
6743 $discount = new DiscountAbsolute($db);
6744 $result = $discount->fetch(0, $object->id);
6745
6746 // Reopen an invoice
6748 || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id))
6749 || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id))
6750 || ($object->type == Facture::TYPE_SITUATION && empty($discount->id)))
6751 && ($object->status == Facture::STATUS_CLOSED || $object->status == Facture::STATUS_ABANDONED || ($object->status == 1 && $object->paye == 1)) // Condition ($object->status == 1 && $object->paye == 1) should not happened but can be found due to corrupted data
6752 && ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $usercancreate) || $usercanreopen)) { // A paid invoice (partially or completely)
6753 if ($object->close_code != 'replaced' || (!$objectidnext)) { // Not replaced by another invoice or replaced but the replacement invoice has been deleted
6754 unset($params['attr']['title']);
6755 print dolGetButtonAction($langs->trans('ReOpen'), '', 'default', $_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=reopen&token='.newToken(), '', true, $params);
6756 } else {
6757 $params['attr']['title'] = $langs->trans("DisabledBecauseReplacedInvoice");
6758 print dolGetButtonAction($langs->trans('ReOpen'), '', 'default', '#', '', false, $params);
6759 }
6760 }
6761
6762 // Create contract
6763 if (getDolGlobalString('CONTRACT_CREATE_FROM_INVOICE')) {
6764 if (isModEnabled('contract') && $object->status == Facture::STATUS_VALIDATED) {
6765 $langs->load("contracts");
6766
6767 if ($usercancreatecontract) {
6768 print '<a class="butAction" href="' . DOL_URL_ROOT . '/contrat/card.php?action=create&origin=' . $object->element . '&originid=' . $object->id . '&socid=' . $object->socid . '">' . $langs->trans('AddContract') . '</a>';
6769 }
6770 }
6771 }
6772
6773 // Subtotal
6774 if ($object->status == Facture::STATUS_DRAFT && isModEnabled('subtotals')
6775 && (getDolGlobalInt('SUBTOTAL_TITLE_'.strtoupper($object->element)) || getDolGlobalInt('SUBTOTAL_'.strtoupper($object->element)))) {
6776 $langs->load("subtotals");
6777
6778 $url_button = array();
6779
6780 $url_button[] = array(
6781 'lang' => 'subtotals',
6782 'enabled' => (isModEnabled('invoice') && $object->status == Facture::STATUS_DRAFT && getDolGlobalInt('SUBTOTAL_TITLE_'.strtoupper($object->element))),
6783 'perm' => (bool) $usercancreate,
6784 'label' => $langs->trans('AddTitleLine'),
6785 'url' => '/compta/facture/card.php?facid='.$object->id.'&action=add_title_line&token='.newToken()
6786 );
6787
6788 $url_button[] = array(
6789 'lang' => 'subtotals',
6790 'enabled' => (isModEnabled('invoice') && $object->status == Facture::STATUS_DRAFT && getDolGlobalInt('SUBTOTAL_'.strtoupper($object->element))),
6791 'perm' => (bool) $usercancreate,
6792 'label' => $langs->trans('AddSubtotalLine'),
6793 'url' => '/compta/facture/card.php?facid='.$object->id.'&action=add_subtotal_line&token='.newToken()
6794 );
6795 print dolGetButtonAction('', $langs->trans('SubTotal'), 'default', $url_button, '', true);
6796 }
6797
6798 // Validate
6799 if ($object->status == Facture::STATUS_DRAFT && count($object->lines) > 0
6800 && ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) && (getDolGlobalString('FACTURE_ENABLE_NEGATIVE') || $object->total_ttc >= 0))
6801 || ($object->type == Facture::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) {
6802 if ($usercanvalidate) {
6803 unset($params['attr']['title']);
6804 print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=valid&token='.newToken(), '', true, $params);
6805 }
6806 }
6807
6808 // Send by mail
6809 if (empty($user->socid)) {
6810 if (($object->status == Facture::STATUS_VALIDATED || $object->status == Facture::STATUS_CLOSED) || getDolGlobalString('FACTURE_SENDBYEMAIL_FOR_ALL_STATUS')) {
6811 if ($objectidnext) {
6812 $params['attr']['title'] = $langs->trans("DisabledBecauseReplacedInvoice");
6813 print dolGetButtonAction('', $langs->trans('SendMail'), 'email', '#', '', false, $params);
6814 } else {
6815 if ($usercansend) {
6816 unset($params['attr']['title']);
6817 print dolGetButtonAction('', $langs->trans('SendMail'), 'email', $_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=presend&mode=init#formmailbeforetitle', '', true, $params);
6818 } else {
6819 unset($params['attr']['title']);
6820 print dolGetButtonAction('', $langs->trans('SendMail'), 'email', '#', '', false, $params);
6821 }
6822 }
6823 }
6824 }
6825
6826 // Request a direct debit order
6827 if ($object->status > Facture::STATUS_DRAFT && $object->paye == 0) {
6828 if ($resteapayer > 0) {
6829 if ($usercancreatewithdrarequest) {
6830 if (!$objectidnext && $object->close_code != 'replaced') { // Not replaced by another invoice
6831 print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$object->id.'" title="'.dol_escape_htmltag($langs->trans("MakeWithdrawRequest")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
6832 } else {
6833 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('MakeWithdrawRequest').'</span>';
6834 }
6835 } else {
6836 //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
6837 }
6838 } else {
6839 //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("AmountMustBePositive")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
6840 }
6841 }
6842
6843 // POS Ticket
6844 if (isModEnabled('takepos') && $object->module_source == 'takepos') {
6845 $langs->load("cashdesk");
6846 $receipt_url = DOL_URL_ROOT."/takepos/receipt.php";
6847 print '<a target="_blank" rel="noopener noreferrer" class="butAction" href="'.$receipt_url.'?facid='.((int) $object->id).'">'.$langs->trans('POSTicket').'</a>';
6848 }
6849
6850 // Create payment
6851 if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->status == 1 && $object->paye == 0 && $usercanissuepayment) {
6852 if ($objectidnext) {
6853 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('DoPayment').'</span>';
6854 } else {
6855 if ($object->type == Facture::TYPE_DEPOSIT && $resteapayer == 0) {
6856 // For down payment, we refuse to receive more than amount to pay.
6857 $params['attr']['title'] = $langs->trans('DisabledBecauseRemainderToPayIsZero');
6858 print dolGetButtonAction($langs->trans('DoPayment'), '', 'default', '#', '', false, $params);
6859 } else {
6860 // Sometimes we can receive more, so we accept to enter more and will offer a button to convert into discount (but it is not a credit note, just a prepayment done)
6861 //print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/paiement.php?facid='.$object->id.'&action=create&accountid='.$object->fk_account.'">'.$langs->trans('DoPayment').'</a>';
6862 unset($params['attr']['title']);
6863 print dolGetButtonAction($langs->trans('DoPayment'), '', 'default', DOL_URL_ROOT.'/compta/paiement.php?facid='.$object->id.'&action=create'.($object->fk_account > 0 ? '&accountid='.$object->fk_account : ''), '', true, $params);
6864 }
6865 }
6866 }
6867
6868 $sumofpayment = $totalpaid;
6869 $sumofpaymentall = $totalpaid + $totalcreditnotes + $totaldeposits;
6870
6871 // Reverse back money or convert to reduction
6873 // For credit note only
6874 if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->status == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment) {
6875 if ($resteapayer == 0) {
6876 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span>';
6877 } else {
6878 print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/paiement.php?facid='.$object->id.'&action=create&accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a>';
6879 }
6880 }
6881
6882 // For standard invoice with excess received
6883 if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->status == Facture::STATUS_VALIDATED && empty($object->paye) && $resteapayer < 0 && $usercancreate && empty($discount->id)) {
6884 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=converttoreduc&token='.newToken().'">'.$langs->trans('ConvertExcessReceivedToReduc').'</a>';
6885 }
6886 // For credit note
6887 if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->status == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercancreate
6888 && (getDolGlobalString('INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED') || $sumofpayment == 0) && $object->total_ht < 0
6889 ) {
6890 print '<a class="butAction classfortooltip'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=converttoreduc&token='.newToken().'" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReduc2")).'">'.$langs->trans('ConvertToReduc').'</a>';
6891 }
6892
6893 // For down payment invoice (deposit)
6894 if ($object->type == Facture::TYPE_DEPOSIT && $usercancreate && $object->status > Facture::STATUS_DRAFT && empty($discount->id)) {
6895 // We can close a down payment only if paid amount is same than amount of down payment (by definition). We can bypass this if hidden and unstable option DEPOSIT_CAN_BE_CONVERTED_AS_AVAILABLE_CREDIT_EVEN_IF_NOT_YET_PAID is set.
6896 if (price2num($object->total_ttc, 'MT') <= price2num($sumofpaymentall, 'MT') || getDolGlobalInt('DEPOSIT_CAN_BE_CONVERTED_AS_AVAILABLE_CREDIT_EVEN_IF_NOT_YET_PAID') || ($object->type == Facture::STATUS_ABANDONED && in_array($object->close_code, array('bankcharge', 'discount_vat', 'other')))) {
6897 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=converttoreduc&token='.newToken().'">'.$langs->trans('ConvertToReduc').'</a>';
6898 } else {
6899 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("AmountPaidMustMatchAmountOfDownPayment").'">'.$langs->trans('ConvertToReduc').'</span>';
6900 }
6901 }
6902 }
6903
6904 // Classify paid
6905 if ($object->status == Facture::STATUS_VALIDATED && $usercanissuepayment && (
6906 ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT && ($resteapayer <= 0 || (getDolGlobalString('INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') && $object->total_ttc == $resteapayer))) ||
6907 ($object->type == Facture::TYPE_CREDIT_NOTE && $resteapayer >= 0) ||
6908 ($object->type == Facture::TYPE_DEPOSIT && $object->total_ttc > 0)
6909 )
6910 ) {
6911 if ($object->type == Facture::TYPE_DEPOSIT && price2num($object->total_ttc, 'MT') != price2num($sumofpaymentall, 'MT')) {
6912 // We can close a down payment only if paid amount is same than amount of down payment (by definition)
6913 $params['attr']['title'] = $langs->trans('AmountPaidMustMatchAmountOfDownPayment');
6914 print dolGetButtonAction($langs->trans('ClassifyPaid'), '', 'default', '#', '', false, $params);
6915 } else {
6916 unset($params['attr']['title']);
6917 print dolGetButtonAction($langs->trans('ClassifyPaid'), '', 'default', $_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=paid&token='.newToken(), '', true, $params);
6918 }
6919 }
6920
6921 // Classify 'closed not completely paid' (possible if validated and not yet set as paid completely)
6922 if ($object->status == Facture::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && (!getDolGlobalString('INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') || $resteapayer != $object->total_ttc) && $usercanissuepayment) {
6923 if ($totalpaid > 0 || $totalcreditnotes > 0) {
6924 // If one payment or one credit note was linked to this invoice
6925 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=paid&token='.newToken().'">'.$langs->trans('ClassifyPaidPartially').'</a>';
6926 } else {
6927 if (!getDolGlobalString('INVOICE_CAN_NEVER_BE_CANCELED')) {
6928 if ($objectidnext) {
6929 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ClassifyCanceled').'</span>';
6930 } else {
6931 print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=canceled&token='.newToken().'">'.$langs->trans('ClassifyCanceled').'</a>';
6932 }
6933 }
6934 }
6935 }
6936
6937 // Create next situation invoice (a credit note of the cycle is not a situation to continue from)
6938 if ($usercancreate && $object->isSituationInvoice() && $object->type == Facture::TYPE_SITUATION && ($object->status == 1 || $object->status == 2)) {
6939 if ($object->is_last_in_cycle() && $object->situation_final != 1) {
6940 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=create&type=5&origin=facture&originid='.$object->id.'&socid='.$object->socid.'" >'.$langs->trans('CreateNextSituationInvoice').'</a>';
6941 } elseif (!$object->is_last_in_cycle()) {
6942 print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInCycle").'">'.$langs->trans('CreateNextSituationInvoice').'</a>';
6943 } else {
6944 print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseFinal").'">'.$langs->trans('CreateNextSituationInvoice').'</a>';
6945 }
6946 }
6947
6948 // Create a credit note
6949 if (($object->type == Facture::TYPE_STANDARD || ($object->type == Facture::TYPE_DEPOSIT && !getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) || $object->type == Facture::TYPE_PROFORMA) && $object->status > 0 && $usercancreate) {
6950 if (!$objectidnext) {
6951 print '<!-- button create credit note -->';
6952 if ($object->module_source == 'takepos') {
6953 print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseInvoiceGeneratedBy", $langs->transnoentitiesnoconv('TakePOS')).'">'.$langs->trans("CreateCreditNote").'</a>';
6954 } else {
6955 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&fac_avoir='.$object->id.'&action=create&type=2'.($object->fk_project > 0 ? '&projectid='.$object->fk_project : '').($object->entity > 0 ? '&originentity='.$object->entity : '').'">'.$langs->trans("CreateCreditNote").'</a>';
6956 }
6957 }
6958 }
6959
6960 // For situation invoice, create credit note
6961 if ($object->status > Facture::STATUS_DRAFT
6962 && $object->isSituationInvoice()
6963 && $usercancreate
6964 && !$objectidnext
6965 && $object->is_last_in_cycle()
6966 && getDolGlobalInt('INVOICE_USE_SITUATION_CREDIT_NOTE')
6967 ) {
6968 if ($usercanunvalidate) {
6969 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&fac_avoir='.$object->id.'&invoiceAvoirWithLines=1&action=create&type=2'.($object->fk_project > 0 ? '&projectid='.$object->fk_project : '').'">'.$langs->trans("CreateCreditNote").'</a>';
6970 } else {
6971 print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateCreditNote").'</span>';
6972 }
6973 }
6974
6975 // Clone as predefined / Create template
6976 if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->status == 0 && $usercancreate) {
6977 if (!$objectidnext && count($object->lines) > 0) {
6978 unset($params['attr']['title']);
6979 print dolGetButtonAction($langs->trans('ChangeIntoRepeatableInvoice'), '', 'default', DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$object->id.'&action=create', '', true, $params);
6980 }
6981 }
6982
6983 // Clone
6984 if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $usercancreate) {
6985 unset($params['attr']['title']);
6986 print dolGetButtonAction($langs->trans('ToClone'), '', 'clone', $_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=clone&object=invoice&token='.newToken(), '', true, $params);
6987 }
6988
6989 // Remove situation from cycle
6990 if (in_array($object->status, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
6991 && $object->isSituationInvoice()
6992 && $usercancreate
6993 && !$objectidnext
6994 && $object->situation_counter > 1
6995 && $object->is_last_in_cycle()
6996 && $usercanunvalidate
6997 ) {
6998 if (price2num($object->total_ttc - $totalcreditnotes, 'MT') == 0) {
6999 print '<a id="butSituationOut" class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=situationout&token='.newToken().'">'.$langs->trans("RemoveSituationFromCycle").'</a>';
7000 } else {
7001 print '<a id="butSituationOutRefused" class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotEnouthCreditNote").'" >'.$langs->trans("RemoveSituationFromCycle").'</a>';
7002 }
7003 }
7004
7005 // Delete
7006 $isErasable = $object->is_erasable();
7007
7008 $htmltooltip = '';
7009 if ($isErasable == -6) {
7010 $htmltooltip = $langs->trans('DisabledBecauseAlreadySentByEmail');
7011 } elseif ($isErasable == -5) {
7012 $htmltooltip = $langs->trans('DisabledBecauseAlreadyPrintedOnce');
7013 } elseif ($isErasable == -4) {
7014 $htmltooltip = $langs->trans('DisabledBecausePayments');
7015 } elseif ($isErasable == -3) {
7016 $htmltooltip = $langs->trans('DisabledBecauseNotLastSituationInvoice');
7017 } elseif ($isErasable == -2) {
7018 $htmltooltip = $langs->trans('DisabledBecauseNotLastInvoice');
7019 } elseif ($isErasable == -1) {
7020 $htmltooltip = $langs->trans('DisabledBecauseDispatchedInBookkeeping');
7021 } elseif ($isErasable <= 0) { // Any other cases
7022 $htmltooltip = $langs->trans('DisabledBecauseNotErasable').(empty($object->error) ? ': UnknownReason' : ': '.$object->error);
7023 } elseif ($objectidnext) {
7024 $htmltooltip = $langs->trans('DisabledBecauseReplacedInvoice');
7025 }
7026 if ($usercandelete || ($usercancreate && $isErasable == 1)) { // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions)
7027 $enableDelete = false;
7028 $deleteHref = '#';
7029 if ($isErasable > 0 && ! $objectidnext) {
7030 $deleteHref = $_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=delete&token='.newToken();
7031 $enableDelete = true;
7032 }
7033 unset($params['attr']['title']);
7034 print dolGetButtonAction($htmltooltip, $langs->trans('Delete'), 'delete', $deleteHref, '', $enableDelete, $params);
7035 } else {
7036 unset($params['attr']['title']);
7037 print dolGetButtonAction($htmltooltip, $langs->trans('Delete'), 'delete', '#', '', false);
7038 }
7039 }
7040 print '</div>';
7041 }
7042
7043 // Select mail models is same action as presend
7044 if (GETPOST('modelselected', 'alpha')) {
7045 $action = 'presend';
7046 }
7047 if ($action != 'prerelance' && $action != 'presend') {
7048 print '<div class="fichecenter"><div class="fichehalfleft">';
7049 print '<a name="builddoc"></a>'; // ancre
7050
7051 // Generated documents
7052 $filename = dol_sanitizeFileName($object->ref);
7053 $filedir = $conf->invoice->multidir_output[$object->entity ?? $conf->entity].'/'.dol_sanitizeFileName($object->ref);
7054 $urlsource = $_SERVER['PHP_SELF'].'?facid='.$object->id;
7055 $genallowed = $usercanread;
7056 $delallowed = $usercancreate;
7057 $tooltipAfterComboOfModels = '';
7058 if (getDolGlobalString('MAIN_PDF_ADD_TERMSOFSALE_INVOICE')) {
7059 $tooltipAfterComboOfModels = $langs->trans("AccordingToYourSetupTheFileWillBeConcatenated", getDolGlobalString('MAIN_INFO_INVOICE_TERMSOFSALE'));
7060 }
7061
7062 print $formfile->showdocuments(
7063 'facture',
7064 $filename,
7065 $filedir,
7066 $urlsource,
7067 $genallowed,
7068 (int) $delallowed,
7069 $object->model_pdf,
7070 1,
7071 0,
7072 0,
7073 28,
7074 0,
7075 '',
7076 '',
7077 '',
7078 $soc->default_lang,
7079 '',
7080 $object,
7081 0,
7082 'remove_file_comfirm',
7083 $tooltipAfterComboOfModels
7084 );
7085
7086 $somethingshown = $formfile->numoffiles;
7087
7088 // Show links to link elements
7089 $tmparray = $form->showLinkToObjectBlock($object, array(), array('invoice'), 1);
7090 $linktoelem = $tmparray['linktoelem'];
7091 $htmltoenteralink = $tmparray['htmltoenteralink'];
7092 print $htmltoenteralink;
7093
7094 $compatibleImportElementsList = false;
7095 if ($usercancreate
7096 && $object->status == Facture::STATUS_DRAFT
7098 $compatibleImportElementsList = array('commande', 'propal', 'subscription'); // import from linked elements
7099 }
7100 $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList);
7101
7102 // Show online payment link
7103 // The list can be complete by the hook 'doValidatePayment' executed inside getValidOnlinePaymentMethods()
7104 include_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
7105 $validpaymentmethod = getValidOnlinePaymentMethods('');
7106 $useonlinepayment = count($validpaymentmethod);
7107
7108 if ($object->status != Facture::STATUS_DRAFT && $useonlinepayment) {
7109 print '<br><!-- Link to pay -->'."\n";
7110 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
7111 print showOnlinePaymentUrl('invoice', $object->ref).'<br>';
7112 }
7113
7114 print '</div><div class="fichehalfright">';
7115
7116 $MAXEVENT = 10;
7117
7118 $morehtmlcenter = '<div class="nowraponall">';
7119 $morehtmlcenter .= dolGetButtonTitle($langs->trans('FullConversation'), '', 'fa fa-comments imgforviewmode', DOL_URL_ROOT.'/compta/facture/messaging.php?id='.$object->id);
7120 $morehtmlcenter .= dolGetButtonTitle($langs->trans('FullList'), '', 'fa fa-bars imgforviewmode', DOL_URL_ROOT.'/compta/facture/agenda.php?id='.$object->id);
7121 $morehtmlcenter .= '</div>';
7122
7123 // List of actions on element
7124 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
7125 $formactions = new FormActions($db);
7126 $somethingshown = $formactions->showactions($object, 'invoice', $socid, 1, '', $MAXEVENT, '', $morehtmlcenter); // Show all action for thirdparty
7127
7128 print '</div></div>';
7129 }
7130
7131
7132 // Presend form
7133 $modelmail = 'facture_send';
7134 $defaulttopic = 'SendBillRef';
7135 $diroutput = $conf->invoice->multidir_output[$object->entity ?? $conf->entity];
7136 $trackid = 'inv'.$object->id;
7137
7138 include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
7139}
7140
7141// End of page
7142llxFooter();
7143$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
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:476
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage bank accounts.
Class to manage accounting journals.
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage warehouses.
Class to manage standard extra fields.
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const STATUS_DRAFT
Draft status.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_PROFORMA
Proforma invoice (should not be used.
const STATUS_VALIDATED
Validated (need to be paid)
const TYPE_DEPOSIT
Deposit invoice.
const STATUS_ABANDONED
Classified abandoned and no payment done.
const TYPE_CREDIT_NOTE
Credit note invoice.
const STATUS_CLOSED
Classified paid.
Class to manage invoice lines.
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 to manage "other" html components Only common components are here.
Class to help generate other html components Only common components are here.
Class with static methods for building HTML components related to products Only components common to ...
Class to manage building of HTML components.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
Class to manage the table of subscription to notifications.
Class to manage payments of customer invoices.
Class ProductCombination Used to represent the relation between a product and one of its variants.
Class to manage products or services.
const TYPE_PRODUCT
Regular product.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage VAT - Value-added tax (also known in French as TVA)
Definition tva.class.php:39
Class to manage Dolibarr users.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
global $mysoc
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition date.lib.php:666
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:451
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:129
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
GETPOSTDATE($prefix, $hourTime='', $gm='auto', $saverestore='')
Helper function that combines values of a dolibarr DatePicker (such as Form\selectDate) for year,...
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dolGetButtonTitle($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
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.
GETPOSTISARRAY($paramname, $method=0)
Return true if the parameter $paramname is submit from a POST OR GET as an array.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTFLOAT($paramname, $rounding='', $option=2)
Return the value of a $_GET or $_POST supervariable, converted into float.
dolGetButtonAction($label, $text='', $actionType='default', $url='', $id='', $userRight=1, $params=array())
Function dolGetButtonAction.
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
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_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
img_edit($titlealt='default', $float=0, $other='')
Show logo edit/modify fiche.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
facture_prepare_head($object)
Initialize the array of tabs for customer invoice.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:137
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.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.