dolibarr 25.0.0-alpha
invoice.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2018 Andreu Bisquerra <jove@bisquerra.com>
3 * Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com>
4 * Copyright (C) 2022-2023 Christophe Battarel <christophe.battarel@altairis.fr>
5 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
29// if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Not disabled cause need to load personalized language
30// if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Not disabled cause need to load personalized language
31// if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1');
32// if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1');
33
34if (!defined('NOTOKENRENEWAL')) {
35 define('NOTOKENRENEWAL', '1');
36}
37if (!defined('NOREQUIREMENU')) {
38 define('NOREQUIREMENU', '1');
39}
40if (!defined('NOREQUIREHTML')) {
41 define('NOREQUIREHTML', '1');
42}
43if (!defined('NOREQUIREAJAX')) {
44 define('NOREQUIREAJAX', '1');
45}
46
47// Load Dolibarr environment
48if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
49 require '../main.inc.php';
50}
51require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
52require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
53require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
54require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
55require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
65$hookmanager->initHooks(array('takeposinvoice'));
66
67$langs->loadLangs(array("companies", "commercial", "bills", "cashdesk", "stocks", "banks"));
68
69$action = GETPOST('action', 'aZ09');
70$idproduct = GETPOSTINT('idproduct');
71$place = (GETPOST('place', 'aZ09') ? GETPOST('place', 'aZ09') : 0); // $place is id of table for Bar or Restaurant
72$placeid = 0; // $placeid is ID of invoice
73$mobilepage = GETPOST('mobilepage', 'alpha');
74$batch = GETPOST('batch', 'alpha');
75$sourceinvoiceid = GETPOSTINT('sourceinvoiceid');
76
77// Terminal is stored into $_SESSION["takeposterminal"];
78
79if (!$user->hasRight('takepos', 'run') && !defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
80 accessforbidden('No permission to use the TakePOS');
81}
82
83if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
84 // DIRECT LINK TO THIS PAGE FROM MOBILE AND NO TERMINAL SELECTED
85 if ($_SESSION["takeposterminal"] == "") {
86 if (getDolGlobalString('TAKEPOS_NUM_TERMINALS') == "1") {
87 $_SESSION["takeposterminal"] = 1;
88 } else {
89 header("Location: ".DOL_URL_ROOT."/takepos/index.php");
90 exit;
91 }
92 }
93}
94
95
96$takeposterminal = isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '';
97
98// When session has expired (selected terminal has been lost from session), redirect to the terminal selection.
99if (empty($takeposterminal)) {
100 if (getDolGlobalInt('TAKEPOS_NUM_TERMINALS') == 1) {
101 $_SESSION["takeposterminal"] = 1; // Use terminal 1 if there is only 1 terminal
102 $takeposterminal = 1;
103 } elseif (!empty($_COOKIE["takeposterminal"])) {
104 $_SESSION["takeposterminal"] = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE["takeposterminal"]); // Restore takeposterminal from previous session
105 $takeposterminal = $_SESSION["takeposterminal"];
106 } else {
107 print <<<SCRIPT
108<script type="text/javascript">
109 jQuery(function() {
110 ModalBox('ModalTerminal');
111 });
112</script>
113SCRIPT;
114 exit;
115 }
116}
117
118
125function fail($message)
126{
127 header($_SERVER['SERVER_PROTOCOL'].' 500 Internal Server Error', true, 500);
128 die($message);
129}
130
138function takeposDeleteLineWithChildren($invoice, $lineid)
139{
140 $lineid = (int) $lineid;
141 if ($lineid <= 0) {
142 return 0;
143 }
144
145 $childrenbyparent = array();
146 if (is_array($invoice->lines)) {
147 foreach ($invoice->lines as $line) {
148 $parentid = (int) $line->fk_parent_line;
149 if ($parentid > 0) {
150 $childrenbyparent[$parentid][] = (int) $line->id;
151 }
152 }
153 }
154
155 $linestodelete = array();
156 $stack = array($lineid);
157 while (!empty($stack)) {
158 $currentlineid = array_pop($stack);
159 if (in_array($currentlineid, $linestodelete, true)) {
160 continue;
161 }
162
163 $linestodelete[] = $currentlineid;
164 if (!empty($childrenbyparent[$currentlineid])) {
165 foreach ($childrenbyparent[$currentlineid] as $childlineid) {
166 $stack[] = $childlineid;
167 }
168 }
169 }
170
171 // Delete supplements before their parent line so no orphan line remains visible on receipts.
172 foreach (array_reverse($linestodelete) as $deletelineid) {
173 // Properly unlink discount to make credit note available again
174 $sql_discount = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_facture_line = ".((int) $deletelineid);
175 $resql_discount = $invoice->db->query($sql_discount);
176 if ($resql_discount && $invoice->db->num_rows($resql_discount) > 0) {
177 $obj_discount = $invoice->db->fetch_object($resql_discount);
178 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
179 $discount_to_unlink = new DiscountAbsolute($invoice->db);
180 if ($discount_to_unlink->fetch($obj_discount->rowid) > 0) {
181 $discount_to_unlink->unlink_invoice();
182 }
183 }
184
185 $result = $invoice->deleteLine($deletelineid);
186 if ($result < 0) {
187 return $result;
188 }
189 }
190
191 return 1;
192}
193
194
195
196$number = GETPOSTFLOAT('number', '', 0); // Option 0: the value is typed in the free zone (user format) or sent by the numeric pad (always with a dot)
197$idline = GETPOSTINT('idline');
198$selectedline = GETPOSTINT('selectedline');
199$desc = GETPOST('desc', 'alphanohtml');
200$pay = GETPOST('pay', 'aZ09');
201$amountofpayment = GETPOSTFLOAT('amount');
202
203$invoiceid = GETPOSTINT('invoiceid');
204
205$paycode = $pay;
206if ($pay == 'cash') {
207 $paycode = 'LIQ'; // For backward compatibility
208}
209if ($pay == 'card') {
210 $paycode = 'CB'; // For backward compatibility
211}
212if ($pay == 'cheque') {
213 $paycode = 'CHQ'; // For backward compatibility
214}
215
216// Retrieve paiementid and paiementcode
217$paiementid = 0;
218if ($paycode) {
219 $sql = "SELECT id, code FROM ".MAIN_DB_PREFIX."c_paiement";
220 $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
221 $sql .= " AND code = '".$db->escape($paycode)."'";
222 $resql = $db->query($sql);
223 if ($resql) {
224 $obj = $db->fetch_object($resql);
225 if ($obj) {
226 $paiementid = $obj->id;
227 }
228 }
229}
230
231$invoice = new Facture($db);
232if ($invoiceid > 0) {
233 $ret = $invoice->fetch($invoiceid);
234} else {
235 $ret = $invoice->fetch(0, '(PROV-POS'.$takeposterminal.'-'.$place.')');
236}
237if ($ret > 0) {
238 $placeid = $invoice->id;
239}
240
241$constforcompanyid = 'CASHDESK_ID_THIRDPARTY'.$takeposterminal;
242
243$soc = new Societe($db);
244if ($invoice->socid > 0) {
245 $soc->fetch($invoice->socid);
246} else {
247 $soc->fetch(getDolGlobalInt($constforcompanyid));
248}
249
250// Assign a default project, if relevant
251if (isModEnabled('project') && getDolGlobalInt("CASHDESK_ID_PROJECT".$takeposterminal)) {
252 $invoice->fk_project = getDolGlobalInt("CASHDESK_ID_PROJECT".$takeposterminal);
253}
254
255// Change the currency of invoice if it was modified
256if (isModEnabled('multicurrency') && !empty($_SESSION["takeposcustomercurrency"])) {
257 if ($invoice->multicurrency_code != $_SESSION["takeposcustomercurrency"]) {
258 $invoice->setMulticurrencyCode($_SESSION["takeposcustomercurrency"]);
259 }
260}
261
262$term = empty($_SESSION["takeposterminal"]) ? 1 : $_SESSION["takeposterminal"];
263
264
265/*
266 * Actions
267 */
268$error = 0;
269$parameters = array();
270$reshook = $hookmanager->executeHooks('doActions', $parameters, $invoice, $action); // Note that $action and $object may have been modified by some hooks
271if ($reshook < 0) {
272 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
273}
274
275
276$sectionwithinvoicelink = '';
277$CUSTOMER_DISPLAY_line1 = '';
278$CUSTOMER_DISPLAY_line2 = '';
279$headerorder = '';
280$footerorder = '';
281$printer = null;
282$idoflineadded = 0;
283$clonebatch = GETPOSTINT('clonebatch');
284
285// Enforce the "edit lines" permission on every action that modifies an existing line
286// (delete, quantity, price, discount). Adding a line, a free zone or a note is gated by
287// the "run" permission elsewhere and must stay available to a plain cashier (#38949).
288if (in_array($action, array('deleteline', 'updateqty', 'updateprice', 'updatereduction', 'update_reduction_global')) && !$user->hasRight('takepos', 'editlines')) {
289 dol_htmloutput_errors($langs->trans("NotEnoughPermissions", "TakePos"), array(), 1);
290 $action = '';
291}
292
293
294if (empty($reshook)) {
295 if ($action == 'cloneticket' && $user->hasRight('takepos', 'run')) {
296 $cloneid = 0;
297 $cloneplace = '';
298 $clonemessage = '';
299 $sourceinvoice = new Facture($db);
300 $result = $sourceinvoice->fetch($sourceinvoiceid);
301 $targetentity = !empty($_SESSION['takeposinvoiceentity']) ? (int) $_SESSION['takeposinvoiceentity'] : (int) $conf->entity;
302
303 if ($result <= 0 || $sourceinvoice->module_source != 'takepos' || !in_array($sourceinvoice->status, array(Facture::STATUS_VALIDATED, Facture::STATUS_CLOSED)) || $sourceinvoice->type == Facture::TYPE_CREDIT_NOTE || (int) $sourceinvoice->entity != $targetentity) {
304 $langs->load('errors');
305 $clonemessage = $langs->trans('ErrorBadValueForParameter', 'sourceinvoiceid');
306 setEventMessages($clonemessage, null, 'errors');
307 } else {
308 $cloneinvoice = dol_clone($sourceinvoice, 1);
309 '@phan-var-force Facture $cloneinvoice';
310 $cloneinvoice->date = dol_now();
311 $cloneid = $cloneinvoice->createFromClone($user, $sourceinvoiceid, $targetentity);
312
313 if ($cloneid > 0) {
314 $cloneplace = '0';
315 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture WHERE ref = '(PROV-POS".$db->escape((string) $takeposterminal)."-0)' AND entity IN (".getEntity('invoice').")";
316 $resql = $db->query($sql);
317 if ($resql && $db->num_rows($resql) > 0) {
318 $max_sale = 0;
319 $sql = "SELECT ref FROM ".MAIN_DB_PREFIX."facture WHERE entity IN (".getEntity('invoice').") AND ref LIKE '(PROV-POS".$db->escape((string) $takeposterminal)."-0-%'";
320 $resql2 = $db->query($sql);
321 if ($resql2) {
322 while ($obj = $db->fetch_object($resql2)) {
323 $num_sale = str_replace(")", "", str_replace("(PROV-POS".$takeposterminal."-0-", "", $obj->ref));
324 if ((int) $num_sale > $max_sale) {
325 $max_sale = (int) $num_sale;
326 }
327 }
328 }
329 $cloneplace = '0-'.($max_sale + 1);
330 }
331
332 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
333 $sql .= " SET module_source = 'takepos', pos_source = '".$db->escape((string) $takeposterminal)."',";
334 $sql .= " ref = '".$db->escape("(PROV-POS".((string) $takeposterminal)."-".$cloneplace.")")."'";
335 $sql .= " WHERE rowid = ".((int) $cloneid);
336 $result = $db->query($sql);
337
338 if ($result && isModEnabled('productbatch') && isModEnabled('stock')) {
339 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet";
340 $sql .= " SET batch = NULL, fk_warehouse = NULL";
341 $sql .= " WHERE fk_facture = ".((int) $cloneid);
342 $sql .= " AND fk_product IN (SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tobatch > 0)";
343 $result = $db->query($sql);
344 }
345 }
346
347 if ($cloneid > 0 && $result) {
348 $place = $cloneplace;
349 $placeid = $cloneid;
350 $invoice = new Facture($db);
351 $invoice->fetch($cloneid);
352 $clonebatch = 1;
353 } else {
354 if ($cloneid > 0) {
355 $cloneinvoice->fetch($cloneid);
356 $cloneinvoice->delete($user);
357 $cloneid = 0;
358 }
359 $langs->load('errors');
360 $clonemessage = !empty($cloneinvoice->error) ? $cloneinvoice->error : $langs->trans('ErrorFailedToCloneTicket');
361 setEventMessages($clonemessage, $cloneinvoice->errors, 'errors');
362 }
363 }
364
365 if (GETPOST('format', 'aZ09') == 'json') {
366 $batchlineid = 0;
367 $batchproductid = 0;
368 if ($cloneid > 0 && isModEnabled('productbatch') && isModEnabled('stock')) {
369 $sql = 'SELECT fd.rowid, fd.fk_product';
370 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet AS fd, '.MAIN_DB_PREFIX.'product AS p';
371 $sql .= ' WHERE fd.fk_product = p.rowid';
372 $sql .= ' AND fd.fk_facture = '.((int) $cloneid);
373 $sql .= " AND (fd.batch IS NULL OR fd.batch = '') AND p.tobatch > 0";
374 $sql .= ' ORDER BY fd.rang, fd.rowid';
375 $sql .= $db->plimit(1);
376 $resql = $db->query($sql);
377 if ($resql && ($obj = $db->fetch_object($resql))) {
378 $batchlineid = (int) $obj->rowid;
379 $batchproductid = (int) $obj->fk_product;
380 }
381 }
382
383 top_httphead('application/json');
384 echo json_encode(array('success' => $cloneid > 0, 'invoiceid' => $cloneid, 'place' => $cloneplace, 'batchlineid' => $batchlineid, 'batchproductid' => $batchproductid, 'message' => $clonemessage));
385 exit;
386 }
387 }
388
389 // Test that period is not close
390 $tmpcurrentday = dol_getdate(dol_now());
391
392 $sql = "SELECT MIN(ref) as firstref FROM ".MAIN_DB_PREFIX."pos_cash_fence";
393 $sql .= " WHERE entity = ".((int) $conf->entity);
394 $sql .= " AND posnumber = ".((int) $takeposterminal);
395 $sql .= " AND year_close = ".((int) $tmpcurrentday['year']);
396 $sql .= " AND (";
397 $sql .= " (month_close IS NULL AND day_close IS NULL)";
398 $sql .= " OR (month_close = ".((int) $tmpcurrentday['mon'])." AND day_close IS NULL)";
399 $sql .= " OR (month_close = ".((int) $tmpcurrentday['mon'])." AND day_close = ".((int) $tmpcurrentday['mday']).")";
400 $sql .= ")";
401 $sql .= " AND status = 1";
402
403 $refcashcontrol = 0;
404 $resql = $db->query($sql);
405 if ($resql) {
406 $obj = $db->fetch_object($resql);
407 if ($obj) {
408 $refcashcontrol = $obj->firstref;
409 }
410 }
411
412 if ($refcashcontrol) {
413 $error++;
414 $langs->load('errors');
415 dol_htmloutput_errors($langs->trans("ACashControlHasBeenclosedForCurrentDay", $refcashcontrol), [], 1);
416 $action = '';
417 }
418
419 // Action to record a payment on a TakePOS invoice
420 if ($action == 'valid' && $user->hasRight('takepos', 'run')) {
421 $bankaccount = 0;
422 $error = 0;
423
424 if (getDolGlobalString('TAKEPOS_CAN_FORCE_BANK_ACCOUNT_DURING_PAYMENT')) {
425 $bankaccount = GETPOSTINT('accountid');
426 } else {
427 if ($pay == 'LIQ') {
428 $bankaccount = getDolGlobalInt('CASHDESK_ID_BANKACCOUNT_CASH'.$_SESSION["takeposterminal"]); // For backward compatibility
429 } elseif ($pay == "CHQ") {
430 $bankaccount = getDolGlobalInt('CASHDESK_ID_BANKACCOUNT_CHEQUE'.$_SESSION["takeposterminal"]); // For backward compatibility
431 } else {
432 $accountname = "CASHDESK_ID_BANKACCOUNT_".$pay.$_SESSION["takeposterminal"];
433 $bankaccount = getDolGlobalInt($accountname);
434 }
435 }
436
437 if ($bankaccount <= 0 && $pay != "delayed" && isModEnabled("bank")) {
438 $errormsg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount"));
439 $error++;
440 }
441
442 $now = dol_now();
443 $res = 0;
444
445 $invoice = new Facture($db);
446 $invoice->fetch($placeid);
447
448 $invoice->oldcopy = dol_clone($invoice, 2);
449
450 $db->begin();
451
452 if ($invoice->total_ttc < 0) {
453 $invoice->type = $invoice::TYPE_CREDIT_NOTE;
454
455 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture";
456 $sql .= " WHERE entity IN (".getEntity('invoice').")";
457 $sql .= " AND fk_soc = ".((int) $invoice->socid);
458 $sql .= " AND type <> ".Facture::TYPE_CREDIT_NOTE;
459 $sql .= " AND fk_statut >= ".$invoice::STATUS_VALIDATED;
460 $sql .= " ORDER BY rowid DESC";
461
462 $fk_source = 0;
463 $resql = $db->query($sql);
464 if ($resql) {
465 $obj = $db->fetch_object($resql);
466 $fk_source = $obj->rowid;
467 if ((int) $fk_source == 0) {
468 fail($langs->transnoentitiesnoconv("NoPreviousBillForCustomer"));
469 }
470 } else {
471 fail($langs->transnoentitiesnoconv("NoPreviousBillForCustomer"));
472 }
473 $invoice->fk_facture_source = $fk_source;
474 $invoice->update($user);
475 }
476
477 $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'.(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
478 $allowstockchange = (getDolGlobalString($constantforkey) != "1");
479
480 if ($error) {
481 dol_htmloutput_errors($errormsg, [], 1);
482 } elseif ($invoice->status != Facture::STATUS_DRAFT) {
483 //If invoice is validated but it is not fully paid is not error and make the payment
484 $remaintopay = $invoice->getRemainToPay();
485 if (($remaintopay > 0 && $invoice->type != Facture::TYPE_CREDIT_NOTE) || ($remaintopay < 0 && $invoice->type == Facture::TYPE_CREDIT_NOTE)) {
486 $res = 1;
487 } else {
488 dol_syslog("Sale already validated");
489 dol_htmloutput_errors($langs->trans("InvoiceIsAlreadyValidated", "TakePos"), [], 1);
490 }
491 } elseif (count($invoice->lines) == 0) {
492 $error++;
493 dol_syslog('Sale without lines');
494 dol_htmloutput_errors($langs->trans("NoLinesToBill", "TakePos"), [], 1);
495 } elseif (isModEnabled('stock') && !isModEnabled('productbatch') && $allowstockchange) {
496 // Validation of invoice with change into stock when product/lot module is NOT enabled and stock change NOT disabled.
497 // The case for isModEnabled('productbatch') is processed few lines later.
498 $savconst = getDolGlobalString('STOCK_CALCULATE_ON_BILL');
499
500 $conf->global->STOCK_CALCULATE_ON_BILL = 1; // To force the change of stock during invoice validation
501
502 $constantforkey = 'CASHDESK_ID_WAREHOUSE'.(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
503 dol_syslog("Validate invoice with stock change. Warehouse defined into constant ".$constantforkey." = ".getDolGlobalString($constantforkey));
504
505 // Validate invoice with stock change into warehouse getDolGlobalInt($constantforkey)
506 // Label of stock movement will be the same as when we validate invoice "Invoice XXXX validated"
507 $batch_rule = 0; // Module productbatch is disabled here, so no need for a batch_rule.
508 $res = $invoice->validate($user, '', getDolGlobalInt($constantforkey), 0, $batch_rule);
509
510 // Restore setup
511 $conf->global->STOCK_CALCULATE_ON_BILL = $savconst;
512 } else {
513 // Validation of invoice with no change into stock (because param $idwarehouse is not fill)
514 dol_syslog("Call validate on invoice ".$invoice->ref, LOG_DEBUG);
515 $res = $invoice->validate($user);
516 if ($res < 0) {
517 $error++;
518 $langs->load("admin");
519 dol_htmloutput_errors($invoice->error == 'NotConfigured' ? $langs->trans("NotConfigured").' (TakePos numbering module)' : $invoice->error, $invoice->errors, 1);
520 }
521 }
522
523 // Add the payment
524 if (!$error && $res >= 0) {
525 $remaintopay = $invoice->getRemainToPay();
526 // Credit notes have negative remaintopay; regular invoices have positive
527 if (($remaintopay > 0 && $invoice->type != Facture::TYPE_CREDIT_NOTE) || ($remaintopay < 0 && $invoice->type == Facture::TYPE_CREDIT_NOTE)) {
528 $payment = new Paiement($db);
529
530 $payment->datepaye = $now;
531 $payment->fk_account = $bankaccount;
532 if ($pay == 'LIQ') {
533 $payment->pos_change = GETPOSTFLOAT('excess');
534 }
535
536 $payment->amounts[$invoice->id] = $amountofpayment;
537 // If user has not used change control, add total invoice payment
538 // Or if user has used change control and the amount of payment is higher than remain to pay, add the remain to pay
539 if ($amountofpayment <= 0 || $amountofpayment > $remaintopay) {
540 $payment->amounts[$invoice->id] = $remaintopay;
541 }
542 // We do not set $payments->multicurrency_amounts because we want payment to be in main currency.
543
544 $payment->paiementid = $paiementid;
545 $payment->paiementcode = $paycode;
546 $payment->num_payment = '';
547
548 if ($pay != "delayed") {
549 $res = $payment->create($user); // This record payment and regenerate the PDF
550 if ($res < 0) {
551 $error++;
552 //setEventMessages($payment->error, $payment->errors, 'error');
553 dol_htmloutput_mesg($payment->error, $payment->errors, 'error', 1);
554 } else {
555 //setEventMessages(null, $payment->warnings, 'warnings');
556 if (!empty($payment->warnings)) {
557 dol_htmloutput_mesg('', $payment->warnings, 'warning', 1);
558 }
559
560 $res = $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccount, '', '');
561 if ($res < 0) {
562 $error++;
563 dol_htmloutput_mesg($langs->trans('ErrorNoPaymentDefined').' '.$payment->error, $payment->errors, 'error', 1);
564 }
565 }
566 $remaintopay = $invoice->getRemainToPay(); // Recalculate remain to pay after the payment is recorded
567 } elseif (getDolGlobalInt("TAKEPOS_DELAYED_TERMS")) {
568 $invoice->setPaymentTerms(getDolGlobalInt("TAKEPOS_DELAYED_TERMS"));
569 }
570 }
571
572 if ($remaintopay == 0) {
573 dol_syslog("Invoice is paid, so we set it to status Paid");
574 $result = $invoice->setPaid($user);
575 if ($result > 0) {
576 $invoice->paye = 1;
577 $invoice->status = $invoice::STATUS_CLOSED;
578 $invoice->close_code = '';
579 }
580 // set payment method
581 $invoice->setPaymentMethods($paiementid);
582 } else {
583 dol_syslog("Invoice is not paid, remain to pay = ".$remaintopay);
584 }
585 } else {
586 dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
587 }
588
589
590 $warehouseid = 0;
591 // Update stock for batch products
592 if (!$error && $res >= 0) {
593 if (isModEnabled('stock') && isModEnabled('productbatch') && $allowstockchange) {
594 // Update stocks
595 dol_syslog("Now we record the stock movement for each qualified line");
596
597 // The case !isModEnabled('productbatch') was processed few lines before.
598 require_once DOL_DOCUMENT_ROOT . "/product/stock/class/mouvementstock.class.php";
599 $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
600 $inventorycode = dol_print_date(dol_now(), 'dayhourlog');
601 // Label of stock movement will be "TakePOS - Invoice XXXX"
602 $labeltakeposmovement = 'TakePOS - '.$langs->transnoentitiesnoconv("Invoice").' '.$invoice->ref;
603
604 foreach ($invoice->lines as $line) {
605 // Use the warehouse id defined on invoice line else in the setup
606 $warehouseid = ($line->fk_warehouse ? $line->fk_warehouse : getDolGlobalInt($constantforkey));
607
608 // var_dump('fk_product='.$line->fk_product.' batch='.$line->batch.' warehouse='.$line->fk_warehouse.' qty='.$line->qty);
609 if ($line->batch != '' && $warehouseid > 0) {
610 $prod_batch = new Productbatch($db);
611 $prod_batch->find(0, '', '', $line->batch, $warehouseid, (int) $line->fk_product);
612
613 $mouvP = new MouvementStock($db);
614 $mouvP->setOrigin($invoice->element, $invoice->id);
615
616 if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
617 $res = $mouvP->reception($user, $line->fk_product, $warehouseid, $line->qty, $line->price, $labeltakeposmovement, '', '', $line->batch, '', 0, $inventorycode);
618 } else {
619 $res = $mouvP->livraison($user, $line->fk_product, $warehouseid, $line->qty, $line->price, $labeltakeposmovement, '', '', '', $prod_batch->batch, $prod_batch->id, $inventorycode);
620 }
621
622 if ($res < 0) {
623 dol_htmloutput_errors($mouvP->error, $mouvP->errors, 1);
624 $error++;
625 }
626 } else {
627 $mouvP = new MouvementStock($db);
628 $mouvP->setOrigin($invoice->element, $invoice->id);
629
630 if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
631 $res = $mouvP->reception($user, $line->fk_product, $warehouseid, $line->qty, $line->price, $labeltakeposmovement, '', '', '', '', 0, $inventorycode);
632 } else {
633 $res = $mouvP->livraison($user, $line->fk_product, $warehouseid, $line->qty, $line->price, $labeltakeposmovement, '', '', '', '', 0, $inventorycode);
634 }
635
636 if ($res < 0) {
637 dol_htmloutput_errors($mouvP->error, $mouvP->errors, 1);
638 $error++;
639 }
640 }
641 }
642 }
643 }
644
645 if (!$error && $res >= 0) {
646 $db->commit();
647 } else {
648 $invoice->ref = $invoice->oldcopy->ref;
649 $invoice->paye = $invoice->oldcopy->paye;
650 $invoice->status = $invoice->oldcopy->status;
651 $invoice->statut = $invoice->oldcopy->statut;
652
653 $db->rollback();
654 }
655 }
656
657 $creditnote = null;
658 if ($action == 'creditnote' && $user->hasRight('takepos', 'run')) {
659 $db->begin();
660
661 $creditnote = new Facture($db);
662 $creditnote->socid = $invoice->socid;
663 $creditnote->date = dol_now();
664 $creditnote->module_source = 'takepos';
665 $creditnote->pos_source = isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '' ;
666 $creditnote->type = Facture::TYPE_CREDIT_NOTE;
667 $creditnote->fk_facture_source = $placeid;
668
669 $creditnote->create($user);
670
671 $fk_parent_line = 0; // Initialise
672
673 foreach ($invoice->lines as $line) {
674 // Reset fk_parent_line for no child products and special product
675 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
676 $fk_parent_line = 0;
677 }
678
679 if (getDolGlobalInt('INVOICE_USE_SITUATION')) {
680 if (!empty($invoice->situation_counter)) {
681 $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
682 $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
683 if (!empty($invoice->tab_previous_situation_invoice)) {
684 // search the last standard invoice in cycle and the possible credit note between this last and invoice
685 // TODO Move this out of loop of $invoice->lines
686 $tab_jumped_credit_notes = array();
687 $lineIndex = count($invoice->tab_previous_situation_invoice) - 1;
688 $searchPreviousInvoice = true;
689 while ($searchPreviousInvoice) {
690 if ($invoice->tab_previous_situation_invoice[$lineIndex]->situation_cycle_ref || $lineIndex < 1) {
691 $searchPreviousInvoice = false; // find, exit;
692 break;
693 } else {
694 if ($invoice->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
695 $tab_jumped_credit_notes[$lineIndex] = $invoice->tab_previous_situation_invoice[$lineIndex]->id;
696 }
697 $lineIndex--; // go to previous invoice in cycle
698 }
699 }
700
701 $maxPrevSituationPercent = 0;
702 foreach ($invoice->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
703 if ($prevLine->id == $source_fk_prev_id) {
704 $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
705
706 //$line->subprice = $line->subprice - $prevLine->subprice;
707 $line->total_ht -= $prevLine->total_ht;
708 $line->total_tva -= $prevLine->total_tva;
709 $line->total_ttc -= $prevLine->total_ttc;
710 $line->total_localtax1 -= $prevLine->total_localtax1;
711 $line->total_localtax2 -= $prevLine->total_localtax2;
712
713 $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
714 $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
715 $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
716 $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
717 }
718 }
719
720 // prorata
721 $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
722
723 //print 'New line based on invoice id '.$invoice->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>';
724
725 // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
726 $maxPrevSituationPercent = 0;
727 foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
728 foreach ($invoice->tab_previous_situation_invoice[$index]->lines as $prevLine) {
729 if ($prevLine->fk_prev_id == $source_fk_prev_id) {
730 $maxPrevSituationPercent = $prevLine->situation_percent;
731
732 $line->total_ht -= $prevLine->total_ht;
733 $line->total_tva -= $prevLine->total_tva;
734 $line->total_ttc -= $prevLine->total_ttc;
735 $line->total_localtax1 -= $prevLine->total_localtax1;
736 $line->total_localtax2 -= $prevLine->total_localtax2;
737
738 $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
739 $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
740 $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
741 $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
742 }
743 }
744 }
745
746 // prorata
747 $line->situation_percent += $maxPrevSituationPercent;
748
749 //print 'New line based on invoice id '.$invoice->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>';
750 }
751 }
752 }
753
754 // We update field for credit notes
755 $line->fk_facture = $creditnote->id;
756 $line->fk_parent_line = $fk_parent_line;
757
758 $line->subprice = -$line->subprice; // invert price for object
759 // $line->pa_ht = $line->pa_ht; // we chose to have the buy/cost price always positive, so no inversion of the sign here
760 $line->total_ht = -$line->total_ht;
761 $line->total_tva = -$line->total_tva;
762 $line->total_ttc = -$line->total_ttc;
763 $line->total_localtax1 = -$line->total_localtax1;
764 $line->total_localtax2 = -$line->total_localtax2;
765
766 $line->multicurrency_subprice = -$line->multicurrency_subprice;
767 $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
768 $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
769 $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
770
771 $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount already linked
772
773 $creditnote->lines[] = $line; // insert new line in current object
774
775 // Defined the new fk_parent_line
776 if ($result > 0 && $line->product_type == 9) {
777 $fk_parent_line = $result;
778 }
779 }
780 $creditnote->update_price(1);
781
782 // The credit note is created here.
783 // If TAKEPOS_VALIDATE_CREDIT_NOTE_ON_CREATION is set, we validate it immediately (old behavior).
784 // Otherwise, it is left as draft so it can be edited from TakePOS (e.g. to modify quantities or batches).
785 // Stock movements will be done when the credit note is validated later (via Payment / Valid action).
786 $res = 1;
787 if (getDolGlobalString('TAKEPOS_VALIDATE_CREDIT_NOTE_ON_CREATION')) {
788 $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'.(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
789 $allowstockchange = getDolGlobalString($constantforkey) != "1";
790
791 if (isModEnabled('stock') && !isModEnabled('productbatch') && $allowstockchange) {
792 $savconst = getDolGlobalString('STOCK_CALCULATE_ON_BILL');
793 $conf->global->STOCK_CALCULATE_ON_BILL = 1; // Force stock update on invoice validation
794
795 $constantforkey = 'CASHDESK_ID_WAREHOUSE'.(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
796 $warehouseid = getDolGlobalInt($constantforkey);
797
798 dol_syslog("Validate invoice with stock change into warehouse defined into constant ".$constantforkey." = ".getDolGlobalString($constantforkey)." or warehouseid= ".$warehouseid." if defined.");
799
800 $batch_rule = 0; // Module productbatch is disabled here, so no need for a batch_rule.
801 $res = $creditnote->validate($user, '', $warehouseid, 0, $batch_rule);
802 if ($res < 0) {
803 $error++;
804 dol_htmloutput_errors($creditnote->error, $creditnote->errors, 1);
805 }
806
807 // Restore setup
808 $conf->global->STOCK_CALCULATE_ON_BILL = $savconst;
809 } else {
810 $res = $creditnote->validate($user);
811 }
812
813 // Update stock for batch products
814 if (!$error && $res >= 0) {
815 if (isModEnabled('stock') && isModEnabled('productbatch') && $allowstockchange) {
816 dol_syslog("Now we record the stock movement for each qualified line");
817
818 require_once DOL_DOCUMENT_ROOT . "/product/stock/class/mouvementstock.class.php";
819 $constantforkey = 'CASHDESK_ID_WAREHOUSE'.(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
820 $inventorycode = dol_print_date(dol_now(), 'dayhourlog');
821 $labeltakeposmovement = 'TakePOS - '.$langs->transnoentitiesnoconv("CreditNote").' '.$creditnote->ref;
822
823 foreach ($creditnote->lines as $line) {
824 // Use the warehouse id defined on invoice line else in the setup
825 $warehouseid = ($line->fk_warehouse ? $line->fk_warehouse : getDolGlobalInt($constantforkey));
826
827 $mouvP = new MouvementStock($db);
828 $mouvP->setOrigin($creditnote->element, $creditnote->id);
829
830 $batch_to_use = ($line->batch != '' && $warehouseid > 0) ? $line->batch : '';
831
832 $res = $mouvP->reception($user, $line->fk_product, $warehouseid, $line->qty, $line->price, $labeltakeposmovement, '', '', $batch_to_use, '', 0, $inventorycode);
833 if ($res < 0) {
834 dol_htmloutput_errors($mouvP->error, $mouvP->errors, 1);
835 $error++;
836 }
837 }
838 }
839 }
840 }
841
842 if (!$error) {
843 $db->commit();
844 } else {
845 $creditnote->id = $placeid; // Creation has failed, we reset to ID of source invoice so we go back to this one in action=history
846 $db->rollback();
847 }
848 }
849
850 if (($action == 'history' || $action == 'creditnote') && $user->hasRight('takepos', 'run')) {
851 if ($action == 'creditnote' && $creditnote !== null && $creditnote->id > 0) { // Test on permission already done
852 $placeid = $creditnote->id;
853 } else {
854 $placeid = GETPOSTINT('placeid');
855 }
856
857 $invoice = new Facture($db);
858 $invoice->fetch($placeid);
859 }
860
861 // If we add a line and no invoice yet, we create the invoice
862 if (($action == "addline" || $action == "freezone") && $placeid == 0 && ($user->hasRight('takepos', 'run') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE'))) {
863 $invoice->socid = getDolGlobalInt($constforcompanyid);
864
865 $dolnowtzuserrel = dol_now('tzuserrel'); // If user is 02 january 22:00, we want to store '02 january'
866 $monthuser = dol_print_date($dolnowtzuserrel, '%m', 'gmt');
867 $dayuser = dol_print_date($dolnowtzuserrel, '%d', 'gmt');
868 $yearuser = dol_print_date($dolnowtzuserrel, '%Y', 'gmt');
869 $dateinvoice = dol_mktime(0, 0, 0, (int) $monthuser, (int) $dayuser, (int) $yearuser, 'tzserver'); // If we enter the 02 january, we need to save the 02 january for server
870
871 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
872 $invoice->date = $dateinvoice; // Invoice::create() needs a date with no hours
873
874 /*
875 print "monthuser=".$monthuser." dayuser=".$dayuser." yearuser=".$yearuser.'<br>';
876 print '---<br>';
877 print 'TZSERVER: '.dol_print_date(dol_now('tzserver'), 'dayhour', 'gmt').'<br>';
878 print 'TZUSER: '.dol_print_date(dol_now('tzuserrel'), 'dayhour', 'gmt').'<br>';
879 print 'GMT: '.dol_print_date(dol_now('gmt'), 'dayhour', 'gmt').'<br>'; // Hour in greenwich
880 print '---<br>';
881 print dol_print_date($invoice->date, 'dayhour', 'gmt').'<br>';
882 print "IN SQL, we will got: ".dol_print_date($db->idate($invoice->date), 'dayhour', 'gmt').'<br>';
883 print dol_print_date($db->idate($invoice->date, 'gmt'), 'dayhour', 'gmt').'<br>';
884 */
885
886 $invoice->module_source = 'takepos';
887 $invoice->pos_source = isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '' ;
888 $invoice->entity = !empty($_SESSION["takeposinvoiceentity"]) ? $_SESSION["takeposinvoiceentity"] : $conf->entity;
889
890 if ($invoice->socid <= 0) {
891 $langs->load('errors');
892 dol_htmloutput_errors($langs->trans("ErrorModuleSetupNotComplete", "TakePos"), [], 1);
893 } else {
894 $db->begin();
895
896 // Create invoice
897 $placeid = $invoice->create($user);
898
899 if ($placeid < 0) {
900 $error++;
901 dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
902 } else {
903 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
904 $sql .= " SET ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")'";
905 $sql .= " WHERE rowid = ".((int) $placeid);
906 $resql = $db->query($sql);
907 if (!$resql) {
908 $error++;
909 }
910 }
911
912 if (!$error) {
913 $db->commit();
914 } else {
915 $db->rollback();
916 }
917 }
918 }
919
920 $tva_npr = 0;
921 // If we add a line by clicking on a product (invoice exists here because it was created juste before if it didn't exists)
922 if ($action == "addline" && ($user->hasRight('takepos', 'run') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE'))) {
923 $prod = new Product($db);
924 $prod->fetch($idproduct);
925
926 $customer = new Societe($db);
927 $customer->fetch($invoice->socid);
928
929 $datapriceofproduct = $prod->getSellPrice($mysoc, $customer, 0);
930
931 $qty = GETPOSTISSET('qty') ? GETPOSTFLOAT('qty', '', GETPOSTINT('qty_std') ? 1 : 2) : 1;
932 $price = $datapriceofproduct['pu_ht'];
933 $price_ttc = $datapriceofproduct['pu_ttc'];
934 //$price_min = $datapriceofproduct['price_min'];
935 $price_base_type = empty($datapriceofproduct['price_base_type']) ? 'HT' : $datapriceofproduct['price_base_type'];
936 $tva_tx = $datapriceofproduct['tva_tx'];
937 $tva_npr = (int) $datapriceofproduct['tva_npr'];
938
939 // Local Taxes
940 $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr);
941 $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr);
942
943
944 if (isModEnabled('productbatch') && isModEnabled('stock')) {
945 $batch = GETPOST('batch', 'alpha');
946
947 if (!empty($batch)) { // We have just clicked on a batch number, we will execute action=setbatch later...
948 $action = "setbatch";
949 } elseif ($prod->status_batch > 0) {
950 // If product need a lot/serial, we show the list of lot/serial available for the product...
951
952 // Set nb of suggested with nb of batch into the warehouse of the terminal
953 $nbofsuggested = 0;
954 $prod->load_stock('warehouseopen');
955
956 $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
957 $warehouseid = getDolGlobalInt($constantforkey);
958
959 //var_dump($prod->stock_warehouse);
960 foreach ($prod->stock_warehouse as $tmpwarehouseid => $tmpval) {
961 if (getDolGlobalInt($constantforkey) && $tmpwarehouseid != getDolGlobalInt($constantforkey)) {
962 // Product to select is not on the warehouse configured for terminal, so we ignore this warehouse
963 continue;
964 }
965 if (!empty($prod->stock_warehouse[$tmpwarehouseid]) && is_array($prod->stock_warehouse[$tmpwarehouseid]->detail_batch)) {
966 if (is_object($prod->stock_warehouse[$tmpwarehouseid]) && count($prod->stock_warehouse[$tmpwarehouseid]->detail_batch)) {
967 foreach ($prod->stock_warehouse[$tmpwarehouseid]->detail_batch as $dbatch) {
968 $nbofsuggested++;
969 }
970 }
971 }
972 }
973 //var_dump($prod->stock_warehouse);
974
975 echo "<script>\n";
976 echo "function addbatch(batch, warehouseid) {\n";
977 echo "console.log('We add batch '+batch+' from warehouse id '+warehouseid);\n";
978 echo '$("#poslines").load("'.DOL_URL_ROOT.'/takepos/invoice.php?action=addline&batch="+encodeURIComponent(batch)+"&warehouseid="+warehouseid+"&place='.$place.'&idproduct='.$idproduct.'&token='.newToken().'", function() {});'."\n";
979 echo "}\n";
980 echo "</script>\n";
981
982 $suggestednb = 1;
983 echo "<center>".$langs->trans("SearchIntoBatch").": <b> $nbofsuggested </b></center><br><table>";
984 foreach ($prod->stock_warehouse as $tmpwarehouseid => $tmpval) {
985 if (getDolGlobalInt($constantforkey) && $tmpwarehouseid != getDolGlobalInt($constantforkey)) {
986 // Not on the forced warehouse, so we ignore this warehouse
987 continue;
988 }
989 if (!empty($prod->stock_warehouse[$tmpwarehouseid]) && is_array($prod->stock_warehouse[$tmpwarehouseid]->detail_batch)) {
990 foreach ($prod->stock_warehouse[$tmpwarehouseid]->detail_batch as $dbatch) { // $dbatch is instance of Productbatch
991 $batchStock = + $dbatch->qty; // To get a numeric
992 $quantityToBeDelivered = 1;
993 $deliverableQty = min($quantityToBeDelivered, $batchStock);
994 print '<tr>';
995 print '<!-- subj='.$suggestednb.'/'.$nbofsuggested.' -->';
996 print '<!-- Show details of lot/serial in warehouseid='.$tmpwarehouseid.' -->';
997 print '<td class="left">';
998 $detail = '';
999 $detail .= '<span class="opacitymedium">'.$langs->trans("LotSerial").':</span> '.$dbatch->batch;
1000 //if (!getDolGlobalString('PRODUCT_DISABLE_SELLBY')) {
1001 //$detail .= ' - '.$langs->trans("SellByDate").': '.dol_print_date($dbatch->sellby, "day");
1002 //}
1003 //if (!getDolGlobalString('PRODUCT_DISABLE_EATBY')) {
1004 //$detail .= ' - '.$langs->trans("EatByDate").': '.dol_print_date($dbatch->eatby, "day");
1005 //}
1006 $detail .= '</td><td>';
1007 $detail .= '<span class="opacitymedium">'.$langs->trans("Qty").':</span> '.$dbatch->qty;
1008 $detail .= '</td><td>';
1009 $detail .= ' <button class="marginleftonly" onclick="addbatch(\''.dol_escape_js($dbatch->batch).'\', '.$tmpwarehouseid.')">'.$langs->trans("Select")."</button>";
1010 $detail .= '<br>';
1011 print $detail;
1012
1013 $quantityToBeDelivered -= $deliverableQty;
1014 if ($quantityToBeDelivered < 0) {
1015 $quantityToBeDelivered = 0;
1016 }
1017 $suggestednb++;
1018 print '</td></tr>';
1019 }
1020 }
1021 }
1022
1023 if ($nbofsuggested == 0) {
1024 // Add manual entry for returns or new batches when stock is 0
1025 print '<tr><td class="left" style="padding-top: 10px; border-top: 1px solid #ddd; text-align: center;">';
1026 print '<span class="opacitymedium">'.$langs->trans("LotSerial").' (Manual) :</span> ';
1027 print '<input type="text" id="manual_batch_add" class="flat" size="10"> ';
1028 print '<button class="button" onclick="addbatch(document.getElementById(\'manual_batch_add\').value, '.$warehouseid.')">'.$langs->trans("Add").'</button>';
1029 print '</td></tr>';
1030 }
1031
1032 print "</table>";
1033
1034 print '</body></html>';
1035 exit;
1036 }
1037 }
1038
1039
1040 if (getDolGlobalString('TAKEPOS_SUPPLEMENTS')) {
1041 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1042 $cat = new Categorie($db);
1043 $categories = $cat->containing($idproduct, 'product');
1044 $found = (array_search(getDolGlobalInt('TAKEPOS_SUPPLEMENTS_CATEGORY'), array_column($categories, 'id')));
1045 if ($found !== false) { // If this product is a supplement
1046 $sql = "SELECT fk_parent_line FROM ".MAIN_DB_PREFIX."facturedet where rowid = ".((int) $selectedline);
1047 $resql = $db->query($sql);
1048 $row = $db->fetch_array($resql);
1049 if ($row[0] == null) {
1050 $parent_line = $selectedline;
1051 } else {
1052 $parent_line = $row[0]; //If the parent line is already a supplement, add the supplement to the main product
1053 }
1054 }
1055 }
1056
1057 $err = 0;
1058 // Group if enabled. Skip group if line already sent to the printer, or if product requires a batch/serial number (cannot group different serials)
1059 if (getDolGlobalString('TAKEPOS_GROUP_SAME_PRODUCT') && empty($prod->status_batch)) {
1060 foreach ($invoice->lines as $line) {
1061 if ($line->product_ref == $prod->ref) {
1062 if ($line->special_code == 4) {
1063 continue;
1064 } // If this line is sended to printer create new line
1065 // check if qty in stock
1066 if (getDolGlobalString('TAKEPOS_QTY_IN_STOCK') && (($line->qty + $qty) > $prod->stock_reel)) {
1067 $invoice->error = $langs->trans("ErrorStockIsNotEnough");
1068 dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
1069 $err++;
1070 break;
1071 }
1072 $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty + $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->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit);
1073 if ($result < 0) {
1074 dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
1075 } else {
1076 $idoflineadded = $line->id;
1077 }
1078 break;
1079 }
1080 }
1081 }
1082 if ($idoflineadded <= 0 && empty($err)) {
1083 $invoice->fetch_thirdparty();
1084 $array_options = array();
1085
1086 $line = array('description' => $prod->description, 'price' => $price, 'tva_tx' => $tva_tx, 'localtax1_tx' => $localtax1_tx, 'localtax2_tx' => $localtax2_tx, 'remise_percent' => $customer->remise_percent, 'price_ttc' => $price_ttc, 'array_options' => $array_options);
1087
1088 /* setup of margin calculation */
1089 if (getDolGlobalString('MARGIN_TYPE')) {
1090 if (getDolGlobalString('MARGIN_TYPE') == 'pmp' && !empty($prod->pmp)) {
1091 $line['fk_fournprice'] = null;
1092 $line['pa_ht'] = $prod->pmp;
1093 } elseif (getDolGlobalString('MARGIN_TYPE') == 'costprice' && !empty($prod->cost_price)) {
1094 $line['fk_fournprice'] = null;
1095 $line['pa_ht'] = $prod->cost_price;
1096 } else {
1097 // default is fournprice
1098 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1099 $pf = new ProductFournisseur($db);
1100 if ($pf->find_min_price_product_fournisseur($idproduct, $qty) > 0) {
1101 $line['fk_fournprice'] = $pf->product_fourn_price_id;
1102 $line['pa_ht'] = $pf->fourn_unitprice_with_discount;
1103 if (getDolGlobalString('PRODUCT_CHARGES') && $pf->fourn_charges > 0) {
1104 $line['pa_ht'] += (float) $pf->fourn_charges / $pf->fourn_qty;
1105 }
1106 }
1107 }
1108 }
1109
1110 // complete line by hook
1111 $parameters = array('prod' => $prod, 'line' => $line);
1112 $reshook = $hookmanager->executeHooks('completeTakePosAddLine', $parameters, $invoice, $action); // Note that $action and $line may have been modified by some hooks
1113 if ($reshook < 0) {
1114 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1115 }
1116
1117
1118 if (empty($reshook)) {
1119 if (!empty($hookmanager->resArray)) {
1120 $line = $hookmanager->resArray;
1121 }
1122
1123 // check if qty in stock
1124 if (getDolGlobalString('TAKEPOS_QTY_IN_STOCK') && $qty > $prod->stock_reel) {
1125 $invoice->error = $langs->trans("ErrorStockIsNotEnough");
1126 dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
1127 $err++;
1128 }
1129
1130 if (empty($err)) {
1131 $idoflineadded = $invoice->addline($line['description'], $line['price'], $qty, $line['tva_tx'], $line['localtax1_tx'], $line['localtax2_tx'], $idproduct, (float) $line['remise_percent'], '', 0, 0, 0, 0, $price_base_type, $line['price_ttc'], $prod->type, -1, 0, '', 0, (empty($parent_line) ? '' : $parent_line), (empty($line['fk_fournprice']) ? 0 : $line['fk_fournprice']), (empty($line['pa_ht']) ? '' : $line['pa_ht']), '', $line['array_options'], 100, 0, $prod->fk_unit, 0);
1132 }
1133 }
1134
1135 if (getDolGlobalString('TAKEPOS_CUSTOMER_DISPLAY')) {
1136 $CUSTOMER_DISPLAY_line1 = $prod->label;
1137 $CUSTOMER_DISPLAY_line2 = price($price_ttc);
1138 }
1139 }
1140
1141 $invoice->fetch($placeid);
1142 }
1143
1144 // If we add a line by submitting freezone form (invoice exists here because it was created just before if it didn't exist)
1145 if ($action == "freezone" && $user->hasRight('takepos', 'run')) {
1146 $customer = new Societe($db);
1147 $customer->fetch($invoice->socid);
1148
1149 $tva_tx = GETPOST('tva_tx', 'alpha');
1150 if ($tva_tx != '') {
1151 if (!preg_match('/\‍((.*)\‍)/', $tva_tx)) {
1152 $tva_tx = price2num($tva_tx);
1153 }
1154 } else {
1155 $tva_tx = get_default_tva($mysoc, $customer);
1156 }
1157
1158 // Local Taxes
1159 $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr);
1160 $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr);
1161
1162 $res = $invoice->addline($desc, $number, 1, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', 0, 0, 0, 0, getDolGlobalInt('TAKEPOS_DISCOUNT_TTC') ? ($number >= 0 ? 'HT' : 'TTC') : (getDolGlobalInt('TAKEPOS_CHANGE_PRICE_HT') ? 'HT' : 'TTC'), $number, 0, -1, 0, '', 0, 0, 0, 0, '', array(), 100, 0, null, 0);
1163 if ($res < 0) {
1164 dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
1165 }
1166 $invoice->fetch($placeid);
1167 }
1168
1169 if ($action == "addnote" && ($user->hasRight('takepos', 'run') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE'))) {
1170 $desc = GETPOST('addnote', 'alpha');
1171 if ($idline == 0) {
1172 $invoice->update_note($desc, '_public');
1173 } else {
1174 foreach ($invoice->lines as $line) {
1175 if ($line->id == $idline) {
1176 $result = $invoice->updateline($line->id, $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->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit);
1177 }
1178 }
1179 }
1180 $invoice->fetch($placeid);
1181 }
1182
1183 if ($action == "deleteline" && ($user->hasRight('takepos', 'editlines') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE'))) {
1184 /*
1185 $permissiontoupdateline = ($user->hasRight('takepos', 'editlines') && ($user->hasRight('takepos', 'editorderedlines') || $line->special_code != "4"));
1186 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
1187 if ($invoice->status == $invoice::STATUS_DRAFT && $invoice->pos_source && $invoice->module_source == 'takepos') {
1188 $permissiontoupdateline = true;
1189 // TODO Add also a test on $_SESSION('publicobjectid'] defined at creation of object
1190 // TODO Check also that invoice->ref is (PROV-POS1-2) with 1 = terminal and 2, the table ID
1191 }
1192 }*/
1193 $db->begin();
1194
1195 if ($idline > 0 && $placeid > 0) { // If invoice exists and a line is selected.
1196 $result = takeposDeleteLineWithChildren($invoice, $idline);
1197 if ($result < 0) {
1198 dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
1199 }
1200 $invoice->fetch($placeid);
1201 } elseif ($placeid > 0) { // If invoice exists but no line selected (delete from another device or with no line selected), proceed to delete the last line.
1202 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facturedet where fk_facture = ".((int) $placeid)." ORDER BY rowid DESC";
1203 $resql = $db->query($sql);
1204 $obj = $db->fetch_object($resql);
1205 if ($obj) {
1206 $deletelineid = $obj->rowid;
1207 $result = takeposDeleteLineWithChildren($invoice, $deletelineid);
1208 if ($result < 0) {
1209 dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
1210 }
1211 }
1212 $invoice->fetch($placeid);
1213 }
1214
1215 $db->commit();
1216
1217 if (count($invoice->lines) == 0) {
1218 // Keep an empty draft invoice alive when a non-default customer was
1219 // already attached so deleting the last line does not silently lose
1220 // the customer that was just selected (#38219). Only drop the invoice
1221 // when it is still on the default cashdesk thirdparty (or none).
1222 $defaultsocid = (int) getDolGlobalString('CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]);
1223 $invoicesocid = (int) $invoice->socid;
1224 if ($invoicesocid === 0 || $invoicesocid === $defaultsocid) {
1225 $invoice->delete($user);
1226
1227 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
1228 header("Location: ".DOL_URL_ROOT."/takepos/public/auto_order.php");
1229 } else {
1230 header("Location: ".DOL_URL_ROOT."/takepos/invoice.php");
1231 }
1232 exit;
1233 }
1234 }
1235 }
1236
1237 // Action to delete or discard an invoice
1238 if ($action == "delete" && ($user->hasRight('takepos', 'run') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE'))) {
1239 // $placeid is the invoice id (it differs from place) and is defined if the place is set and
1240 // the ref of invoice is '(PROV-POS'.$_SESSION["takeposterminal"].'-'.$place.')', so the fetch at beginning of page works.
1241 if ($placeid > 0) {
1242 $result = $invoice->fetch($placeid);
1243
1244 if ($result > 0 && $invoice->status == Facture::STATUS_DRAFT) {
1245 $db->begin();
1246
1247 // We delete the lines
1248 $resdeletelines = 1;
1249 foreach ($invoice->lines as $line) {
1250 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1251 $tmpres = $invoice->deleteLine($line->id);
1252 if ($tmpres < 0) {
1253 $resdeletelines = 0;
1254 break;
1255 }
1256 }
1257
1258 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
1259 $varforconst = 'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"];
1260 $sql .= " SET fk_soc = ".((int) getDolGlobalString($varforconst)).", ";
1261 $sql .= " datec = '".$db->idate(dol_now())."'";
1262 $sql .= " WHERE entity IN (".getEntity('invoice').")";
1263 $sql .= " AND ref = '(PROV-POS".$db->escape($_SESSION["takeposterminal"]."-".$place).")'";
1264 $resql1 = $db->query($sql);
1265
1266 if ($resdeletelines && $resql1) {
1267 $db->commit();
1268 } else {
1269 $db->rollback();
1270 }
1271
1272 $invoice->fetch($placeid);
1273 }
1274 }
1275 }
1276
1277 // Action to fully remove (discard) the current sale: delete the draft invoice so its tab disappears
1278 // (the "delete" action above only empties and resets the cart).
1279 if ($action == "discardsale" && ($user->hasRight('takepos', 'run') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE'))) {
1280 if ($placeid > 0) {
1281 $result = $invoice->fetch($placeid);
1282 if ($result > 0 && $invoice->status == Facture::STATUS_DRAFT) {
1283 $invoice->delete($user);
1284 $placeid = 0;
1285 }
1286 }
1287 }
1288
1289 if ($action == "updateqty") { // Test on permission is done later
1290 foreach ($invoice->lines as $line) {
1291 if ($line->id == $idline) {
1292 $permissiontoupdateline = ($user->hasRight('takepos', 'editlines') && ($user->hasRight('takepos', 'editorderedlines') || $line->special_code != "4"));
1293 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
1294 if ($invoice->status == $invoice::STATUS_DRAFT && $invoice->pos_source && $invoice->module_source == 'takepos') {
1295 $permissiontoupdateline = true;
1296 // TODO Add also a test on $_SESSION('publicobjectid'] defined at creation of object
1297 // TODO Check also that invoice->ref is (PROV-POS1-2) with 1 = terminal and 2, the table ID
1298 }
1299 }
1300 if (!$permissiontoupdateline) {
1301 dol_htmloutput_errors($langs->trans("NotEnoughPermissions", "TakePos").' - No permission to updateqty', [], 1);
1302 } else {
1303 if ($number <= 0) {
1304 $result = takeposDeleteLineWithChildren($invoice, $line->id);
1305 if ($result < 0) {
1306 dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
1307 }
1308 } else {
1309 $vatratecode = $line->tva_tx;
1310 if ($line->vat_src_code) {
1311 $vatratecode .= ' ('.$line->vat_src_code.')';
1312 }
1313
1314 $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $number, $line->remise_percent, $line->date_start, $line->date_end, $vatratecode, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit);
1315 }
1316 }
1317 }
1318 }
1319
1320 $invoice->fetch($placeid);
1321 }
1322
1323 if ($action == "updateprice") { // Test on permission is done later
1324 $customer = new Societe($db);
1325 $customer->fetch($invoice->socid);
1326
1327 foreach ($invoice->lines as $line) {
1328 if ($line->id == $idline) {
1329 $prod = new Product($db);
1330 $prod->fetch($line->fk_product);
1331 $datapriceofproduct = $prod->getSellPrice($mysoc, $customer, 0);
1332 $price_min = $datapriceofproduct['price_min'];
1333 $usercanproductignorepricemin = ((getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('produit', 'ignore_price_min_advance')) || !getDolGlobalString('MAIN_USE_ADVANCED_PERMS'));
1334
1335 $vatratecleaned = $line->tva_tx;
1336 $reg = array();
1337 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', (string) $line->tva_tx, $reg)) { // If vat is "xx (yy)"
1338 $vatratecleaned = trim($reg[1]);
1339 //$vatratecode = $reg[2];
1340 }
1341
1342 $pu_ht = price2num((float) price2num($number, 'MU') / (1 + ((float) $vatratecleaned / 100)), 'MU');
1343 // Check min price
1344 if ($usercanproductignorepricemin && (!empty($price_min) && ((float) price2num($pu_ht) * (1 - (float) price2num($line->remise_percent) / 100) < price2num($price_min)))) {
1345 $langs->load("products");
1346 dol_htmloutput_errors($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency)));
1347 // echo $langs->trans("CantBeLessThanMinPrice");
1348 } else {
1349 $permissiontoupdateline = ($user->hasRight('takepos', 'editlines') && ($user->hasRight('takepos', 'editorderedlines') || $line->special_code != "4"));
1350 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
1351 if ($invoice->status == $invoice::STATUS_DRAFT && $invoice->pos_source && $invoice->module_source == 'takepos') {
1352 $permissiontoupdateline = true;
1353 // TODO Add also a test on $_SESSION('publicobjectid'] defined at creation of object
1354 // TODO Check also that invoice->ref is (PROV-POS1-2) with 1 = terminal and 2, the table ID
1355 }
1356 }
1357
1358 $vatratecode = $line->tva_tx;
1359 if ($line->vat_src_code) {
1360 $vatratecode .= ' ('.$line->vat_src_code.')';
1361 }
1362
1363 if (!$permissiontoupdateline) {
1364 dol_htmloutput_errors($langs->trans("NotEnoughPermissions", "TakePos").' - No permission to updateprice', [], 1);
1365 } elseif (getDolGlobalInt('TAKEPOS_CHANGE_PRICE_HT') == 1) {
1366 $result = $invoice->updateline($line->id, $line->desc, $number, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vatratecode, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit);
1367 } else {
1368 $result = $invoice->updateline($line->id, $line->desc, $number, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vatratecode, $line->localtax1_tx, $line->localtax2_tx, 'TTC', $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);
1369 }
1370 }
1371 }
1372 }
1373
1374 // Reload data
1375 $invoice->fetch($placeid);
1376 }
1377
1378 if ($action == "updatereduction") { // Test on permission is done later
1379 $customer = new Societe($db);
1380 $customer->fetch($invoice->socid);
1381
1382 foreach ($invoice->lines as $line) {
1383 if ($line->id == $idline) {
1384 dol_syslog("updatereduction Process line ".$line->id.' to apply discount of '.$number.'%');
1385
1386 $prod = new Product($db);
1387 $prod->fetch($line->fk_product);
1388
1389 $datapriceofproduct = $prod->getSellPrice($mysoc, $customer, 0);
1390 $price_min = $datapriceofproduct['price_min'];
1391 $usercanproductignorepricemin = ((getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('produit', 'ignore_price_min_advance')) || !getDolGlobalString('MAIN_USE_ADVANCED_PERMS'));
1392
1393 $pu_ht = price2num($line->subprice / (1 + ($line->tva_tx / 100)), 'MU');
1394
1395 // Check min price
1396 if ($usercanproductignorepricemin && (!empty($price_min) && ((float) price2num($line->subprice) * (1 - (float) price2num($number) / 100) < (float) price2num($price_min)))) {
1397 $langs->load("products");
1398 dol_htmloutput_errors($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency)));
1399 } else {
1400 $permissiontoupdateline = ($user->hasRight('takepos', 'editlines') && ($user->hasRight('takepos', 'editorderedlines') || $line->special_code != "4"));
1401 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
1402 if ($invoice->status == $invoice::STATUS_DRAFT && $invoice->pos_source && $invoice->module_source == 'takepos') {
1403 $permissiontoupdateline = true;
1404 // TODO Add also a test on $_SESSION('publicobjectid'] defined at creation of object
1405 // TODO Check also that invoice->ref is (PROV-POS1-2) with 1 = terminal and 2, the table ID
1406 }
1407 }
1408 if (!$permissiontoupdateline) {
1409 dol_htmloutput_errors($langs->trans("NotEnoughPermissions", "TakePos"), [], 1);
1410 } else {
1411 $vatratecode = $line->tva_tx;
1412 if ($line->vat_src_code) {
1413 $vatratecode .= ' ('.$line->vat_src_code.')';
1414 }
1415 $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty, $number, $line->date_start, $line->date_end, $vatratecode, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit);
1416 }
1417 }
1418 }
1419 }
1420
1421 // Reload data
1422 $invoice->fetch($placeid);
1423 } elseif ($action == 'update_reduction_global' && $user->hasRight('takepos', 'editlines')) {
1424 foreach ($invoice->lines as $line) {
1425 $vatratecode = $line->tva_tx;
1426 if ($line->vat_src_code) {
1427 $vatratecode .= ' ('.$line->vat_src_code.')';
1428 }
1429 $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty, $number, $line->date_start, $line->date_end, $vatratecode, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit);
1430 }
1431
1432 $invoice->fetch($placeid);
1433 }
1434
1435 if ($action == "editbatch_popup" && ($user->hasRight('takepos', 'run') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE'))) {
1436 $idline = GETPOSTINT('idline');
1437 $idproduct = GETPOSTINT('idproduct');
1438 $prod = new Product($db);
1439 $prod->fetch($idproduct);
1440 $prod->load_stock('warehouseopen');
1441
1442 $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
1443 $warehouseid = getDolGlobalInt($constantforkey);
1444
1445 print '<html><body>';
1446 print '<div class="divscroll">';
1447 print '<div class="marginbottomonly"><b>'.dolPrintLabel($prod->label).'</b>'.(!empty($prod->ref) ? ' <span class="opacitymedium">('.dolPrintLabel($prod->ref).')</span>' : '').'</div>';
1448 print '<table class="noborder">';
1449
1450 $nbofsuggested = 0;
1451 if (is_array($prod->stock_warehouse)) {
1452 foreach ($prod->stock_warehouse as $tmpwarehouseid => $tmpval) {
1453 if (getDolGlobalInt($constantforkey) && $tmpwarehouseid != getDolGlobalInt($constantforkey)) {
1454 continue;
1455 }
1456 if (!empty($prod->stock_warehouse[$tmpwarehouseid]) && is_array($prod->stock_warehouse[$tmpwarehouseid]->detail_batch)) {
1457 foreach ($prod->stock_warehouse[$tmpwarehouseid]->detail_batch as $dbatch) {
1458 $detail = '';
1459 $detail .= '<span class="opacitymedium">'.$langs->trans("LotSerial").':</span> '.$dbatch->batch;
1460 $detail .= ' <span class="opacitymedium">'.$langs->trans("Qty").':</span> '.$dbatch->qty;
1461 $detail .= ' <button class="marginleftonly" onclick="updatebatch(\''.dol_escape_js($dbatch->batch).'\', '.$tmpwarehouseid.', '.$idline.', '.((int) $clonebatch).')">'.$langs->trans("Select")."</button>";
1462
1463 print '<tr><td class="left">'.$detail;
1464 $nbofsuggested++;
1465 print '</td></tr>';
1466 }
1467 }
1468 }
1469 }
1470 if ($nbofsuggested == 0) {
1471 print '<tr><td class="left">'.$langs->trans("NoRecordFound").'</td></tr>';
1472 }
1473
1474 // Add manual entry for returns or new batches
1475 print '<tr><td class="left" style="padding-top: 10px; border-top: 1px solid #ddd;">';
1476 print '<span class="opacitymedium">'.$langs->trans("LotSerial").' (Manual) :</span> ';
1477 print '<input type="text" id="manual_batch" class="flat" size="10"> ';
1478 print '<button class="button" onclick="updatebatch(document.getElementById(\'manual_batch\').value, '.$warehouseid.', '.$idline.', '.((int) $clonebatch).')">'.$langs->trans("Add").'</button>';
1479 print ' &nbsp; <button type="button" class="button button-cancel" onclick="$(\'#poslines\').load(\'invoice.php?place=\'+place+\'&invoiceid=\'+invoiceid);">'.$langs->trans("Cancel").'</button>';
1480 print '</td></tr>';
1481
1482 print "</table>";
1483 print '</div></body></html>';
1484 exit;
1485 }
1486
1487 if ($action == "setbatch" && ($user->hasRight('takepos', 'run') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE'))) {
1488 $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
1489 $warehouseid = (GETPOSTINT('warehouseid') > 0 ? GETPOSTINT('warehouseid') : getDolGlobalInt($constantforkey)); // Get the warehouse id from GETPOSTINT('warehouseid'), otherwise use default setup.
1490 $idline = (empty($idoflineadded) ? GETPOSTINT('idline') : $idoflineadded);
1491 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET batch = '".$db->escape($batch)."', fk_warehouse = ".((int) $warehouseid);
1492 $sql .= " WHERE rowid = ".((int) $idline)." AND fk_facture = ".((int) $placeid);
1493 $db->query($sql);
1494
1495 // Reload data
1496 $invoice->fetch($placeid);
1497
1498 if ($clonebatch && isModEnabled('productbatch') && isModEnabled('stock')) {
1499 $sql = 'SELECT fd.rowid, fd.fk_product';
1500 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet AS fd, '.MAIN_DB_PREFIX.'product AS p';
1501 $sql .= ' WHERE fd.fk_product = p.rowid';
1502 $sql .= ' AND fd.fk_facture = '.((int) $placeid);
1503 $sql .= " AND (fd.batch IS NULL OR fd.batch = '') AND p.tobatch > 0";
1504 $sql .= ' ORDER BY fd.rang, fd.rowid';
1505 $sql .= $db->plimit(1);
1506 $resql = $db->query($sql);
1507 if ($resql && ($obj = $db->fetch_object($resql))) {
1508 print '<script>editbatch('.((int) $obj->rowid).', '.((int) $obj->fk_product).', 1);</script>';
1509 exit;
1510 }
1511 }
1512 }
1513
1514 if ($action == "order" && $placeid != 0 && ($user->hasRight('takepos', 'run') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE'))) {
1515 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1516 if ((isModEnabled('receiptprinter') && getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0) || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter" || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") {
1517 require_once DOL_DOCUMENT_ROOT.'/takepos/class/dolreceiptprinter.class.php';
1518 $printer = new dolReceiptPrinter($db);
1519 }
1520
1521 $sql = "SELECT label FROM ".MAIN_DB_PREFIX."takepos_floor_tables where rowid = ".((int) $place);
1522 $resql = $db->query($sql);
1523 $row = $db->fetch_object($resql);
1524 $headerorder = '<html><br><b>'.$langs->trans('Place').' '.$row->label.'<br><table width="65%"><thead><tr><th class="left">'.$langs->trans("Label").'</th><th class="right">'.$langs->trans("Qty").'</th></tr></thead><tbody>';
1525 $footerorder = '</tbody></table>'.dol_print_date(dol_now(), 'dayhour').'<br></html>';
1526 $order_receipt_printer1 = "";
1527 $order_receipt_printer2 = "";
1528 $order_receipt_printer3 = "";
1529 $catsprinter1 = explode(';', getDolGlobalString('TAKEPOS_PRINTED_CATEGORIES_1'));
1530 $catsprinter2 = explode(';', getDolGlobalString('TAKEPOS_PRINTED_CATEGORIES_2'));
1531 $catsprinter3 = explode(';', getDolGlobalString('TAKEPOS_PRINTED_CATEGORIES_3'));
1532 $linestoprint = 0;
1533 foreach ($invoice->lines as $line) {
1534 if ($line->special_code == "4") {
1535 continue;
1536 }
1537 $c = new Categorie($db);
1538 $existing = $c->containing($line->fk_product, Categorie::TYPE_PRODUCT, 'id');
1539 $result = array_intersect($catsprinter1, $existing);
1540 $count = count($result);
1541 if (!$line->fk_product) {
1542 $count++; // Print Free-text item (Unassigned printer) to Printer 1
1543 }
1544 if ($count > 0) {
1545 $linestoprint++;
1546 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='1' where rowid = ".((int) $line->id); //Set to print on printer 1
1547 $db->query($sql);
1548 $order_receipt_printer1 .= '<tr><td class="left">';
1549 if ($line->fk_product) {
1550 $order_receipt_printer1 .= $line->product_label;
1551 } else {
1552 $order_receipt_printer1 .= $line->description;
1553 }
1554 $order_receipt_printer1 .= '</td><td class="right">'.$line->qty;
1555 if (!empty($line->array_options['options_order_notes'])) {
1556 $order_receipt_printer1 .= "<br>(".$line->array_options['options_order_notes'].")";
1557 }
1558 $order_receipt_printer1 .= '</td></tr>';
1559 }
1560 }
1561 if (((isModEnabled('receiptprinter') && getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0) || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter" || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && $linestoprint > 0 && $printer !== null) {
1562 $invoice->fetch($placeid); //Reload object before send to printer
1563 $printer->orderprinter = 1;
1564 echo "<script>";
1565 echo "var orderprinter1esc='";
1566 $ret = $printer->sendToPrinter($invoice, getDolGlobalInt('TAKEPOS_TEMPLATE_TO_USE_FOR_ORDERS'.$_SESSION["takeposterminal"]), getDolGlobalInt('TAKEPOS_ORDER_PRINTER1_TO_USE'.$_SESSION["takeposterminal"])); // PRINT TO PRINTER 1
1567 echo "';</script>";
1568 }
1569 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where special_code='1' and fk_facture = ".((int) $invoice->id); // Set as printed
1570 $db->query($sql);
1571 $invoice->fetch($placeid); //Reload object after set lines as printed
1572 $linestoprint = 0;
1573
1574 foreach ($invoice->lines as $line) {
1575 if ($line->special_code == "4") {
1576 continue;
1577 }
1578 $c = new Categorie($db);
1579 $existing = $c->containing($line->fk_product, Categorie::TYPE_PRODUCT, 'id');
1580 $result = array_intersect($catsprinter2, $existing);
1581 $count = count($result);
1582 if ($count > 0) {
1583 $linestoprint++;
1584 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='2' where rowid = ".((int) $line->id); //Set to print on printer 2
1585 $db->query($sql);
1586 $order_receipt_printer2 .= '<tr>'.$line->product_label.'<td class="right">'.$line->qty;
1587 if (!empty($line->array_options['options_order_notes'])) {
1588 $order_receipt_printer2 .= "<br>(".$line->array_options['options_order_notes'].")";
1589 }
1590 $order_receipt_printer2 .= '</td></tr>';
1591 }
1592 }
1593 if (((isModEnabled('receiptprinter') && getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0) || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter" || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && $linestoprint > 0) {
1594 $invoice->fetch($placeid); //Reload object before send to printer
1595 $printer->orderprinter = 2;
1596 echo "<script>";
1597 echo "var orderprinter2esc='";
1598 $ret = $printer->sendToPrinter($invoice, getDolGlobalInt('TAKEPOS_TEMPLATE_TO_USE_FOR_ORDERS'.$_SESSION["takeposterminal"]), getDolGlobalInt('TAKEPOS_ORDER_PRINTER2_TO_USE'.$_SESSION["takeposterminal"])); // PRINT TO PRINTER 2
1599 echo "';</script>";
1600 }
1601 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where special_code='2' and fk_facture = ".((int) $invoice->id); // Set as printed
1602 $db->query($sql);
1603 $invoice->fetch($placeid); //Reload object after set lines as printed
1604 $linestoprint = 0;
1605
1606 foreach ($invoice->lines as $line) {
1607 if ($line->special_code == "4") {
1608 continue;
1609 }
1610 $c = new Categorie($db);
1611 $existing = $c->containing($line->fk_product, Categorie::TYPE_PRODUCT, 'id');
1612 $result = array_intersect($catsprinter3, $existing);
1613 $count = count($result);
1614 if ($count > 0) {
1615 $linestoprint++;
1616 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='3' where rowid = ".((int) $line->id); //Set to print on printer 3
1617 $db->query($sql);
1618 $order_receipt_printer3 .= '<tr>'.$line->product_label.'<td class="right">'.$line->qty;
1619 if (!empty($line->array_options['options_order_notes'])) {
1620 $order_receipt_printer3 .= "<br>(".$line->array_options['options_order_notes'].")";
1621 }
1622 $order_receipt_printer3 .= '</td></tr>';
1623 }
1624 }
1625 if (((isModEnabled('receiptprinter') && getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0) || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter" || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && $linestoprint > 0 && $printer !== null) {
1626 $invoice->fetch($placeid); //Reload object before send to printer
1627 $printer->orderprinter = 3;
1628 echo "<script>";
1629 echo "var orderprinter3esc='";
1630 $ret = $printer->sendToPrinter($invoice, getDolGlobalInt('TAKEPOS_TEMPLATE_TO_USE_FOR_ORDERS'.$_SESSION["takeposterminal"]), getDolGlobalInt('TAKEPOS_ORDER_PRINTER3_TO_USE'.$_SESSION["takeposterminal"])); // PRINT TO PRINTER 3
1631 echo "';</script>";
1632 }
1633 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where special_code='3' and fk_facture = ".((int) $invoice->id); // Set as printed
1634 $db->query($sql);
1635 $invoice->fetch($placeid); //Reload object after set lines as printed
1636 }
1637
1638 $sectionwithinvoicelink = '';
1639 if (($action == "valid" || $action == "history" || $action == 'creditnote' || ($action == 'addline' && $invoice->status == $invoice::STATUS_CLOSED)) && $user->hasRight('takepos', 'run')) {
1640 $sectionwithinvoicelink .= '<!-- Section with invoice link -->'."\n";
1641 $sectionwithinvoicelink .= '<span style="font-size:120%;" class="center inline-block marginbottomonly">';
1642 if ($invoice->status == $invoice::STATUS_DRAFT) {
1643 $sectionwithinvoicelink .= $invoice->ref;
1644 } else {
1645 $sectionwithinvoicelink .= $invoice->getNomUrl(1, '', 0, 0, '', 0, 0, -1, '_backoffice');
1646 }
1647 $sectionwithinvoicelink .= " - ";
1648 $remaintopay = $invoice->getRemainToPay();
1649 if ($remaintopay > 0) {
1650 $sectionwithinvoicelink .= $langs->trans('RemainToPay').': <span class="amountremaintopay" style="font-size: unset">'.price($remaintopay, 1, $langs, 1, -1, -1, $conf->currency).'</span>';
1651 } else {
1652 $sectionwithinvoicelink .= $invoice->getLibStatut(2);
1653 }
1654
1655 $sectionwithinvoicelink .= '</span><br>';
1656
1657 $customprinterallowed = false;
1658 $customprinttemplateallowed = true;
1659
1660 // BAR RESTAURANT specific menu
1661 if (getDolGlobalString('TAKEPOS_BAR_RESTAURANT')) {
1662 // Button to print receipt before payment
1663 $customprinterallowed = true;
1664 $customprinttemplateallowed = true;
1665 }
1666
1667 include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/blockedlog.lib.php';
1668 if (isALNERunningVersion()) {
1669 // Custom printer may be allowed if mandatory information in template are guaranteed. For the moment, we prefer not allow this.
1670 $customprinttemplateallowed = false;
1671 }
1672
1673 if ($invoice->status == $invoice::STATUS_CLOSED) {
1674 if (getDolGlobalInt('TAKEPOS_PRINT_INVOICE_DOC_INSTEAD_OF_RECEIPT')) {
1675 $sectionwithinvoicelink .= ' <a target="_blank" class="button" href="' . DOL_URL_ROOT . '/document.php?token=' . newToken() . '&modulepart=facture&file=' . $invoice->ref . '/' . $invoice->ref . '.pdf">'.$langs->trans("Invoice").'</a>';
1676 } else {
1677 // This section should be same than into index.php
1678 if (getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") {
1679 // Used when the external addon takeposconnector is installed. Deprecated.
1680 if (getDolGlobalString('TAKEPOS_PRINT_SERVER') && filter_var(getDolGlobalString('TAKEPOS_PRINT_SERVER'), FILTER_VALIDATE_URL) == true) {
1681 // If TAKEPOS_PRINT_SERVER is an URL
1682 $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="PrintByESCPOSOld('.$placeid.')">'.$langs->trans('PrintTicket').'</button>';
1683 } else {
1684 // If TAKEPOS_PRINT_SERVER is an IP
1685 // Print by calling the receipt.php to get HTML content and send the HTML content to TAKEPOS_PRINT_SERVER:8111/print
1686 $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="PrintHTMLToSlashPrint('.$placeid.')">'.$langs->trans('PrintTicket').'</button>';
1687 }
1688 } elseif ($customprinterallowed && $customprinttemplateallowed && (isModEnabled('receiptprinter') && getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0) || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter") { // @phpstan-ignore-line
1689 // Button Print Receipt on special custom printer using custom template
1690 $nameOfPrinter = dol_getIdFromCode($db, getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term), 'printer_receipt', 'rowid', 'name', 1);
1691 $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="PrintByESCPOS('.$placeid.')" title="'.dolPrintHTMLForAttribute($langs->trans("SentToPrinter").' '.$nameOfPrinter).'">'.$langs->trans('PrintTicket').'</button>';
1692 } else {
1693 // Button Print Receipt on browser
1694 $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="PrintByBrowser('.$placeid.')">'.$langs->trans('PrintTicket').'</button>';
1695
1696 // Additional buttons
1697 if ($customprinttemplateallowed && getDolGlobalString('TAKEPOS_PRINT_WITHOUT_DETAILS')) {
1698 $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="PrintBox('.$placeid.', \'without_details\')">'.$langs->trans('PrintWithoutDetails').'</button>';
1699 }
1700 if ($customprinttemplateallowed && getDolGlobalString('TAKEPOS_GIFT_RECEIPT')) {
1701 $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="PrintByBrowser('.$placeid.', 1)">'.$langs->trans('GiftReceipt').'</button>';
1702 }
1703 }
1704 }
1705 if (getDolGlobalString('TAKEPOS_EMAIL_TEMPLATE_INVOICE') && getDolGlobalInt('TAKEPOS_EMAIL_TEMPLATE_INVOICE') > 0) {
1706 $sectionwithinvoicelink .= ' <button id="buttonsend" type="button" onclick="SendTicket('.$placeid.')">'.$langs->trans('SendTicket').'</button>';
1707 }
1708
1709 if ($remaintopay <= 0 && getDolGlobalString('TAKEPOS_AUTO_PRINT_TICKETS') && $action != "history") {
1710 $sectionwithinvoicelink .= '<script type="text/javascript">console.log("Emulate click on #buttonprint"); $("#buttonprint").click();</script>';
1711 }
1712 }
1713 }
1714}
1715
1716
1717/*
1718 * View
1719 */
1720
1721$form = new Form($db);
1722
1723// llxHeader
1724if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
1725 $title = 'TakePOS - Dolibarr '.DOL_VERSION;
1726 if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
1727 $title = 'TakePOS - ' . getDolGlobalString('MAIN_APPLICATION_TITLE');
1728 }
1729 $head = '<meta name="apple-mobile-web-app-title" content="TakePOS"/>
1730 <meta name="apple-mobile-web-app-capable" content="yes">
1731 <meta name="mobile-web-app-capable" content="yes">
1732 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>';
1733 $arrayofcss = array(
1734 '/takepos/css/pos.css.php',
1735 );
1736 $arrayofjs = array('/takepos/js/jquery.colorbox-min.js');
1737 $disablejs = 0;
1738 $disablehead = 0;
1739 top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1740
1741 print '<body>'."\n";
1742} else {
1743 top_httphead('text/html', 1);
1744}
1745
1746?>
1747<!-- invoice.php -->
1748<script type="text/javascript">
1749var selectedline=0;
1750var selectedtext="";
1751<?php if ($action == "valid") {
1752 echo "var place=0;";
1753}?> // Set to default place after close sale
1754var placeid=<?php echo($placeid > 0 ? $placeid : 0); ?>;
1755$(document).ready(function() {
1756 var idoflineadded = <?php echo(empty($idoflineadded) ? 0 : $idoflineadded); ?>;
1757
1758 $('.posinvoiceline').click(function(){
1759 console.log("Click done on "+this.id);
1760 $('.posinvoiceline').removeClass("selected");
1761 $(this).addClass("selected");
1762 if (!this.id) {
1763 return;
1764 }
1765 if (selectedline == this.id) {
1766 return; // If is already selected
1767 } else {
1768 selectedline = this.id;
1769 }
1770 selectedtext=$('#'+selectedline).find("td:first").html();
1771 <?php
1772 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
1773 print '$("#phonediv1").load("'.DOL_URL_ROOT.'/takepos/public/auto_order.php?action=editline&token='.newToken().'&placeid="+placeid+"&selectedline="+selectedline, function() {
1774 });';
1775 }
1776 ?>
1777 });
1778
1779 /* Autoselect the line */
1780 if (idoflineadded > 0)
1781 {
1782 console.log("Auto select "+idoflineadded);
1783 $('.posinvoiceline#'+idoflineadded).click();
1784 }
1785<?php
1786
1787if ($action == "order" && !empty($order_receipt_printer1)) {
1788 if (filter_var(getDolGlobalString('TAKEPOS_PRINT_SERVER'), FILTER_VALIDATE_URL) == true) {
1789 ?>
1790 $.ajax({
1791 type: "POST",
1792 url: '<?php print getDolGlobalString('TAKEPOS_PRINT_SERVER'); ?>/printer/index.php',
1793 data: 'invoice='+orderprinter1esc
1794 });
1795 <?php
1796 } else {
1797 ?>
1798 $.ajax({
1799 type: "POST",
1800 url: 'http://<?php print getDolGlobalString('TAKEPOS_PRINT_SERVER'); ?>:8111/print',
1801 data: '<?php
1802 print $headerorder.$order_receipt_printer1.$footerorder; ?>'
1803 });
1804 <?php
1805 }
1806}
1807
1808if ($action == "order" && !empty($order_receipt_printer2)) {
1809 if (filter_var(getDolGlobalString('TAKEPOS_PRINT_SERVER'), FILTER_VALIDATE_URL) == true) {
1810 ?>
1811 $.ajax({
1812 type: "POST",
1813 url: '<?php print getDolGlobalString('TAKEPOS_PRINT_SERVER'); ?>/printer/index.php?printer=2',
1814 data: 'invoice='+orderprinter2esc
1815 });
1816 <?php
1817 } else {
1818 ?>
1819 $.ajax({
1820 type: "POST",
1821 url: 'http://<?php print getDolGlobalString('TAKEPOS_PRINT_SERVER'); ?>:8111/print2',
1822 data: '<?php
1823 print $headerorder.$order_receipt_printer2.$footerorder; ?>'
1824 });
1825 <?php
1826 }
1827}
1828
1829if ($action == "order" && !empty($order_receipt_printer3)) {
1830 if (filter_var(getDolGlobalString('TAKEPOS_PRINT_SERVER'), FILTER_VALIDATE_URL) == true) {
1831 ?>
1832 $.ajax({
1833 type: "POST",
1834 url: '<?php print getDolGlobalString('TAKEPOS_PRINT_SERVER'); ?>/printer/index.php?printer=3',
1835 data: 'invoice='+orderprinter3esc
1836 });
1837 <?php
1838 }
1839}
1840
1841// Set focus to search field
1842if ($action == "search" || $action == "valid") {
1843 ?>
1844 parent.ClearSearch(true);
1845 <?php
1846}
1847
1848
1849if ($action == "search") {
1850 ?>
1851 $('#search').focus();
1852 <?php
1853}
1854
1855?>
1856
1857});
1858
1859function SendTicket(id)
1860{
1861 console.log("Open box to select the Print/Send form");
1862 $.colorbox({href:"send.php?facid="+id, width:"70%", height:"30%", transition:"none", iframe:"true", title:<?php echo "'".dol_escape_js($langs->trans("SendTicket"))."'" ; ?>});
1863 return true;
1864}
1865
1866/* Open the popup of the receipt to allow printing */
1867function PrintBox(id, action) {
1868 console.log("Open box before printing");
1869 $.colorbox({href:"printbox.php?facid="+id+"&action="+action+"&token=<?php echo newToken(); ?>", width:"80%", height:"200px", transition:"none", iframe:"true", title:"<?php echo $langs->trans("PrintWithoutDetails"); ?>"});
1870 return true;
1871}
1872
1873/* Open the popup of the receipt to allow printing */
1874function PrintByBrowser(id, gift) {
1875 console.log("Call PrintByBrowser() to generate the receipt.");
1876 $.colorbox({href:"receipt.php?facid="+id+"&gift="+gift, width:"40%", height:"90%", transition:"none", iframe:"true", title:<?php echo "'".dol_escape_js($langs->trans("PrintTicket"))."'" ; ?>});
1877 return true;
1878}
1879
1880/* Print of configured printer when TAKEPOS_PRINT_SERVER is IP */
1881function PrintHTMLToSlashPrint(id){
1882 var receipt;
1883 console.log("PrintHTMLToSlashPrint" + id);
1884 $.get("receipt.php?facid="+id, function(data, status) {
1885 receipt=data.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '');
1886 $.ajax({
1887 type: "POST",
1888 url: 'http://<?php print getDolGlobalString('TAKEPOS_PRINT_SERVER'); ?>:8111/print',
1889 data: receipt
1890 });
1891 });
1892 return true;
1893}
1894
1895/* Print of configured printer when TAKEPOS_PRINT_SERVER is URL, using the ESCPOS driver */
1896function PrintByESCPOSOld(id){
1897 console.log("PrintByESCPOSOld id=" + id);
1898 $.get("<?php echo DOL_URL_ROOT; ?>/takepos/ajax/ajax.php?action=printinvoiceticket&token=<?php echo currentToken(); ?>&term=<?php echo urlencode(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : ''); ?>&id="+id, function(data, status) {
1899 $.ajax({
1900 type: "POST",
1901 url: '<?php print getDolGlobalString('TAKEPOS_PRINT_SERVER'); ?>/printer/index.php',
1902 data: 'invoice='+data
1903 });
1904 });
1905 return true;
1906}
1907
1908<?php
1909$nameOfPrinter = dol_getIdFromCode($db, getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term), 'printer_receipt', 'rowid', 'name', 1);
1910?>
1911// Call the ajax to execute the printinvoiceticket action, using the ESCPOS driver
1912// With some external module another method may be called.
1913function PrintByESCPOS(id) {
1914 console.log("PrintByESCPOS Printing invoice ticket by calling takepos/aja/ajax.php id=" + id);
1915
1916 $.ajax({
1917 type: "GET",
1918 data: { token: '<?php echo currentToken(); ?>' },
1919 url: "<?php print DOL_URL_ROOT.'/takepos/ajax/ajax.php?action=printinvoiceticket&token='.currentToken().'&term='.urlencode(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '').'&id='; ?>" + id,
1920 success: function(){
1921 showPrintResultPopup(<?php echo "'".dol_escape_js($langs->trans("SentToPrinter").' '.$nameOfPrinter)."'" ; ?>, 2000);
1922 },
1923 error: function(){
1924 showPrintResultPopup(<?php echo "'".dol_escape_js($langs->trans("FailedToSendToPrinter"))."'" ; ?>, 2000);
1925 }
1926 });
1927 return true;
1928}
1929
1930// Show the message in div popup
1931function showPrintResultPopup(message, duration) {
1932 $("#dialogforpopuptakepos").show().text(message).fadeIn();
1933
1934 setTimeout(function(){
1935 $("#dialogforpopuptakepos").fadeOut().hide();
1936 }, duration);
1937}
1938
1939
1940
1941// Call url to generate a credit note (with same lines) from existing invoice
1942var creditNoteParams="";
1943function CreditNote() {
1944 <?php
1945 $parameters = array();
1946 $reshook = $hookmanager->executeHooks('paramsForCreditNote', $parameters, $invoice, $action);?>
1947 $("#poslines").load("<?php
1948 print DOL_URL_ROOT; ?>/takepos/invoice.php?action=creditnote&token=<?php echo newToken() ?>&invoiceid="+placeid+creditNoteParams, function() { });
1949 return true;
1950}
1951
1952
1953// Call url to add notes
1954function SetNote() {
1955 $("#poslines").load("<?php print DOL_URL_ROOT; ?>/takepos/invoice.php?action=addnote&token=<?php echo newToken() ?>&invoiceid="+placeid+"&idline="+selectedline, { "addnote": $("#textinput").val() });
1956 return true;
1957}
1958
1959
1960$( document ).ready(function() {
1961 console.log("Set customer info and sales in header placeid=<?php echo $placeid; ?> status=<?php echo $invoice->statut; ?>");
1962
1963 <?php
1964 $s = $langs->trans("Customer");
1965 if ($invoice->id > 0 && ($invoice->socid != getDolGlobalString($constforcompanyid))) {
1966 $s = $soc->name;
1967 if (getDolGlobalInt('TAKEPOS_CHOOSE_CONTACT')) {
1968 $contactids = $invoice->getIdContact('external', 'BILLING');
1969 $contactid = $contactids[0];
1970 if ($contactid > 0) {
1971 $contact = new Contact($db);
1972 $contact->fetch($contactid);
1973 $s .= " - " . $contact->getFullName($langs);
1974 }
1975 }
1976 } elseif (getDolGlobalInt("TAKEPOS_NO_GENERIC_THIRDPARTY")) {
1977 print '$("#idcustomer").val("");';
1978 }
1979 ?>
1980
1981 $("#customerandsales").html('');
1982 $("#shoppingcart").html('');
1983
1984 <?php if (getDolGlobalInt('TAKEPOS_CHOOSE_CONTACT') == 0) { ?>
1985 $("#customerandsales").append('<a class="valignmiddle tdoverflowmax100 minwidth100" id="customer" onclick="Customer();" title="<?php print dol_escape_js(dol_escape_htmltag((string) $s)); ?>"><span class="fas fa-building paddingrightonly"></span><?php print dol_escape_js((string) $s); ?></a>');
1986 <?php } else { ?>
1987 $("#customerandsales").append('<a class="valignmiddle tdoverflowmax300 minwidth100" id="contact" onclick="Contact();" title="<?php print dol_escape_js(dol_escape_htmltag((string) $s)); ?>"><span class="fas fa-building paddingrightonly"></span><?php print dol_escape_js((string) $s); ?></a>');
1988 <?php } ?>
1989
1990 <?php
1991 $sql = "SELECT rowid, datec, ref FROM ".MAIN_DB_PREFIX."facture";
1992 $sql .= " WHERE entity IN (".getEntity('invoice').")";
1993 if (!getDolGlobalString('TAKEPOS_CAN_EDIT_IF_ALREADY_VALIDATED')) {
1994 // By default, only invoices with a ref not already defined can in list of open invoice we can edit.
1995 $sql .= " AND ref LIKE '(PROV-POS".$db->escape(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '')."-0%'";
1996 } else {
1997 // If TAKEPOS_CAN_EDIT_IF_ALREADY_VALIDATED set, we show also draft invoice that already has a reference defined
1998 $sql .= " AND pos_source = '".$db->escape((string) $_SESSION["takeposterminal"])."'";
1999 $sql .= " AND module_source = 'takepos'";
2000 }
2001
2002 $sql .= $db->order('datec', 'ASC');
2003 $resql = $db->query($sql);
2004 if ($resql) {
2005 $max_sale = 0;
2006 while ($obj = $db->fetch_object($resql)) {
2007 $num_sale = str_replace(")", "", str_replace("(PROV-POS".$_SESSION["takeposterminal"]."-", "", $obj->ref));
2008 if (str_replace("-", "", $num_sale) > $max_sale) {
2009 $max_sale = str_replace("-", "", $num_sale);
2010 }
2011 // Build the HTML of the sale, then escape it once for the js string it is appended with
2012 $htmlsale = '<a class="valignmiddle" title="'.dol_escape_htmltag($langs->trans("SaleStartedAt", dol_print_date($db->jdate($obj->datec), '%H:%M', 'tzuser')).' - '.$obj->ref).'"';
2013 $htmlsale .= ' onclick="place=\''.$num_sale.'\'; invoiceid=\''.$obj->rowid.'\'; Refresh();">';
2014 $htmlsale .= '<span class="'.($placeid == $obj->rowid ? 'basketselected' : 'basketnotselected').'">';
2015 $htmlsale .= '<span class="fa fa-shopping-cart paddingright"></span>'.dol_print_date($db->jdate($obj->datec), '%H:%M', 'tzuser');
2016 $htmlsale .= '</span>';
2017 $htmlsale .= '</a>';
2018 echo '$("#shoppingcart").append(\''.dol_escape_js($htmlsale, 1).'\');';
2019 }
2020 echo '$("#shoppingcart").append(\'<a onclick="place=\\\'0-';
2021 echo $max_sale + 1;
2022 echo '\\\'; invoiceid=0; Refresh();"><div><span class="fa fa-plus" title="'.dol_escape_htmltag($langs->trans("StartAParallelSale")).'"><span class="fa fa-shopping-cart"></span></div></a>\');';
2023 } else {
2024 dol_print_error($db);
2025 }
2026
2027 $s = '';
2028
2029 $idwarehouse = 0;
2030 $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'. (isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
2031 if (isModEnabled('stock')) {
2032 if (getDolGlobalString($constantforkey) != "1") {
2033 $constantforkey = 'CASHDESK_ID_WAREHOUSE'. (isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
2034 $idwarehouse = getDolGlobalInt($constantforkey);
2035 if ($idwarehouse > 0) {
2036 $s = '<span class="small">';
2037 $warehouse = new Entrepot($db);
2038 $warehouse->fetch($idwarehouse);
2039 $s .= '<span class="hideonsmartphone">'.$langs->trans("Warehouse").'<br></span>'.$warehouse->ref;
2040 if ($warehouse->statut == Entrepot::STATUS_CLOSED) {
2041 $s .= ' ('.$langs->trans("Closed").')';
2042 }
2043 $s .= '</span>';
2044 print "$('#infowarehouse').html('".dol_escape_js($s)."');";
2045 print '$("#infowarehouse").css("display", "inline-block");';
2046 } else {
2047 $s = '<span class="small hideonsmartphone">';
2048 $s .= $langs->trans("StockChangeDisabled").'<br>'.$langs->trans("NoWarehouseDefinedForTerminal");
2049 $s .= '</span>';
2050 print "$('#infowarehouse').html('".dol_escape_js($s)."');";
2051 if (!empty($conf->dol_optimize_smallscreen)) {
2052 print '$("#infowarehouse").css("display", "none");';
2053 }
2054 }
2055 } else {
2056 $s = '<span class="small hideonsmartphone">'.$langs->trans("StockChangeDisabled").'</span>';
2057 print "$('#infowarehouse').html('".dol_escape_js($s)."');";
2058 if (!empty($conf->dol_optimize_smallscreen)) {
2059 print '$("#infowarehouse").css("display", "none");';
2060 }
2061 }
2062 }
2063
2064
2065 // Module Adherent
2066 $s = '';
2067 if (isModEnabled('member') && $invoice->socid > 0 && $invoice->socid != getDolGlobalInt($constforcompanyid)) {
2068 $s = '<span class="small">';
2069 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
2070 $langs->load("members");
2071 $s .= $langs->trans("Member").': ';
2072 $adh = new Adherent($db);
2073 $result = $adh->fetch(0, '', $invoice->socid);
2074 if ($result > 0) {
2075 $adh->ref = $adh->getFullName($langs);
2076 if (empty($adh->status) || $adh->status == Adherent::STATUS_EXCLUDED) {
2077 $s .= "<s>";
2078 }
2079 $s .= $adh->getFullName($langs);
2080 $s .= ' - '.$adh->type;
2081 if ($adh->datefin) {
2082 $s .= '<br>'.$langs->trans("SubscriptionEndDate").': '.dol_print_date($adh->datefin, 'day');
2083 if ($adh->hasDelay()) {
2084 $s .= " ".img_warning($langs->trans("Late"));
2085 }
2086 } else {
2087 $s .= '<br>'.$langs->trans("SubscriptionNotReceived");
2088 if ($adh->status > 0) {
2089 $s .= " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated
2090 }
2091 }
2092 if (empty($adh->status) || $adh->status == Adherent::STATUS_EXCLUDED) {
2093 $s .= "</s>";
2094 }
2095 } else {
2096 $s .= '<br>'.$langs->trans("ThirdpartyNotLinkedToMember");
2097 }
2098 $s .= '</span>';
2099 }
2100 ?>
2101 $("#moreinfo").html(<?php print "'".dol_escape_js($s)."'" ; ?>);
2102
2103});
2104
2105
2106<?php
2107if (getDolGlobalString('TAKEPOS_CUSTOMER_DISPLAY')) {
2108 echo "function CustomerDisplay(){";
2109 echo "var line1='".$CUSTOMER_DISPLAY_line1."'.substring(0,20);";
2110 echo "line1=line1.padEnd(20);";
2111 echo "var line2='".$CUSTOMER_DISPLAY_line2."'.substring(0,20);";
2112 echo "line2=line2.padEnd(20);";
2113 if (getDolGlobalString('TAKEPOS_CONNECTOR_TO_WHB_CUSTOMER_DISPLAY')) {
2114 echo 'webSocketCustomerDisplay.send(line1);';
2115 echo 'webSocketCustomerDisplay.send(line2);';
2116 } else {
2117 echo "$.ajax({
2118 type: 'GET',
2119 data: { text: line1+line2 },
2120 url: '".getDolGlobalString('TAKEPOS_PRINT_SERVER')."/display/index.php',
2121 });";
2122 }
2123 echo "}";
2124}
2125?>
2126
2127</script>
2128
2129
2130<?php
2131// Add again js for footer because this content is injected into index.php page so all init
2132// for tooltip and other js beautifiers must be reexecuted too.
2133if (!empty($conf->use_javascript_ajax)) {
2134 print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
2135 print '<script src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.'"></script>'."\n";
2136}
2137
2138$usediv = (GETPOST('format', 'aZ09') == 'div');
2139
2140print '<!-- invoice.php place='.(int) $place.' invoice='.$invoice->ref.' usediv='.json_encode($usediv).', mobilepage='.(empty($mobilepage) ? '' : $mobilepage).' $_SESSION["basiclayout"]='.(empty($_SESSION["basiclayout"]) ? '' : $_SESSION["basiclayout"]).' conf TAKEPOS_BAR_RESTAURANT='.getDolGlobalString('TAKEPOS_BAR_RESTAURANT').' -->'."\n";
2141print '<div class="div-table-responsive-no-min invoice">';
2142if ($usediv) {
2143 print '<div id="tablelines">';
2144} else {
2145 print '<table id="tablelines" class="noborder noshadow postablelines centpercent">';
2146}
2147
2148$buttontocreatecreditnote = '';
2149if (($action == "valid" || $action == "history" || $action == "addline")
2150 && $invoice->type != Facture::TYPE_CREDIT_NOTE && !getDolGlobalString('TAKEPOS_NO_CREDITNOTE') && $invoice->status == $invoice::STATUS_CLOSED) {
2151 $buttontocreatecreditnote .= ' &nbsp; <!-- Show button to create a credit note -->'."\n";
2152 $buttontocreatecreditnote .= '<button id="buttonprint" type="button" onclick="ModalBox(\'ModalCreditNote\')">'.$langs->trans('CreateCreditNote').'</button>';
2153 if (getDolGlobalInt('TAKEPOS_PRINT_INVOICE_DOC_INSTEAD_OF_RECEIPT')) {
2154 $buttontocreatecreditnote .= ' <a target="_blank" class="button" href="' . DOL_URL_ROOT . '/document.php?token=' . newToken() . '&modulepart=facture&file=' . urlencode($invoice->ref . '/' . $invoice->ref . '.pdf').'">'.$langs->trans("Invoice").'</a>';
2155 }
2156}
2157
2158$buttontocloneticket = '';
2159if (($action == 'valid' || $action == 'history' || $action == 'addline') && in_array($invoice->status, array(Facture::STATUS_VALIDATED, Facture::STATUS_CLOSED)) && $invoice->type != Facture::TYPE_CREDIT_NOTE) {
2160 $buttontocloneticket .= ' &nbsp;<button id="buttonclone" type="button" onclick="CloneTicket('.((int) $invoice->id).')">'.$langs->trans('CloneTicket').'</button>';
2161}
2162
2163// Show the ref of invoice
2164if ($sectionwithinvoicelink && ($mobilepage == "invoice" || $mobilepage == "")) {
2165 print '<!-- Print table line with link to invoice ref -->';
2166 if (getDolGlobalString('TAKEPOS_SHOW_HT')) {
2167 print '<tr><td colspan="5" class="paddingtopimp paddingbottomimp" style="padding-top: 10px !important; padding-bottom: 10px !important;">';
2168 print $sectionwithinvoicelink;
2169 print $buttontocreatecreditnote;
2170 print $buttontocloneticket;
2171 print '</td></tr>';
2172 } else {
2173 print '<tr><td colspan="4" class="paddingtopimp paddingbottomimp" style="padding-top: 10px !important; padding-bottom: 10px !important;">';
2174 print $sectionwithinvoicelink;
2175 print $buttontocreatecreditnote;
2176 print $buttontocloneticket;
2177 print '</td></tr>';
2178 }
2179}
2180
2181// Show the list of selected product
2182if (!$usediv) {
2183 print '<tr class="liste_titre nodrag nodrop">';
2184 print '<td class="linecoldescription">';
2185}
2186// In phone version only show when it is invoice page
2187if (empty($mobilepage) || $mobilepage == "invoice") {
2188 print '<!-- hidden var used by some js functions -->';
2189 print '<input type="hidden" name="invoiceid" id="invoiceid" value="'.$invoice->id.'">';
2190 print '<input type="hidden" name="thirdpartyid" id="thirdpartyid" value="'.$invoice->socid.'">';
2191}
2192if (!$usediv) {
2193 if (getDolGlobalString('TAKEPOS_BAR_RESTAURANT')) {
2194 $sql = "SELECT floor, label FROM ".MAIN_DB_PREFIX."takepos_floor_tables where rowid = ".((int) $place);
2195 $resql = $db->query($sql);
2196 $obj = $db->fetch_object($resql);
2197 if ($obj) {
2198 $label = $obj->label;
2199 $floor = $obj->floor;
2200 }
2201 if ($mobilepage == "invoice" || $mobilepage == "") {
2202 // If not on smartphone version or if it is the invoice page
2203 //print 'mobilepage='.$mobilepage;
2204 print '<span class="opacitymedium">'.$langs->trans('Place')."</span> <b>".(empty($label) ? '?' : $label)."</b><br>";
2205 print '<span class="opacitymedium">'.$langs->trans('Floor')."</span> <b>".(empty($floor) ? '?' : $floor)."</b>";
2206 }
2207 }
2208 print '</td>';
2209}
2210
2211// Complete header by hook
2212$parameters = array();
2213$reshook = $hookmanager->executeHooks('completeTakePosInvoiceHeader', $parameters, $invoice, $action); // Note that $action and $object may have been modified by some hooks
2214if ($reshook < 0) {
2215 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2216}
2217print $hookmanager->resPrint;
2218
2219if (empty($_SESSION["basiclayout"]) || $_SESSION["basiclayout"] != 1) {
2220 if (getDolGlobalInt("TAKEPOS_SHOW_SUBPRICE")) {
2221 print '<td class="linecolqty right">'.$langs->trans('PriceUHT').'</td>';
2222 }
2223 print '<td class="linecolqty right">'.$langs->trans('ReductionShort').'</td>';
2224 print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
2225 if (getDolGlobalString('TAKEPOS_SHOW_HT')) {
2226 print '<td class="linecolht right nowraponall">';
2227 print '<span class="opacitymedium small">' . $langs->trans('TotalHTShort') . '</span><br>';
2228 // In phone version only show when it is invoice page
2229 if (empty($mobilepage) || $mobilepage == "invoice") {
2230 print '<span id="linecolht-span-total" style="font-size:1.3em; font-weight: bold;">' . price($invoice->total_ht, 1, '', 1, -1, -1, $conf->currency) . '</span>';
2231 if (isModEnabled('multicurrency') && !empty($_SESSION["takeposcustomercurrency"]) && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
2232 //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
2233 include_once DOL_DOCUMENT_ROOT . '/multicurrency/class/multicurrency.class.php';
2234 $multicurrency = new MultiCurrency($db);
2235 $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
2236 print '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">(' . price($invoice->total_ht * $multicurrency->rate->rate) . ' ' . $_SESSION["takeposcustomercurrency"] . ')</span>';
2237 }
2238 }
2239 print '</td>';
2240 }
2241 print '<td class="linecolht right nowraponall">';
2242 print '<span class="opacitymedium small">'.$langs->trans('TotalTTCShort').'</span><br>';
2243 // In phone version only show when it is invoice page
2244 if (empty($mobilepage) || $mobilepage == "invoice") {
2245 print '<span id="linecolht-span-total" style="font-size:1.3em; font-weight: bold;">'.price($invoice->total_ttc, 1, '', 1, -1, -1, $conf->currency).'</span>';
2246 if (isModEnabled('multicurrency') && !empty($_SESSION["takeposcustomercurrency"]) && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
2247 //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
2248 include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
2249 $multicurrency = new MultiCurrency($db);
2250 $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
2251 print '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">('.price($invoice->total_ttc * $multicurrency->rate->rate).' '.$_SESSION["takeposcustomercurrency"].')</span>';
2252 }
2253 }
2254 print '</td>';
2255} elseif ($mobilepage == "invoice") {
2256 print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
2257}
2258if (!$usediv) {
2259 print "</tr>\n";
2260}
2261
2262if (!empty($_SESSION["basiclayout"]) && $_SESSION["basiclayout"] == 1) {
2263 if ($mobilepage == "cats") {
2264 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2265 $categorie = new Categorie($db);
2266 $categories = $categorie->get_full_arbo('product');
2267 $htmlforlines = '';
2268 foreach ($categories as $row) {
2269 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
2270 $htmlforlines .= '<div class="leftcat"';
2271 } else {
2272 $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline"';
2273 }
2274 $htmlforlines .= ' onclick="LoadProducts('.$row['id'].');">';
2275 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
2276 $htmlforlines .= '<img class="imgwrapper" width="33%" src="'.DOL_URL_ROOT.'/takepos/public/auto_order.php?genimg=cat&query=cat&id='.$row['id'].'"><br>';
2277 } else {
2278 $htmlforlines .= '<td class="left">';
2279 }
2280 $htmlforlines .= $row['label'];
2281 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
2282 $htmlforlines .= '</div>'."\n";
2283 } else {
2284 $htmlforlines .= '</td></tr>'."\n";
2285 }
2286 }
2287 print $htmlforlines;
2288 }
2289
2290 if ($mobilepage == "products") {
2291 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2292 $object = new Categorie($db);
2293 $catid = GETPOSTINT('catid');
2294 $result = $object->fetch($catid);
2295 $prods = $object->getObjectsInCateg("product");
2297 '@phan-var-force Product[] $prods';
2298 $htmlforlines = '';
2299 foreach ($prods as $row) {
2300 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
2301 $htmlforlines .= '<div class="leftcat"';
2302 } else {
2303 $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline"';
2304 }
2305 $htmlforlines .= ' onclick="AddProduct(\''.$place.'\', '.$row->id.')"';
2306 $htmlforlines .= '>';
2307 if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
2308 $htmlforlines .= '<img class="imgwrapper" width="33%" src="'.DOL_URL_ROOT.'/takepos/public/auto_order.php?genimg=pro&query=pro&id='.$row->id.'"><br>';
2309 $htmlforlines .= $row->label.' '.price($row->price_ttc, 1, $langs, 1, -1, -1, $conf->currency);
2310 $htmlforlines .= '</div>'."\n";
2311 } else {
2312 $htmlforlines .= '<td class="left">';
2313 $htmlforlines .= $row->label;
2314 $htmlforlines .= '<div class="right">'.price($row->price_ttc, 1, $langs, 1, -1, -1, $conf->currency).'</div>';
2315 $htmlforlines .= '</td>';
2316 $htmlforlines .= '</tr>'."\n";
2317 }
2318 }
2319 print $htmlforlines;
2320 }
2321
2322 if ($mobilepage == "places") {
2323 $sql = "SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables";
2324 $resql = $db->query($sql);
2325
2326 $rows = array();
2327 $htmlforlines = '';
2328 while ($row = $db->fetch_array($resql)) {
2329 $rows[] = $row;
2330 $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline';
2331 $htmlforlines .= '" onclick="LoadPlace(\''.$row['label'].'\')">';
2332 $htmlforlines .= '<td class="left">';
2333 $htmlforlines .= $row['label'];
2334 $htmlforlines .= '</td>';
2335 $htmlforlines .= '</tr>'."\n";
2336 }
2337 print $htmlforlines;
2338 }
2339}
2340
2341if ($placeid > 0) {
2342 //In Phone basic layout hide some content depends situation
2343 if (!empty($_SESSION["basiclayout"]) && $_SESSION["basiclayout"] == 1 && $mobilepage != "invoice" && $action != "order") {
2344 return;
2345 }
2346
2347 // Loop on each lines on invoice
2348 if (is_array($invoice->lines) && count($invoice->lines)) {
2349 print '<!-- invoice.php show lines of invoices -->'."\n";
2350 $tmplines = array_reverse($invoice->lines);
2351 $htmlsupplements = array();
2352 foreach ($tmplines as $line) {
2353 if ($line->fk_parent_line != false) {
2354 if (!isset($htmlsupplements[$line->fk_parent_line])) {
2355 $htmlsupplements[$line->fk_parent_line] = '';
2356 }
2357 $htmlsupplements[$line->fk_parent_line] .= '<tr class="drag drop oddeven posinvoiceline';
2358 if ($line->special_code == "4") {
2359 $htmlsupplements[$line->fk_parent_line] .= ' order';
2360 }
2361 $htmlsupplements[$line->fk_parent_line] .= '" id="'.$line->id.'"';
2362 if ($line->special_code == "4") {
2363 $htmlsupplements[$line->fk_parent_line] .= ' title="'.dol_escape_htmltag($langs->trans("AlreadyPrinted")).'"';
2364 }
2365 $htmlsupplements[$line->fk_parent_line] .= '>';
2366 $htmlsupplements[$line->fk_parent_line] .= '<td class="left">';
2367 $htmlsupplements[$line->fk_parent_line] .= img_picto('', 'rightarrow.png');
2368 if ($line->product_label) {
2369 $htmlsupplements[$line->fk_parent_line] .= $line->product_label;
2370 }
2371 if ($line->product_label && $line->desc) {
2372 $htmlsupplements[$line->fk_parent_line] .= '<br>';
2373 }
2374 if ($line->product_label != $line->desc) {
2375 $firstline = dolGetFirstLineOfText($line->desc);
2376 if ($firstline != $line->desc) {
2377 $htmlsupplements[$line->fk_parent_line] .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc);
2378 } else {
2379 $htmlsupplements[$line->fk_parent_line] .= $line->desc;
2380 }
2381 }
2382 $htmlsupplements[$line->fk_parent_line] .= '</td>';
2383
2384 // complete line by hook
2385 $parameters = array('line' => $line);
2386 $reshook = $hookmanager->executeHooks('completeTakePosInvoiceParentLine', $parameters, $invoice, $action); // Note that $action and $object may have been modified by some hooks
2387 if ($reshook < 0) {
2388 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2389 }
2390 $htmlsupplements[$line->fk_parent_line] .= $hookmanager->resPrint;
2391
2392 if (empty($_SESSION["basiclayout"]) || $_SESSION["basiclayout"] != 1) {
2393 $htmlsupplements[$line->fk_parent_line] .= '<td class="right">'.vatrate(price2num($line->remise_percent), true).'</td>';
2394 $htmlsupplements[$line->fk_parent_line] .= '<td class="right">'.$line->qty.'</td>';
2395 $htmlsupplements[$line->fk_parent_line] .= '<td class="right">'.price($line->total_ttc).'</td>';
2396 }
2397 $htmlsupplements[$line->fk_parent_line] .= '</tr>'."\n";
2398 continue;
2399 }
2400 $htmlforlines = '';
2401
2402 $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline';
2403 if ($line->special_code == "4") {
2404 $htmlforlines .= ' order';
2405 }
2406 $htmlforlines .= '" id="'.$line->id.'"';
2407 if ($line->special_code == "4") {
2408 $htmlforlines .= ' title="'.dol_escape_htmltag($langs->trans("AlreadyPrinted")).'"';
2409 }
2410 $htmlforlines .= '>';
2411 $htmlforlines .= '<td class="left">';
2412 if (!empty($_SESSION["basiclayout"]) && $_SESSION["basiclayout"] == 1) {
2413 $htmlforlines .= '<span class="phoneqty">'.$line->qty."</span> x ";
2414 }
2415 if (isset($line->product_type)) {
2416 if (empty($line->product_type)) {
2417 $htmlforlines .= img_object('', 'product').' ';
2418 } else {
2419 $htmlforlines .= img_object('', 'service').' ';
2420 }
2421 }
2422 $tooltiptext = '';
2423 if (!getDolGlobalString('TAKEPOS_SHOW_N_FIRST_LINES')) {
2424 if ($line->product_ref) {
2425 $tooltiptext .= '<b>'.$langs->trans("Ref").'</b> : '.$line->product_ref.'<br>';
2426 $tooltiptext .= '<b>'.$langs->trans("Label").'</b> : '.$line->product_label.'<br>';
2427 if (!empty($line->batch)) {
2428 $tooltiptext .= '<br><b>'.$langs->trans("LotSerial").'</b> : '.$line->batch.'<br>';
2429 }
2430 if (!empty($line->fk_warehouse)) {
2431 $tooltiptext .= '<b>'.$langs->trans("Warehouse").'</b> : '.$line->fk_warehouse.'<br>';
2432 }
2433 if ($line->product_label != $line->desc) {
2434 if ($line->desc) {
2435 $tooltiptext .= '<br>';
2436 }
2437 $tooltiptext .= $line->desc;
2438 }
2439 }
2440 if (getDolGlobalInt('TAKEPOS_SHOW_PRODUCT_REFERENCE') == 1) {
2441 $htmlforlines .= $form->textwithpicto($line->product_label ? '<b>' . $line->product_ref . '</b> - ' . $line->product_label : dolGetFirstLineOfText($line->desc, 1), $tooltiptext);
2442 } elseif (getDolGlobalInt('TAKEPOS_SHOW_PRODUCT_REFERENCE') == 2) {
2443 $htmlforlines .= $form->textwithpicto($line->product_ref ? '<b>'.$line->product_ref.'<b>' : dolGetFirstLineOfText($line->desc, 1), $tooltiptext);
2444 } else {
2445 $htmlforlines .= $form->textwithpicto($line->product_label ? $line->product_label : ($line->product_ref ? $line->product_ref : dolGetFirstLineOfText($line->desc, 1)), $tooltiptext);
2446 }
2447 } else {
2448 if ($line->product_ref) {
2449 $tooltiptext .= '<b>'.$langs->trans("Ref").'</b> : '.$line->product_ref.'<br>';
2450 $tooltiptext .= '<b>'.$langs->trans("Label").'</b> : '.$line->product_label.'<br>';
2451 }
2452 if (!empty($line->batch)) {
2453 $tooltiptext .= '<br><b>'.$langs->trans("LotSerial").'</b> : '.$line->batch.'<br>';
2454 }
2455 if (!empty($line->fk_warehouse)) {
2456 $tooltiptext .= '<b>'.$langs->trans("Warehouse").'</b> : '.$line->fk_warehouse.'<br>';
2457 }
2458
2459 if ($line->product_label) {
2460 $htmlforlines .= $line->product_label;
2461 }
2462 if ($line->product_label != $line->desc) {
2463 if ($line->product_label && $line->desc) {
2464 $htmlforlines .= '<br>';
2465 }
2466 $firstline = dolGetFirstLineOfText($line->desc, getDolGlobalInt('TAKEPOS_SHOW_N_FIRST_LINES'));
2467 if ($firstline != $line->desc) {
2468 $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc);
2469 } else {
2470 $htmlforlines .= $line->desc;
2471 }
2472 }
2473 }
2474 if (!empty($line->array_options['options_order_notes'])) {
2475 $htmlforlines .= "<br>(".$line->array_options['options_order_notes'].")";
2476 }
2477 if (isModEnabled('productbatch') && $line->fk_product > 0) {
2478 if (!is_object($line->product) || !($line->product->id > 0)) {
2479 $line->fetch_product();
2480 }
2481
2482 if (is_object($line->product) && $line->product->status_batch > 0) {
2483 $batch_display = empty($line->batch) ? $langs->trans("NotDefined") : dol_escape_htmltag($line->batch);
2484 $htmlforlines .= '<br><span class="opacitymedium">'.$langs->trans("LotSerial").' : '.$batch_display.'</span>';
2485 // Only show edit button if invoice is a Draft (status == 0)
2486 if ($invoice->status == Facture::STATUS_DRAFT) {
2487 $htmlforlines .= ' <a href="#" onclick="editbatch('.$line->id.', '.$line->fk_product.'); return false;" title="'.dol_escape_htmltag($langs->trans("Modify")).'">'.img_edit().'</a>';
2488 }
2489 }
2490 }
2491 if (!empty($_SESSION["basiclayout"]) && $_SESSION["basiclayout"] == 1) {
2492 $htmlforlines .= '</td><td class="right phonetable"><button type="button" onclick="SetQty(place, '.$line->rowid.', '.($line->qty - 1).');" class="publicphonebutton2 phonered">-</button>&nbsp;&nbsp;<button type="button" onclick="SetQty(place, '.$line->rowid.', '.($line->qty + 1).');" class="publicphonebutton2 phonegreen">+</button>';
2493 }
2494 if (empty($_SESSION["basiclayout"]) || $_SESSION["basiclayout"] != 1) {
2495 // Set the content of tooltip
2496 $moreinfo = '';
2497 $moreinfo .= $langs->trans("VATRate").': '.price($line->tva_tx).' %<br>';
2498 $moreinfo .= $langs->trans("UnitPrice").': '.price($line->subprice).'<br>';
2499 $moreinfo .= '<br>';
2500 $moreinfo .= $langs->transcountry("TotalHT", $mysoc->country_code).': '.price($line->total_ht);
2501 if ($line->vat_src_code) {
2502 $moreinfo .= '<br>'.$langs->trans("VATCode").': '.$line->vat_src_code;
2503 }
2504 $moreinfo .= '<br>'.$langs->trans("TotalVAT").': '.price($line->total_tva);
2505 if ($mysoc->useLocalTax(1, 1, $mysoc)) {
2506 $moreinfo .= '<br>'.$langs->transcountry("TotalLT1", $mysoc->country_code).': '.price($line->total_localtax1);
2507 }
2508 if ($mysoc->useLocalTax(2, 1, $mysoc)) {
2509 $moreinfo .= '<br>'.$langs->transcountry("TotalLT2", $mysoc->country_code).': '.price($line->total_localtax2);
2510 }
2511 $moreinfo .= '<hr>';
2512 $moreinfo .= $langs->transcountry("TotalTTC", $mysoc->country_code).': '.price($line->total_ttc);
2513 //$moreinfo .= $langs->trans("TotalHT").': '.$line->total_ht;
2514 if ($line->date_start || $line->date_end) {
2515 $htmlforlines .= '<br><div class="clearboth nowraponall">'.get_date_range($line->date_start, $line->date_end).'</div>';
2516 }
2517 $htmlforlines .= '</td>';
2518
2519 // complete line by hook
2520 $parameters = array('line' => $line);
2521 $reshook = $hookmanager->executeHooks('completeTakePosInvoiceLine', $parameters, $invoice, $action); // Note that $action and $object may have been modified by some hooks
2522 if ($reshook < 0) {
2523 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2524 }
2525 $htmlforlines .= $hookmanager->resPrint;
2526
2527 if (getDolGlobalInt("TAKEPOS_SHOW_SUBPRICE")) {
2528 $htmlforlines .= '<td class="right">'.price($line->subprice).'</td>';
2529 }
2530 $htmlforlines .= '<td class="right">'.vatrate(price2num($line->remise_percent), true).'</td>';
2531 // nowraponall keeps the qty and its '(stock)' block on one line: on narrow layouts
2532 // the native display otherwise wraps over three lines inside the qty column.
2533 $htmlforlines .= '<td class="right nowraponall">';
2534 $htmlforlines .= $line->qty;
2535 if (isModEnabled('stock') && $user->hasRight('stock', 'mouvement', 'lire')) {
2536 $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
2537 if (getDolGlobalString($constantforkey) && $line->fk_product > 0 && !getDolGlobalString('TAKEPOS_HIDE_STOCK_ON_LINE')) {
2538 $productChildrenNb = 0;
2539 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
2540 if (!is_object($line->product) || !($line->product->id > 0)) {
2541 $line->fetch_product();
2542 }
2543 if (is_object($line->product)) {
2544 $productChildrenNb = $line->product->hasFatherOrChild(1);
2545 }
2546 }
2547 if ($productChildrenNb == 0) {
2548 $sql = "SELECT e.rowid, e.ref, e.lieu, e.fk_parent, e.statut, ps.reel, ps.rowid as product_stock_id, p.pmp";
2549 $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,";
2550 $sql .= " ".MAIN_DB_PREFIX."product_stock as ps";
2551 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = ps.fk_product";
2552 $sql .= " WHERE ps.reel != 0";
2553 $sql .= " AND ps.fk_entrepot = ".((int) getDolGlobalString($constantforkey));
2554 $sql .= " AND e.entity IN (".getEntity('stock').")";
2555 $sql .= " AND ps.fk_product = ".((int) $line->fk_product);
2556 $resql = $db->query($sql);
2557 if ($resql) {
2558 $stock_real = 0;
2559 $obj = $db->fetch_object($resql);
2560 if ($obj) {
2561 $stock_real = price2num($obj->reel, 'MS');
2562 }
2563 $htmlforlines .= '&nbsp; ';
2564 $htmlforlines .= '<span class="opacitylow" title="'.$langs->trans("Stock").' '.price($stock_real, 1, '', 1, 0).'">';
2565 $htmlforlines .= '(';
2566 if ($line->qty && $line->qty > $stock_real) {
2567 $htmlforlines .= '<span style="color: var(--amountremaintopaycolor)">';
2568 }
2569 $htmlforlines .= img_picto('', 'stock', 'class="pictofixedwidth"').price($stock_real, 1, '', 1, 0);
2570 if ($line->qty && $line->qty > $stock_real) {
2571 $htmlforlines .= "</span>";
2572 }
2573 $htmlforlines .= ')';
2574 $htmlforlines .= '</span>';
2575 } else {
2576 dol_print_error($db);
2577 }
2578 }
2579 }
2580 }
2581
2582 $htmlforlines .= '</td>';
2583 if (getDolGlobalInt('TAKEPOS_SHOW_HT')) {
2584 $htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">';
2585 $htmlforlines .= price($line->total_ht, 1, '', 1, -1, -1, $conf->currency);
2586 if (isModEnabled('multicurrency') && !empty($_SESSION["takeposcustomercurrency"]) && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
2587 //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
2588 include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
2589 $multicurrency = new MultiCurrency($db);
2590 $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
2591 $htmlforlines .= '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">('.price($line->total_ht * $multicurrency->rate->rate).' '.$_SESSION["takeposcustomercurrency"].')</span>';
2592 }
2593 $htmlforlines .= '</td>';
2594 }
2595 $htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">';
2596 $htmlforlines .= price($line->total_ttc, 1, '', 1, -1, -1, $conf->currency);
2597 if (isModEnabled('multicurrency') && !empty($_SESSION["takeposcustomercurrency"]) && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
2598 //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
2599 include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
2600 $multicurrency = new MultiCurrency($db);
2601 $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
2602 $htmlforlines .= '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">('.price($line->total_ttc * $multicurrency->rate->rate).' '.$_SESSION["takeposcustomercurrency"].')</span>';
2603 }
2604 $htmlforlines .= '</td>';
2605 }
2606 $htmlforlines .= '</tr>'."\n";
2607 $htmlforlines .= empty($htmlsupplements[$line->id]) ? '' : $htmlsupplements[$line->id];
2608
2609 print $htmlforlines;
2610 }
2611 } else {
2612 print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td>';
2613 if (empty($_SESSION["basiclayout"]) || $_SESSION["basiclayout"] != 1) {
2614 print '<td></td><td></td>';
2615 if (getDolGlobalString('TAKEPOS_SHOW_HT')) {
2616 print '<td></td>';
2617 }
2618 }
2619 print '</tr>';
2620 }
2621} else { // No invoice generated yet
2622 print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td>';
2623 if (empty($_SESSION["basiclayout"]) || $_SESSION["basiclayout"] != 1) {
2624 print '<td></td><td></td>';
2625 if (getDolGlobalString('TAKEPOS_SHOW_HT')) {
2626 print '<td></td>';
2627 }
2628 }
2629 print '</tr>';
2630}
2631
2632if ($usediv) {
2633 print '</div>';
2634} else {
2635 print '</table>';
2636}
2637
2638if ($action == "search") {
2639 print '<center>
2640 <input type="text" id="search" class="input-nobottom" name="search" onkeyup="Search2(\'\', null);" style="width: 80%; font-size: 150%;" placeholder="'.dol_escape_htmltag($langs->trans('Search')).'">
2641 </center>';
2642}
2643
2644print '</div>';
2645
2646// llxFooter
2647if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
2648 print '</body></html>';
2649}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
$c
Definition line.php:353
isALNERunningVersion($blockedlogusagealreadychecked=0, $blockedlogmoduleonalreadychecked=0)
Return if the application is executed with the LNE requirements on.
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 members of a foundation.
const STATUS_EXCLUDED
Excluded.
Class to manage categories.
Class to manage contact/addresses.
Class to manage absolute discounts.
Class to manage warehouses.
const STATUS_CLOSED
Warehouse closed, inactive.
Class to manage invoices.
const STATUS_DRAFT
Draft status.
const STATUS_VALIDATED
Validated (need to be paid)
const TYPE_CREDIT_NOTE
Credit note invoice.
const STATUS_CLOSED
Classified paid.
Class to manage generation of HTML components Only common components must be here.
Class to manage stock movements.
Class Currency.
Class to manage payments of customer invoices.
Class to manage predefined suppliers products.
Class to manage products or services.
Manage record for batch number management.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Receipt Printers.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
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...
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
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.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
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.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_htmloutput_mesg($mesgstring='', $mesgarray=array(), $style='ok', $keepembedded=0)
Print formatted messages to output (Used to show messages on html output).
dol_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
Print formatted error messages to output (Used to show messages on html output).
top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs=array(), $arrayofcss=array(), $disableforlogin=0, $disablenofollow=0, $disablenoindex=0)
Output html header of a page.
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
if(empty( $takeposterminal)) fail($message)
Abort invoice creation with a given error message.
Definition invoice.php:125
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button