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