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