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