invoice.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  1. <?php
  2. /**
  3. * Copyright (C) 2018 Andreu Bisquerra <jove@bisquerra.com>
  4. * Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com>
  5. * Copyright (C) 2022-2023 Christophe Battarel <christophe.battarel@altairis.fr>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. /**
  21. * \file htdocs/takepos/invoice.php
  22. * \ingroup takepos
  23. * \brief Page to generate section with list of lines
  24. */
  25. // if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Not disabled cause need to load personalized language
  26. // if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Not disabled cause need to load personalized language
  27. // if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1');
  28. // if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1');
  29. if (!defined('NOTOKENRENEWAL')) {
  30. define('NOTOKENRENEWAL', '1');
  31. }
  32. if (!defined('NOREQUIREMENU')) {
  33. define('NOREQUIREMENU', '1');
  34. }
  35. if (!defined('NOREQUIREHTML')) {
  36. define('NOREQUIREHTML', '1');
  37. }
  38. if (!defined('NOREQUIREAJAX')) {
  39. define('NOREQUIREAJAX', '1');
  40. }
  41. // Load Dolibarr environment
  42. if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  43. require '../main.inc.php';
  44. }
  45. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  46. require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  47. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  48. require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  49. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  50. $hookmanager->initHooks(array('takeposinvoice'));
  51. $langs->loadLangs(array("companies", "commercial", "bills", "cashdesk", "stocks", "banks"));
  52. $action = GETPOST('action', 'aZ09');
  53. $idproduct = GETPOST('idproduct', 'int');
  54. $place = (GETPOST('place', 'aZ09') ? GETPOST('place', 'aZ09') : 0); // $place is id of table for Bar or Restaurant
  55. $placeid = 0; // $placeid is ID of invoice
  56. $mobilepage = GETPOST('mobilepage', 'alpha');
  57. // Terminal is stored into $_SESSION["takeposterminal"];
  58. if (!$user->hasRight('takepos', 'run') && !defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  59. accessforbidden();
  60. }
  61. if ((getDolGlobalString('TAKEPOS_PHONE_BASIC_LAYOUT') == 1 && $conf->browser->layout == 'phone') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  62. // DIRECT LINK TO THIS PAGE FROM MOBILE AND NO TERMINAL SELECTED
  63. if ($_SESSION["takeposterminal"] == "") {
  64. if (getDolGlobalString('TAKEPOS_NUM_TERMINALS') == "1") {
  65. $_SESSION["takeposterminal"] = 1;
  66. } else {
  67. header("Location: ".DOL_URL_ROOT."/takepos/index.php");
  68. exit;
  69. }
  70. }
  71. }
  72. /**
  73. * Abort invoice creationg with a given error message
  74. *
  75. * @param string $message Message explaining the error to the user
  76. * @return void
  77. */
  78. function fail($message)
  79. {
  80. header($_SERVER['SERVER_PROTOCOL'].' 500 Internal Server Error', true, 500);
  81. die($message);
  82. }
  83. $number = GETPOST('number', 'alpha');
  84. $idline = GETPOST('idline', 'int');
  85. $selectedline = GETPOST('selectedline', 'int');
  86. $desc = GETPOST('desc', 'alphanohtml');
  87. $pay = GETPOST('pay', 'aZ09');
  88. $amountofpayment = price2num(GETPOST('amount', 'alpha'));
  89. $invoiceid = GETPOST('invoiceid', 'int');
  90. $paycode = $pay;
  91. if ($pay == 'cash') {
  92. $paycode = 'LIQ'; // For backward compatibility
  93. }
  94. if ($pay == 'card') {
  95. $paycode = 'CB'; // For backward compatibility
  96. }
  97. if ($pay == 'cheque') {
  98. $paycode = 'CHQ'; // For backward compatibility
  99. }
  100. // Retrieve paiementid
  101. $paiementid = 0;
  102. if ($paycode) {
  103. $sql = "SELECT id FROM ".MAIN_DB_PREFIX."c_paiement";
  104. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  105. $sql .= " AND code = '".$db->escape($paycode)."'";
  106. $resql = $db->query($sql);
  107. if ($resql) {
  108. $obj = $db->fetch_object($resql);
  109. if ($obj) {
  110. $paiementid = $obj->id;
  111. }
  112. }
  113. }
  114. $invoice = new Facture($db);
  115. if ($invoiceid > 0) {
  116. $ret = $invoice->fetch($invoiceid);
  117. } else {
  118. $ret = $invoice->fetch('', '(PROV-POS'. (isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '') .'-'.$place.')');
  119. }
  120. if ($ret > 0) {
  121. $placeid = $invoice->id;
  122. }
  123. $constforcompanyid = 'CASHDESK_ID_THIRDPARTY'. (isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
  124. $soc = new Societe($db);
  125. if ($invoice->socid > 0) {
  126. $soc->fetch($invoice->socid);
  127. } else {
  128. $soc->fetch(getDolGlobalString($constforcompanyid));
  129. }
  130. // Change the currency of invoice if it was modified
  131. if (isModEnabled('multicurrency') && !empty($_SESSION["takeposcustomercurrency"])) {
  132. if ($invoice->multicurrency_code != $_SESSION["takeposcustomercurrency"]) {
  133. $invoice->setMulticurrencyCode($_SESSION["takeposcustomercurrency"]);
  134. }
  135. }
  136. /*
  137. * Actions
  138. */
  139. $parameters=array();
  140. $reshook=$hookmanager->executeHooks('doActions', $parameters, $invoice, $action); // Note that $action and $object may have been modified by some hooks
  141. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  142. if (empty($reshook)) {
  143. // Action to record a payment on a TakePOS invoice
  144. if ($action == 'valid' && $user->hasRight('facture', 'creer')) {
  145. $bankaccount = 0;
  146. $error = 0;
  147. if (!empty($conf->global->TAKEPOS_CAN_FORCE_BANK_ACCOUNT_DURING_PAYMENT)) {
  148. $bankaccount = GETPOST('accountid', 'int');
  149. } else {
  150. if ($pay == 'LIQ') {
  151. $bankaccount = getDolGlobalString('CASHDESK_ID_BANKACCOUNT_CASH'.$_SESSION["takeposterminal"]); // For backward compatibility
  152. } elseif ($pay == "CHQ") {
  153. $bankaccount = getDolGlobalString('CASHDESK_ID_BANKACCOUNT_CHEQUE'.$_SESSION["takeposterminal"]); // For backward compatibility
  154. } else {
  155. $accountname = "CASHDESK_ID_BANKACCOUNT_".$pay.$_SESSION["takeposterminal"];
  156. $bankaccount = getDolGlobalString($accountname);
  157. }
  158. }
  159. if ($bankaccount <= 0 && $pay != "delayed" && isModEnabled("banque")) {
  160. $errormsg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount"));
  161. $error++;
  162. }
  163. $now = dol_now();
  164. $res = 0;
  165. $invoice = new Facture($db);
  166. $invoice->fetch($placeid);
  167. if ($invoice->total_ttc < 0) {
  168. $invoice->type = $invoice::TYPE_CREDIT_NOTE;
  169. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture WHERE";
  170. $sql .= " fk_soc = ".((int) $invoice->socid);
  171. $sql .= " AND type <> ".Facture::TYPE_CREDIT_NOTE;
  172. $sql .= " AND fk_statut >= ".$invoice::STATUS_VALIDATED;
  173. $sql .= " ORDER BY rowid DESC";
  174. $resql = $db->query($sql);
  175. if ($resql) {
  176. $obj = $db->fetch_object($resql);
  177. $fk_source = $obj->rowid;
  178. if ($fk_source == null) {
  179. fail($langs->transnoentitiesnoconv("NoPreviousBillForCustomer"));
  180. }
  181. } else {
  182. fail($langs->transnoentitiesnoconv("NoPreviousBillForCustomer"));
  183. }
  184. $invoice->fk_facture_source = $fk_source;
  185. $invoice->update($user);
  186. }
  187. $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'.(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
  188. if ($error) {
  189. dol_htmloutput_errors($errormsg, null, 1);
  190. } elseif ($invoice->statut != Facture::STATUS_DRAFT) {
  191. //If invoice is validated but it is not fully paid is not error and make the payment
  192. if ($invoice->getRemainToPay() > 0) {
  193. $res = 1;
  194. } else {
  195. dol_syslog("Sale already validated");
  196. dol_htmloutput_errors($langs->trans("InvoiceIsAlreadyValidated", "TakePos"), null, 1);
  197. }
  198. } elseif (count($invoice->lines) == 0) {
  199. $error++;
  200. dol_syslog('Sale without lines');
  201. dol_htmloutput_errors($langs->trans("NoLinesToBill", "TakePos"), null, 1);
  202. } elseif (isModEnabled('stock') && getDolGlobalString($constantforkey) != "1" && !isModEnabled('productbatch')) {
  203. $savconst = $conf->global->STOCK_CALCULATE_ON_BILL;
  204. if (isModEnabled('productbatch') && !getDolGlobalInt('CASHDESK_FORCE_DECREASE_STOCK')) {
  205. $conf->global->STOCK_CALCULATE_ON_BILL = 0; // To not change the stock (not yet compatible with batch management)
  206. } else {
  207. $conf->global->STOCK_CALCULATE_ON_BILL = 1; // To force the change of stock
  208. }
  209. $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
  210. dol_syslog("Validate invoice with stock change into warehouse defined into constant ".$constantforkey." = ".getDolGlobalString($constantforkey));
  211. $batch_rule = 0;
  212. if (isModEnabled('productbatch') && !empty($conf->global->CASHDESK_FORCE_DECREASE_STOCK)) {
  213. require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
  214. $batch_rule = Productbatch::BATCH_RULE_SELLBY_EATBY_DATES_FIRST;
  215. }
  216. $res = $invoice->validate($user, '', getDolGlobalString($constantforkey), 0, $batch_rule);
  217. $conf->global->STOCK_CALCULATE_ON_BILL = $savconst;
  218. } else {
  219. $res = $invoice->validate($user);
  220. if ($res < 0) {
  221. $error++;
  222. $langs->load("admin");
  223. dol_htmloutput_errors($invoice->error == 'NotConfigured' ? $langs->trans("NotConfigured").' (TakePos numbering module)': $invoice->error, $invoice->errors, 1);
  224. }
  225. }
  226. // Restore save values
  227. //if (!empty($sav_FACTURE_ADDON))
  228. //{
  229. // $conf->global->FACTURE_ADDON = $sav_FACTURE_ADDON;
  230. //}
  231. // Add the payment
  232. if (!$error && $res >= 0) {
  233. $remaintopay = $invoice->getRemainToPay();
  234. if ($remaintopay > 0) {
  235. $payment = new Paiement($db);
  236. $payment->datepaye = $now;
  237. $payment->fk_account = $bankaccount;
  238. $payment->amounts[$invoice->id] = $amountofpayment;
  239. if ($pay == 'LIQ') {
  240. $payment->pos_change = price2num(GETPOST('excess', 'alpha'));
  241. }
  242. // If user has not used change control, add total invoice payment
  243. // Or if user has used change control and the amount of payment is higher than remain to pay, add the remain to pay
  244. if ($amountofpayment <= 0 || $amountofpayment > $remaintopay) {
  245. $payment->amounts[$invoice->id] = $remaintopay;
  246. }
  247. $payment->paiementid = $paiementid;
  248. $payment->num_payment = $invoice->ref;
  249. if ($pay != "delayed") {
  250. $payment->create($user);
  251. $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccount, '', '');
  252. $remaintopay = $invoice->getRemainToPay(); // Recalculate remain to pay after the payment is recorded
  253. } elseif (getDolGlobalInt("TAKEPOS_DELAYED_TERMS")) {
  254. $invoice->setPaymentTerms(getDolGlobalInt("TAKEPOS_DELAYED_TERMS"));
  255. }
  256. }
  257. if ($remaintopay == 0) {
  258. dol_syslog("Invoice is paid, so we set it to status Paid");
  259. $result = $invoice->setPaid($user);
  260. if ($result > 0) {
  261. $invoice->paye = 1;
  262. }
  263. // set payment method
  264. $invoice->setPaymentMethods($paiementid);
  265. } else {
  266. dol_syslog("Invoice is not paid, remain to pay = ".$remaintopay);
  267. }
  268. } else {
  269. dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
  270. }
  271. // Update stock for batch products
  272. if (isModEnabled('productbatch')) {
  273. require_once DOL_DOCUMENT_ROOT . "/product/stock/class/mouvementstock.class.php";
  274. $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
  275. foreach ($invoice->lines as $line) {
  276. if ($line->batch && $line->fk_warehouse > 0) {
  277. $prod_batch = new Productbatch($db);
  278. $prod_batch->find(0, '', '', $line->batch, $line->fk_warehouse);
  279. $mouvP = new MouvementStock($db);
  280. $mouvP->origin = $invoice;
  281. $mouvP->livraison($user, $line->fk_product, $conf->global->$constantforkey, $line->qty, $line->price, 'TakePOS', '', '', '', $prod_batch->batch, $line->batch);
  282. } else {
  283. $mouvP = new MouvementStock($db);
  284. $mouvP->origin = $invoice;
  285. $mouvP->livraison($user, $line->fk_product, $conf->global->$constantforkey, $line->qty, $line->price, 'TakePOS', '', '', '');
  286. }
  287. }
  288. }
  289. }
  290. if ($action == 'creditnote' && $user->hasRight('facture', 'creer')) {
  291. $creditnote = new Facture($db);
  292. $creditnote->socid = $invoice->socid;
  293. $creditnote->date = dol_now();
  294. $creditnote->module_source = 'takepos';
  295. $creditnote->pos_source = isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '' ;
  296. $creditnote->type = Facture::TYPE_CREDIT_NOTE;
  297. $creditnote->fk_facture_source = $placeid;
  298. //$creditnote->remise_absolue = $invoice->remise_absolue;
  299. //$creditnote->remise_percent = $invoice->remise_percent;
  300. $creditnote->create($user);
  301. foreach ($invoice->lines as $line) {
  302. // Extrafields
  303. if (method_exists($line, 'fetch_optionals')) {
  304. // load extrafields
  305. $line->fetch_optionals();
  306. }
  307. // Reset fk_parent_line for no child products and special product
  308. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  309. $fk_parent_line = 0;
  310. }
  311. if (getDolGlobalInt('INVOICE_USE_SITUATION')) {
  312. if (!empty($invoice->situation_counter)) {
  313. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  314. $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
  315. if (!empty($invoice->tab_previous_situation_invoice)) {
  316. // search the last standard invoice in cycle and the possible credit note between this last and invoice
  317. // TODO Move this out of loop of $invoice->lines
  318. $tab_jumped_credit_notes = array();
  319. $lineIndex = count($invoice->tab_previous_situation_invoice) - 1;
  320. $searchPreviousInvoice = true;
  321. while ($searchPreviousInvoice) {
  322. if ($invoice->tab_previous_situation_invoice[$lineIndex]->situation_cycle_ref || $lineIndex < 1) {
  323. $searchPreviousInvoice = false; // find, exit;
  324. break;
  325. } else {
  326. if ($invoice->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
  327. $tab_jumped_credit_notes[$lineIndex] = $invoice->tab_previous_situation_invoice[$lineIndex]->id;
  328. }
  329. $lineIndex--; // go to previous invoice in cycle
  330. }
  331. }
  332. $maxPrevSituationPercent = 0;
  333. foreach ($invoice->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  334. if ($prevLine->id == $source_fk_prev_id) {
  335. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  336. //$line->subprice = $line->subprice - $prevLine->subprice;
  337. $line->total_ht = $line->total_ht - $prevLine->total_ht;
  338. $line->total_tva = $line->total_tva - $prevLine->total_tva;
  339. $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
  340. $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
  341. $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
  342. $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
  343. $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
  344. $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
  345. $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
  346. }
  347. }
  348. // prorata
  349. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  350. //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>';
  351. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  352. $maxPrevSituationPercent = 0;
  353. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  354. foreach ($invoice->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  355. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  356. $maxPrevSituationPercent = $prevLine->situation_percent;
  357. $line->total_ht -= $prevLine->total_ht;
  358. $line->total_tva -= $prevLine->total_tva;
  359. $line->total_ttc -= $prevLine->total_ttc;
  360. $line->total_localtax1 -= $prevLine->total_localtax1;
  361. $line->total_localtax2 -= $prevLine->total_localtax2;
  362. $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
  363. $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
  364. $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
  365. $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
  366. }
  367. }
  368. }
  369. // prorata
  370. $line->situation_percent += $maxPrevSituationPercent;
  371. //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>';
  372. }
  373. }
  374. }
  375. $line->fk_facture = $creditnote->id;
  376. $line->fk_parent_line = $fk_parent_line;
  377. $line->subprice = -$line->subprice; // invert price for object
  378. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  379. $line->total_ht = -$line->total_ht;
  380. $line->total_tva = -$line->total_tva;
  381. $line->total_ttc = -$line->total_ttc;
  382. $line->total_localtax1 = -$line->total_localtax1;
  383. $line->total_localtax2 = -$line->total_localtax2;
  384. $line->multicurrency_subprice = -$line->multicurrency_subprice;
  385. $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
  386. $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
  387. $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
  388. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  389. $creditnote->lines[] = $line; // insert new line in current object
  390. // Defined the new fk_parent_line
  391. if ($result > 0 && $line->product_type == 9) {
  392. $fk_parent_line = $result;
  393. }
  394. }
  395. $creditnote->update_price(1);
  396. $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'.(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
  397. if (isModEnabled('stock') && getDolGlobalString($constantforkey) != "1") {
  398. $savconst = $conf->global->STOCK_CALCULATE_ON_BILL;
  399. $conf->global->STOCK_CALCULATE_ON_BILL = 1;
  400. $constantforkey = 'CASHDESK_ID_WAREHOUSE'.(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
  401. dol_syslog("Validate invoice with stock change into warehouse defined into constant ".$constantforkey." = ".getDolGlobalString($constantforkey));
  402. $batch_rule = 0;
  403. if (isModEnabled('productbatch') && getDolGlobalString('CASHDESK_FORCE_DECREASE_STOCK')) {
  404. require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
  405. $batch_rule = Productbatch::BATCH_RULE_SELLBY_EATBY_DATES_FIRST;
  406. }
  407. $res = $creditnote->validate($user, '', getDolGlobalString($constantforkey), 0, $batch_rule);
  408. $conf->global->STOCK_CALCULATE_ON_BILL = $savconst;
  409. } else {
  410. $res = $creditnote->validate($user);
  411. }
  412. }
  413. if ($action == 'history' || $action == 'creditnote') {
  414. if ($action == 'creditnote') {
  415. $placeid = $creditnote->id;
  416. } else {
  417. $placeid = (int) GETPOST('placeid', 'int');
  418. }
  419. $invoice = new Facture($db);
  420. $invoice->fetch($placeid);
  421. }
  422. // If we add a line and no invoice yet, we create the invoice
  423. if (($action == "addline" || $action == "freezone") && $placeid == 0) {
  424. $invoice->socid = getDolGlobalString($constforcompanyid);
  425. $invoice->date = dol_now('tzuserrel'); // We use the local date, only the day will be saved.
  426. $invoice->module_source = 'takepos';
  427. $invoice->pos_source = isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '' ;
  428. $invoice->entity = !empty($_SESSION["takeposinvoiceentity"]) ? $_SESSION["takeposinvoiceentity"] : $conf->entity;
  429. if ($invoice->socid <= 0) {
  430. $langs->load('errors');
  431. dol_htmloutput_errors($langs->trans("ErrorModuleSetupNotComplete", "TakePos"), null, 1);
  432. } else {
  433. // Create invoice
  434. $placeid = $invoice->create($user);
  435. if ($placeid < 0) {
  436. dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
  437. }
  438. $sql = "UPDATE ".MAIN_DB_PREFIX."facture set ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")' where rowid = ".((int) $placeid);
  439. $db->query($sql);
  440. }
  441. }
  442. if ($action == "addline") {
  443. $prod = new Product($db);
  444. $prod->fetch($idproduct);
  445. $customer = new Societe($db);
  446. $customer->fetch($invoice->socid);
  447. $datapriceofproduct = $prod->getSellPrice($mysoc, $customer, 0);
  448. $qty = GETPOSTISSET('qty') ? GETPOST('qty', 'int') : 1;
  449. $price = $datapriceofproduct['pu_ht'];
  450. $price_ttc = $datapriceofproduct['pu_ttc'];
  451. //$price_min = $datapriceofproduct['price_min'];
  452. $price_base_type = empty($datapriceofproduct['price_base_type']) ? 'HT' : $datapriceofproduct['price_base_type'];
  453. $tva_tx = $datapriceofproduct['tva_tx'];
  454. $tva_npr = $datapriceofproduct['tva_npr'];
  455. // Local Taxes
  456. $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr);
  457. $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr);
  458. if (isModEnabled('productbatch') && isModEnabled('stock')) {
  459. $batch = GETPOST('batch', 'alpha');
  460. if (!empty($batch)) {
  461. $action="setbatch";
  462. } else {
  463. $prod->load_stock('warehouseopen');
  464. $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
  465. if ($prod->stock_warehouse[$conf->global->$constantforkey]->detail_batch!="")
  466. if (is_object($prod->stock_warehouse[$conf->global->$constantforkey]) && count($prod->stock_warehouse[$conf->global->$constantforkey]->detail_batch)) {
  467. foreach ($prod->stock_warehouse[$conf->global->$constantforkey]->detail_batch as $dbatch) {
  468. $nbofsuggested++;
  469. }
  470. }
  471. echo "<script>";
  472. echo "function addbatch(batch, warehouseid){";
  473. echo '$("#poslines").load("invoice.php?action=addline&batch="+batch+"&warehouseid="+warehouseid+"&place='.$place.'&idproduct='.$idproduct.'&token='.newToken().'", function() {
  474. });';
  475. echo "}";
  476. echo "</script>";
  477. if ($nbofsuggested>0) {
  478. echo "<center>".$langs->trans("SearchIntoBatch").": <b> $nbofsuggested </b></center><br><table>";
  479. foreach ($prod->stock_warehouse[$conf->global->$constantforkey]->detail_batch as $dbatch) { // $dbatch is instance of Productbatch
  480. $batchStock = + $dbatch->qty; // To get a numeric
  481. $deliverableQty = min($quantityToBeDelivered, $batchStock);
  482. print '<!-- subj='.$subj.'/'.$nbofsuggested.' --><tr '.((($subj + 1) == $nbofsuggested) ? $bc[$var] : '').'>';
  483. print '<!-- Show details of lot -->';
  484. print '<td class="left">';
  485. $staticwarehouse = new Entrepot($db);
  486. if ($warehouse_id > 0) $staticwarehouse->fetch($conf->global->$constantforkey);
  487. $detail = '';
  488. $detail .= $langs->trans("LotSerial").': '.$dbatch->batch;
  489. if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) {
  490. //$detail .= ' - '.$langs->trans("SellByDate").': '.dol_print_date($dbatch->sellby, "day");
  491. }
  492. if (empty($conf->global->PRODUCT_DISABLE_EATBY)) {
  493. //$detail .= ' - '.$langs->trans("EatByDate").': '.dol_print_date($dbatch->eatby, "day");
  494. }
  495. $detail .= ' - '.$langs->trans("Qty").': '.$dbatch->qty;
  496. $detail .= " <button onclick='addbatch(".$dbatch->batch.", ".getDolGlobalInt($constantforkey).")'>".$langs->trans("Select")."</button>";
  497. $detail .= '<br>';
  498. print $detail;
  499. $quantityToBeDelivered -= $deliverableQty;
  500. if ($quantityToBeDelivered < 0) {
  501. $quantityToBeDelivered = 0;
  502. }
  503. $subj++;
  504. print '</td></tr>';
  505. }
  506. print "</table>";
  507. exit;
  508. }
  509. }
  510. }
  511. if (getDolGlobalString('TAKEPOS_SUPPLEMENTS')) {
  512. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  513. $cat = new Categorie($db);
  514. $categories = $cat->containing($idproduct, 'product');
  515. $found = (array_search(getDolGlobalInt('TAKEPOS_SUPPLEMENTS_CATEGORY'), array_column($categories, 'id')));
  516. if ($found !== false) { // If this product is a supplement
  517. $sql = "SELECT fk_parent_line FROM ".MAIN_DB_PREFIX."facturedet where rowid = ".((int) $selectedline);
  518. $resql = $db->query($sql);
  519. $row = $db->fetch_array($resql);
  520. if ($row[0] == null) {
  521. $parent_line = $selectedline;
  522. } else {
  523. $parent_line = $row[0]; //If the parent line is already a supplement, add the supplement to the main product
  524. }
  525. }
  526. }
  527. $idoflineadded = 0;
  528. $err = 0;
  529. // Group if enabled. Skip group if line already sent to the printer
  530. if (!empty($conf->global->TAKEPOS_GROUP_SAME_PRODUCT)) {
  531. foreach ($invoice->lines as $line) {
  532. if ($line->product_ref == $prod->ref) {
  533. if ($line->special_code==4) continue; // If this line is sended to printer create new line
  534. // check if qty in stock
  535. if (getDolGlobalString('TAKEPOS_QTY_IN_STOCK') && (($line->qty + $qty) > $prod->stock_reel)) {
  536. $invoice->error = $langs->trans('NotEnoughInStock');
  537. dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
  538. $err++;
  539. break;
  540. }
  541. $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);
  542. if ($result < 0) {
  543. dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
  544. } else {
  545. $idoflineadded = $line->id;
  546. }
  547. break;
  548. }
  549. }
  550. }
  551. if ($idoflineadded <= 0 && empty($err)) {
  552. $invoice->fetch_thirdparty();
  553. $array_options = array();
  554. $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);
  555. /* setup of margin calculation */
  556. if (isset($conf->global->MARGIN_TYPE)) {
  557. if (getDolGlobalString('MARGIN_TYPE') == 'pmp' && !empty($prod->pmp)) {
  558. $line['fk_fournprice'] = null;
  559. $line['pa_ht'] = $prod->pmp;
  560. } elseif (getDolGlobalString('MARGIN_TYPE') == 'costprice' && !empty($prod->cost_price)) {
  561. $line['fk_fournprice'] = null;
  562. $line['pa_ht'] = $prod->cost_price;
  563. } else {
  564. // default is fournprice
  565. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  566. $pf = new ProductFournisseur($db);
  567. if ($pf->find_min_price_product_fournisseur($idproduct, $qty) > 0) {
  568. $line['fk_fournprice'] = $pf->product_fourn_price_id;
  569. $line['pa_ht'] = $pf->fourn_unitprice_with_discount;
  570. if (getDolGlobalString('PRODUCT_CHARGES') && $pf->fourn_charges > 0)
  571. $line['pa_ht'] += $pf->fourn_charges / $pf->fourn_qty;
  572. }
  573. }
  574. }
  575. // complete line by hook
  576. $parameters = array('prod' => $prod, 'line' => $line);
  577. $reshook=$hookmanager->executeHooks('completeTakePosAddLine', $parameters, $invoice, $action); // Note that $action and $line may have been modified by some hooks
  578. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  579. if (empty($reshook)) {
  580. if (!empty($hookmanager->resArray)) {
  581. $line = $hookmanager->resArray;
  582. }
  583. // check if qty in stock
  584. if (getDolGlobalString('TAKEPOS_QTY_IN_STOCK') && $qty > $prod->stock_reel) {
  585. $invoice->error = $langs->trans('NotEnoughInStock');
  586. dol_htmloutput_errors($invoice->error, $invoice->errors, 1);
  587. $err++;
  588. }
  589. if (empty($err)) {
  590. $idoflineadded = $invoice->addline($line['description'], $line['price'], $qty, $line['tva_tx'], $line['localtax1_tx'], $line['localtax2_tx'], $idproduct, $line['remise_percent'], '', 0, 0, 0, '', $price_base_type, $line['price_ttc'], $prod->type, -1, 0, '', 0, (!empty($parent_line)) ? $parent_line : '', $line['fk_fournprice'], $line['pa_ht'], '', $line['array_options'], 100, '', null, 0);
  591. }
  592. }
  593. if (!empty($conf->global->TAKEPOS_CUSTOMER_DISPLAY)) {
  594. $CUSTOMER_DISPLAY_line1 = $prod->label;
  595. $CUSTOMER_DISPLAY_line2 = price($price_ttc);
  596. }
  597. }
  598. $invoice->fetch($placeid);
  599. }
  600. if ($action == "freezone") {
  601. $customer = new Societe($db);
  602. $customer->fetch($invoice->socid);
  603. $tva_tx = GETPOST('tva_tx', 'alpha');
  604. if ($tva_tx != '') {
  605. if (!preg_match('/\((.*)\)/', $tva_tx)) {
  606. $tva_tx = price2num($tva_tx);
  607. }
  608. } else {
  609. $tva_tx = get_default_tva($mysoc, $customer);
  610. }
  611. // Local Taxes
  612. $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr);
  613. $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr);
  614. $invoice->addline($desc, $number, 1, $tva_tx, $localtax1_tx, $localtax2_tx, 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, null, '', '', 0, 100, '', null, 0);
  615. $invoice->fetch($placeid);
  616. }
  617. if ($action == "addnote") {
  618. $desc = GETPOST('addnote', 'alpha');
  619. if ($idline==0) {
  620. $invoice->update_note($desc, '_public');
  621. } else foreach ($invoice->lines as $line) {
  622. if ($line->id == $idline) {
  623. $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);
  624. }
  625. }
  626. $invoice->fetch($placeid);
  627. }
  628. if ($action == "deleteline") {
  629. if ($idline > 0 and $placeid > 0) { // If invoice exists and line selected. To avoid errors if deleted from another device or no line selected.
  630. $invoice->deleteline($idline);
  631. $invoice->fetch($placeid);
  632. } elseif ($placeid > 0) { // If invoice exists but no line selected, proceed to delete last line.
  633. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facturedet where fk_facture = ".((int) $placeid)." ORDER BY rowid DESC";
  634. $resql = $db->query($sql);
  635. $row = $db->fetch_array($resql);
  636. $deletelineid = $row[0];
  637. $invoice->deleteline($deletelineid);
  638. $invoice->fetch($placeid);
  639. }
  640. if (count($invoice->lines) == 0) {
  641. $invoice->delete($user);
  642. header("Location: ".DOL_URL_ROOT."/takepos/invoice.php");
  643. exit;
  644. }
  645. }
  646. // Action to delete or discard an invoice
  647. if ($action == "delete") {
  648. // $placeid is the invoice id (it differs from place) and is defined if the place is set and the ref of invoice is '(PROV-POS'.$_SESSION["takeposterminal"].'-'.$place.')', so the fetch at begining of page works.
  649. if ($placeid > 0) {
  650. $result = $invoice->fetch($placeid);
  651. if ($result > 0 && $invoice->statut == Facture::STATUS_DRAFT) {
  652. $db->begin();
  653. // We delete the lines
  654. $resdeletelines = 1;
  655. foreach ($invoice->lines as $line) {
  656. $tmpres = $invoice->deleteline($line->id);
  657. if ($tmpres < 0) {
  658. $resdeletelines = 0;
  659. break;
  660. }
  661. }
  662. $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
  663. $varforconst = 'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"];
  664. $sql .= " SET fk_soc = ".((int) getDolGlobalString($varforconst)).", ";
  665. $sql .= " datec = '".$db->idate(dol_now())."'";
  666. $sql .= " WHERE ref = '(PROV-POS".$db->escape($_SESSION["takeposterminal"]."-".$place).")'";
  667. $resql1 = $db->query($sql);
  668. if ($resdeletelines && $resql1) {
  669. $db->commit();
  670. } else {
  671. $db->rollback();
  672. }
  673. $invoice->fetch($placeid);
  674. }
  675. }
  676. }
  677. if ($action == "updateqty") {
  678. foreach ($invoice->lines as $line) {
  679. if ($line->id == $idline) {
  680. if (!$user->hasRight('takepos', 'editlines') || (!$user->hasRight('takepos', 'editorderedlines') && $line->special_code == "4")) {
  681. dol_htmloutput_errors($langs->trans("NotEnoughPermissions", "TakePos"), null, 1);
  682. } else {
  683. $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $number, $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);
  684. }
  685. }
  686. }
  687. $invoice->fetch($placeid);
  688. }
  689. if ($action == "updateprice") {
  690. $customer = new Societe($db);
  691. $customer->fetch($invoice->socid);
  692. foreach ($invoice->lines as $line) {
  693. if ($line->id == $idline) {
  694. $prod = new Product($db);
  695. $prod->fetch($line->fk_product);
  696. $datapriceofproduct = $prod->getSellPrice($mysoc, $customer, 0);
  697. $price_min = $datapriceofproduct['price_min'];
  698. $usercanproductignorepricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS));
  699. $pu_ht = price2num($number / (1 + ($line->tva_tx / 100)), 'MU');
  700. //Check min price
  701. if ($usercanproductignorepricemin && (!empty($price_min) && (price2num($pu_ht) * (1 - price2num($line->remise_percent) / 100) < price2num($price_min)))) {
  702. $langs->load("products");
  703. dol_htmloutput_errors($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency)));
  704. //echo $langs->trans("CantBeLessThanMinPrice");
  705. } else {
  706. if (!$user->hasRight('takepos', 'editlines') || (!$user->hasRight('takepos', 'editorderedlines') && $line->special_code == "4")) {
  707. dol_htmloutput_errors($langs->trans("NotEnoughPermissions", "TakePos"), null, 1);
  708. } elseif (getDolGlobalInt('TAKEPOS_CHANGE_PRICE_HT') == 1) {
  709. $result = $invoice->updateline($line->id, $line->desc, $number, $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);
  710. } else {
  711. $result = $invoice->updateline($line->id, $line->desc, $number, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $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);
  712. }
  713. }
  714. }
  715. }
  716. // Reload data
  717. $invoice->fetch($placeid);
  718. }
  719. if ($action == "updatereduction") {
  720. $customer = new Societe($db);
  721. $customer->fetch($invoice->socid);
  722. foreach ($invoice->lines as $line) {
  723. if ($line->id == $idline) {
  724. dol_syslog("updatereduction Process line ".$line->id.' to apply discount of '.$number.'%');
  725. $prod = new Product($db);
  726. $prod->fetch($line->fk_product);
  727. $datapriceofproduct = $prod->getSellPrice($mysoc, $customer, 0);
  728. $price_min = $datapriceofproduct['price_min'];
  729. $usercanproductignorepricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS));
  730. $pu_ht = price2num($line->subprice / (1 + ($line->tva_tx / 100)), 'MU');
  731. // Check min price
  732. if ($usercanproductignorepricemin && (!empty($price_min) && (price2num($line->subprice) * (1 - price2num($number) / 100) < price2num($price_min)))) {
  733. $langs->load("products");
  734. dol_htmloutput_errors($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency)));
  735. } else {
  736. if (!$user->hasRight('takepos', 'editlines') || (!$user->hasRight('takepos', 'editorderedlines') && $line->special_code == "4")) {
  737. dol_htmloutput_errors($langs->trans("NotEnoughPermissions", "TakePos"), null, 1);
  738. } else {
  739. $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty, $number, $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);
  740. }
  741. }
  742. }
  743. }
  744. // Reload data
  745. $invoice->fetch($placeid);
  746. } elseif ($action == 'update_reduction_global') {
  747. foreach ($invoice->lines as $line) {
  748. $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty, $number, $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);
  749. }
  750. $invoice->fetch($placeid);
  751. }
  752. if ($action=="setbatch") {
  753. $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
  754. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set batch=".$db->escape($batch).", fk_warehouse=".getDolGlobalString($constantforkey)." where rowid=".((int) $idoflineadded);
  755. $db->query($sql);
  756. }
  757. if ($action == "order" and $placeid != 0) {
  758. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  759. if (getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter" || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") {
  760. require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
  761. $printer = new dolReceiptPrinter($db);
  762. }
  763. $sql = "SELECT label FROM ".MAIN_DB_PREFIX."takepos_floor_tables where rowid=".((int) $place);
  764. $resql = $db->query($sql);
  765. $row = $db->fetch_object($resql);
  766. $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>';
  767. $footerorder = '</tbody></table>'.dol_print_date(dol_now(), 'dayhour').'<br></html>';
  768. $order_receipt_printer1 = "";
  769. $order_receipt_printer2 = "";
  770. $order_receipt_printer3 = "";
  771. $catsprinter1 = explode(';', $conf->global->TAKEPOS_PRINTED_CATEGORIES_1);
  772. $catsprinter2 = explode(';', $conf->global->TAKEPOS_PRINTED_CATEGORIES_2);
  773. $catsprinter3 = explode(';', $conf->global->TAKEPOS_PRINTED_CATEGORIES_3);
  774. $linestoprint = 0;
  775. foreach ($invoice->lines as $line) {
  776. if ($line->special_code == "4") {
  777. continue;
  778. }
  779. $c = new Categorie($db);
  780. $existing = $c->containing($line->fk_product, Categorie::TYPE_PRODUCT, 'id');
  781. $result = array_intersect($catsprinter1, $existing);
  782. $count = count($result);
  783. if (!$line->fk_product) {
  784. $count++; // Print Free-text item (Unassigned printer) to Printer 1
  785. }
  786. if ($count > 0) {
  787. $linestoprint++;
  788. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='1' where rowid=".$line->id; //Set to print on printer 1
  789. $db->query($sql);
  790. $order_receipt_printer1 .= '<tr><td class="left">';
  791. if ($line->fk_product) {
  792. $order_receipt_printer1 .= $line->product_label;
  793. } else {
  794. $order_receipt_printer1 .= $line->description;
  795. }
  796. $order_receipt_printer1 .= '</td><td class="right">'.$line->qty;
  797. if (!empty($line->array_options['options_order_notes'])) {
  798. $order_receipt_printer1 .= "<br>(".$line->array_options['options_order_notes'].")";
  799. }
  800. $order_receipt_printer1 .= '</td></tr>';
  801. }
  802. }
  803. if ((getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter" || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && $linestoprint > 0) {
  804. $invoice->fetch($placeid); //Reload object before send to printer
  805. $printer->orderprinter = 1;
  806. echo "<script>";
  807. echo "var orderprinter1esc='";
  808. $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
  809. echo "';</script>";
  810. }
  811. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where special_code='1' and fk_facture=".$invoice->id; // Set as printed
  812. $db->query($sql);
  813. $invoice->fetch($placeid); //Reload object after set lines as printed
  814. $linestoprint = 0;
  815. foreach ($invoice->lines as $line) {
  816. if ($line->special_code == "4") {
  817. continue;
  818. }
  819. $c = new Categorie($db);
  820. $existing = $c->containing($line->fk_product, Categorie::TYPE_PRODUCT, 'id');
  821. $result = array_intersect($catsprinter2, $existing);
  822. $count = count($result);
  823. if ($count > 0) {
  824. $linestoprint++;
  825. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='2' where rowid=".$line->id; //Set to print on printer 2
  826. $db->query($sql);
  827. $order_receipt_printer2 .= '<tr>'.$line->product_label.'<td class="right">'.$line->qty;
  828. if (!empty($line->array_options['options_order_notes'])) {
  829. $order_receipt_printer2 .= "<br>(".$line->array_options['options_order_notes'].")";
  830. }
  831. $order_receipt_printer2 .= '</td></tr>';
  832. }
  833. }
  834. if ((getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter" || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && $linestoprint > 0) {
  835. $invoice->fetch($placeid); //Reload object before send to printer
  836. $printer->orderprinter = 2;
  837. echo "<script>";
  838. echo "var orderprinter2esc='";
  839. $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
  840. echo "';</script>";
  841. }
  842. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where special_code='2' and fk_facture=".$invoice->id; // Set as printed
  843. $db->query($sql);
  844. $invoice->fetch($placeid); //Reload object after set lines as printed
  845. $linestoprint = 0;
  846. foreach ($invoice->lines as $line) {
  847. if ($line->special_code == "4") {
  848. continue;
  849. }
  850. $c = new Categorie($db);
  851. $existing = $c->containing($line->fk_product, Categorie::TYPE_PRODUCT, 'id');
  852. $result = array_intersect($catsprinter3, $existing);
  853. $count = count($result);
  854. if ($count > 0) {
  855. $linestoprint++;
  856. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='3' where rowid=".$line->id; //Set to print on printer 3
  857. $db->query($sql);
  858. $order_receipt_printer3 .= '<tr>'.$line->product_label.'<td class="right">'.$line->qty;
  859. if (!empty($line->array_options['options_order_notes'])) {
  860. $order_receipt_printer3 .= "<br>(".$line->array_options['options_order_notes'].")";
  861. }
  862. $order_receipt_printer3 .= '</td></tr>';
  863. }
  864. }
  865. if ((getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter" || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && $linestoprint > 0) {
  866. $invoice->fetch($placeid); //Reload object before send to printer
  867. $printer->orderprinter = 3;
  868. echo "<script>";
  869. echo "var orderprinter3esc='";
  870. $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
  871. echo "';</script>";
  872. }
  873. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where special_code='3' and fk_facture=".$invoice->id; // Set as printed
  874. $db->query($sql);
  875. $invoice->fetch($placeid); //Reload object after set lines as printed
  876. }
  877. $sectionwithinvoicelink = '';
  878. if ($action == "valid" || $action == "history" || $action == 'creditnote') {
  879. $sectionwithinvoicelink .= '<!-- Section with invoice link -->'."\n";
  880. $sectionwithinvoicelink .= '<span style="font-size:120%;" class="center">';
  881. $sectionwithinvoicelink .= $invoice->getNomUrl(1, '', 0, 0, '', 0, 0, -1, '_backoffice')." - ";
  882. $remaintopay = $invoice->getRemainToPay();
  883. if ($remaintopay > 0) {
  884. $sectionwithinvoicelink .= $langs->trans('RemainToPay').': <span class="amountremaintopay" style="font-size: unset">'.price($remaintopay, 1, $langs, 1, -1, -1, $conf->currency).'</span>';
  885. } else {
  886. if ($invoice->paye) {
  887. $sectionwithinvoicelink .= '<span class="amountpaymentcomplete" style="font-size: unset">'.$langs->trans("Paid").'</span>';
  888. } else {
  889. $sectionwithinvoicelink .= $langs->trans('BillShortStatusValidated');
  890. }
  891. }
  892. $sectionwithinvoicelink .= '</span><br>';
  893. if (getDolGlobalInt('TAKEPOS_PRINT_INVOICE_DOC_INSTEAD_OF_RECEIPT')) {
  894. $sectionwithinvoicelink .= ' <a target="_blank" class="button" href="' . DOL_URL_ROOT . '/document.php?token=' . newToken() . '&modulepart=facture&file=' . $invoice->ref . '/' . $invoice->ref . '.pdf">Invoice</a>';
  895. } elseif (getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") {
  896. if (getDolGlobalString('TAKEPOS_PRINT_SERVER') && filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) {
  897. $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="TakeposConnector('.$placeid.')">'.$langs->trans('PrintTicket').'</button>';
  898. } else {
  899. $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="TakeposPrinting('.$placeid.')">'.$langs->trans('PrintTicket').'</button>';
  900. }
  901. } elseif (getDolGlobalString('TAKEPOS_PRINT_METHOD') == "receiptprinter") {
  902. $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="DolibarrTakeposPrinting('.$placeid.')">'.$langs->trans('PrintTicket').'</button>';
  903. } else {
  904. $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="Print('.$placeid.')">'.$langs->trans('PrintTicket').'</button>';
  905. if (getDolGlobalString('TAKEPOS_PRINT_WITHOUT_DETAILS')) {
  906. $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="PrintBox('.$placeid.', \'without_details\')">'.$langs->trans('PrintWithoutDetails').'</button>';
  907. }
  908. if (getDolGlobalString('TAKEPOS_GIFT_RECEIPT')) {
  909. $sectionwithinvoicelink .= ' <button id="buttonprint" type="button" onclick="Print('.$placeid.', 1)">'.$langs->trans('GiftReceipt').'</button>';
  910. }
  911. }
  912. if (getDolGlobalString('TAKEPOS_EMAIL_TEMPLATE_INVOICE') && $conf->global->TAKEPOS_EMAIL_TEMPLATE_INVOICE > 0) {
  913. $sectionwithinvoicelink .= ' <button id="buttonsend" type="button" onclick="SendTicket('.$placeid.')">'.$langs->trans('SendTicket').'</button>';
  914. }
  915. if ($remaintopay <= 0 && getDolGlobalString('TAKEPOS_AUTO_PRINT_TICKETS') && $action != "history") {
  916. $sectionwithinvoicelink .= '<script type="text/javascript">$("#buttonprint").click();</script>';
  917. }
  918. }
  919. }
  920. /*
  921. * View
  922. */
  923. $form = new Form($db);
  924. // llxHeader
  925. if ((getDolGlobalString('TAKEPOS_PHONE_BASIC_LAYOUT') == 1 && $conf->browser->layout == 'phone') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  926. $title = 'TakePOS - Dolibarr '.DOL_VERSION;
  927. if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
  928. $title = 'TakePOS - ' . getDolGlobalString('MAIN_APPLICATION_TITLE');
  929. }
  930. $head = '<meta name="apple-mobile-web-app-title" content="TakePOS"/>
  931. <meta name="apple-mobile-web-app-capable" content="yes">
  932. <meta name="mobile-web-app-capable" content="yes">
  933. <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>';
  934. $arrayofcss = array(
  935. '/takepos/css/pos.css.php',
  936. );
  937. $arrayofjs = array('/takepos/js/jquery.colorbox-min.js');
  938. $disablejs = 0;
  939. $disablehead = 0;
  940. top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
  941. print '<body>'."\n";
  942. } else {
  943. top_httphead('text/html', 1);
  944. }
  945. ?>
  946. <!-- invoice.php -->
  947. <script type="text/javascript">
  948. var selectedline=0;
  949. var selectedtext="";
  950. <?php if ($action=="valid") echo "var place=0;";?> // Set to default place after close sale
  951. var placeid=<?php echo ($placeid > 0 ? $placeid : 0); ?>;
  952. $(document).ready(function() {
  953. var idoflineadded = <?php echo (empty($idoflineadded) ? 0 : $idoflineadded); ?>;
  954. $('.posinvoiceline').click(function(){
  955. console.log("Click done on "+this.id);
  956. $('.posinvoiceline').removeClass("selected");
  957. $(this).addClass("selected");
  958. if (selectedline==this.id) return; // If is already selected
  959. else selectedline=this.id;
  960. selectedtext=$('#'+selectedline).find("td:first").html();
  961. <?php
  962. if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  963. print '$("#phonediv1").load("auto_order.php?action=editline&token='.newToken().'&placeid="+placeid+"&selectedline="+selectedline, function() {
  964. });';
  965. }
  966. ?>
  967. });
  968. /* Autoselect the line */
  969. if (idoflineadded > 0)
  970. {
  971. console.log("Auto select "+idoflineadded);
  972. $('.posinvoiceline#'+idoflineadded).click();
  973. }
  974. <?php
  975. if ($action == "order" && !empty($order_receipt_printer1)) {
  976. if (filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) {
  977. ?>
  978. $.ajax({
  979. type: "POST",
  980. url: '<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>/printer/index.php',
  981. data: 'invoice='+orderprinter1esc
  982. });
  983. <?php
  984. } else {
  985. ?>
  986. $.ajax({
  987. type: "POST",
  988. url: 'http://<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>:8111/print',
  989. data: '<?php
  990. print $headerorder.$order_receipt_printer1.$footerorder; ?>'
  991. });
  992. <?php
  993. }
  994. }
  995. if ($action == "order" && !empty($order_receipt_printer2)) {
  996. if (filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) {
  997. ?>
  998. $.ajax({
  999. type: "POST",
  1000. url: '<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>/printer/index.php?printer=2',
  1001. data: 'invoice='+orderprinter2esc
  1002. });
  1003. <?php
  1004. } else {
  1005. ?>
  1006. $.ajax({
  1007. type: "POST",
  1008. url: 'http://<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>:8111/print2',
  1009. data: '<?php
  1010. print $headerorder.$order_receipt_printer2.$footerorder; ?>'
  1011. });
  1012. <?php
  1013. }
  1014. }
  1015. if ($action == "order" && !empty($order_receipt_printer3)) {
  1016. if (filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) {
  1017. ?>
  1018. $.ajax({
  1019. type: "POST",
  1020. url: '<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>/printer/index.php?printer=3',
  1021. data: 'invoice='+orderprinter3esc
  1022. });
  1023. <?php
  1024. }
  1025. }
  1026. // Set focus to search field
  1027. if ($action == "search" || $action == "valid") {
  1028. ?>
  1029. parent.setFocusOnSearchField();
  1030. <?php
  1031. }
  1032. if ($action == "temp" && !empty($ticket_printer1)) {
  1033. ?>
  1034. $.ajax({
  1035. type: "POST",
  1036. url: 'http://<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>:8111/print',
  1037. data: '<?php
  1038. print $header_soc.$header_ticket.$body_ticket.$ticket_printer1.$ticket_total.$footer_ticket; ?>'
  1039. });
  1040. <?php
  1041. }
  1042. if ($action == "search") {
  1043. ?>
  1044. $('#search').focus();
  1045. <?php
  1046. }
  1047. ?>
  1048. });
  1049. function SendTicket(id)
  1050. {
  1051. console.log("Open box to select the Print/Send form");
  1052. $.colorbox({href:"send.php?facid="+id, width:"70%", height:"30%", transition:"none", iframe:"true", title:'<?php echo dol_escape_js($langs->trans("SendTicket")); ?>'});
  1053. return true;
  1054. }
  1055. function PrintBox(id, action) {
  1056. console.log("Open box before printing");
  1057. $.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"); ?>"});
  1058. return true;
  1059. }
  1060. function Print(id, gift){
  1061. console.log("Call Print() to generate the receipt.");
  1062. $.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")); ?>'});
  1063. return true;
  1064. }
  1065. function TakeposPrinting(id){
  1066. var receipt;
  1067. console.log("TakeposPrinting" + id);
  1068. $.get("receipt.php?facid="+id, function(data, status) {
  1069. receipt=data.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '');
  1070. $.ajax({
  1071. type: "POST",
  1072. url: 'http://<?php print getDolGlobalString('TAKEPOS_PRINT_SERVER'); ?>:8111/print',
  1073. data: receipt
  1074. });
  1075. });
  1076. return true;
  1077. }
  1078. function TakeposConnector(id){
  1079. console.log("TakeposConnector" + id);
  1080. $.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) {
  1081. $.ajax({
  1082. type: "POST",
  1083. url: '<?php print getDolGlobalString('TAKEPOS_PRINT_SERVER'); ?>/printer/index.php',
  1084. data: 'invoice='+data
  1085. });
  1086. });
  1087. return true;
  1088. }
  1089. function DolibarrTakeposPrinting(id) {
  1090. console.log("DolibarrTakeposPrinting Printing invoice ticket " + id)
  1091. $.ajax({
  1092. type: "GET",
  1093. data: { token: '<?php echo currentToken(); ?>' },
  1094. url: "<?php print DOL_URL_ROOT.'/takepos/ajax/ajax.php?action=printinvoiceticket&token='.newToken().'&term='.urlencode(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '').'&id='; ?>" + id,
  1095. });
  1096. return true;
  1097. }
  1098. function CreditNote() {
  1099. $("#poslines").load("invoice.php?action=creditnote&token=<?php echo newToken() ?>&invoiceid="+placeid, function() { });
  1100. return true;
  1101. }
  1102. function SetNote() {
  1103. $("#poslines").load("invoice.php?action=addnote&token=<?php echo newToken() ?>&invoiceid="+placeid+"&idline="+selectedline, { "addnote": $("#textinput").val() });
  1104. return true;
  1105. }
  1106. $( document ).ready(function() {
  1107. console.log("Set customer info and sales in header placeid=<?php echo $placeid; ?> status=<?php echo $invoice->statut; ?>");
  1108. <?php
  1109. $s = $langs->trans("Customer");
  1110. if ($invoice->id > 0 && ($invoice->socid != getDolGlobalString($constforcompanyid))) {
  1111. $s = $soc->name;
  1112. if (getDolGlobalInt('TAKEPOS_CHOOSE_CONTACT')) {
  1113. $contactids = $invoice->getIdContact('external', 'BILLING');
  1114. $contactid = $contactids[0];
  1115. if ($contactid > 0) {
  1116. $contact = new Contact($db);
  1117. $contact->fetch($contactid);
  1118. $s .= " - " . $contact->getFullName($langs);
  1119. }
  1120. }
  1121. }
  1122. ?>
  1123. $("#customerandsales").html('');
  1124. $("#shoppingcart").html('');
  1125. <?php if (getDolGlobalInt('TAKEPOS_CHOOSE_CONTACT') == 0) { ?>
  1126. $("#customerandsales").append('<a class="valignmiddle tdoverflowmax100 minwidth100" id="customer" onclick="Customer();" title="<?php print dol_escape_js(dol_escape_htmltag($s)); ?>"><span class="fas fa-building paddingrightonly"></span><?php print dol_escape_js($s); ?></a>');
  1127. <?php } else { ?>
  1128. $("#customerandsales").append('<a class="valignmiddle tdoverflowmax300 minwidth100" id="contact" onclick="Contact();" title="<?php print dol_escape_js(dol_escape_htmltag($s)); ?>"><span class="fas fa-building paddingrightonly"></span><?php print dol_escape_js($s); ?></a>');
  1129. <?php } ?>
  1130. <?php
  1131. $sql = "SELECT rowid, datec, ref FROM ".MAIN_DB_PREFIX."facture";
  1132. if (empty($conf->global->TAKEPOS_CAN_EDIT_IF_ALREADY_VALIDATED)) {
  1133. // By default, only invoices with a ref not already defined can in list of open invoice we can edit.
  1134. $sql .= " WHERE ref LIKE '(PROV-POS".$db->escape(isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '')."-0%' AND entity IN (".getEntity('invoice').")";
  1135. } else {
  1136. // If TAKEPOS_CAN_EDIT_IF_ALREADY_VALIDATED set, we show also draft invoice that already has a reference defined
  1137. $sql .= " WHERE pos_source = '".$db->escape($_SESSION["takeposterminal"])."'";
  1138. $sql .= " AND module_source = 'takepos'";
  1139. $sql .= " AND entity IN (".getEntity('invoice').")";
  1140. }
  1141. $sql .= $db->order('datec', 'ASC');
  1142. $resql = $db->query($sql);
  1143. if ($resql) {
  1144. $max_sale = 0;
  1145. while ($obj = $db->fetch_object($resql)) {
  1146. echo '$("#shoppingcart").append(\'';
  1147. 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=\\\'';
  1148. $num_sale = str_replace(")", "", str_replace("(PROV-POS".$_SESSION["takeposterminal"]."-", "", $obj->ref));
  1149. echo $num_sale;
  1150. if (str_replace("-", "", $num_sale) > $max_sale) {
  1151. $max_sale = str_replace("-", "", $num_sale);
  1152. }
  1153. echo '\\\'; invoiceid=\\\'';
  1154. echo $obj->rowid;
  1155. echo '\\\'; Refresh();">';
  1156. if ($placeid == $obj->rowid) {
  1157. echo '<span class="basketselected">';
  1158. } else {
  1159. echo '<span class="basketnotselected">';
  1160. }
  1161. echo '<span class="fa fa-shopping-cart paddingright"></span>'.dol_print_date($db->jdate($obj->datec), '%H:%M', 'tzuser');
  1162. echo '</span>';
  1163. echo '</a>\');';
  1164. }
  1165. echo '$("#shoppingcart").append(\'<a onclick="place=\\\'0-';
  1166. echo $max_sale + 1;
  1167. 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>\');';
  1168. } else {
  1169. dol_print_error($db);
  1170. }
  1171. $s = '';
  1172. $idwarehouse = 0;
  1173. $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'. (isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
  1174. if (isModEnabled('stock')) {
  1175. if (getDolGlobalString($constantforkey) != "1") {
  1176. $constantforkey = 'CASHDESK_ID_WAREHOUSE'. (isset($_SESSION["takeposterminal"]) ? $_SESSION["takeposterminal"] : '');
  1177. $idwarehouse = getDolGlobalString($constantforkey);
  1178. if ($idwarehouse > 0) {
  1179. $s = '<span class="small">';
  1180. $warehouse = new Entrepot($db);
  1181. $warehouse->fetch($idwarehouse);
  1182. $s .= '<span class="hideonsmartphone">'.$langs->trans("Warehouse").'<br></span>'.$warehouse->ref;
  1183. if ($warehouse->statut == Entrepot::STATUS_CLOSED) {
  1184. $s .= ' ('.$langs->trans("Closed").')';
  1185. }
  1186. $s .= '</span>';
  1187. print "$('#infowarehouse').html('".dol_escape_js($s)."');";
  1188. print '$("#infowarehouse").css("display", "inline-block");';
  1189. } else {
  1190. $s = '<span class="small hideonsmartphone">';
  1191. $s .= $langs->trans("StockChangeDisabled").'<br>'.$langs->trans("NoWarehouseDefinedForTerminal");
  1192. $s .= '</span>';
  1193. print "$('#infowarehouse').html('".dol_escape_js($s)."');";
  1194. if (!empty($conf->dol_optimize_smallscreen)) {
  1195. print '$("#infowarehouse").css("display", "none");';
  1196. }
  1197. }
  1198. } else {
  1199. $s = '<span class="small hideonsmartphone">'.$langs->trans("StockChangeDisabled").'</span>';
  1200. print "$('#infowarehouse').html('".dol_escape_js($s)."');";
  1201. if (!empty($conf->dol_optimize_smallscreen)) {
  1202. print '$("#infowarehouse").css("display", "none");';
  1203. }
  1204. }
  1205. }
  1206. // Module Adherent
  1207. $s = '';
  1208. if (isModEnabled('adherent') && $invoice->socid > 0 && $invoice->socid != getDolGlobalInt($constforcompanyid)) {
  1209. $s = '<span class="small">';
  1210. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  1211. $langs->load("members");
  1212. $s .= $langs->trans("Member").': ';
  1213. $adh = new Adherent($db);
  1214. $result = $adh->fetch('', '', $invoice->socid);
  1215. if ($result > 0) {
  1216. $adh->ref = $adh->getFullName($langs);
  1217. if (empty($adh->statut) || $adh->statut == Adherent::STATUS_EXCLUDED ) {
  1218. $s .= "<s>";
  1219. }
  1220. $s .= $adh->getFullName($langs);
  1221. $s .= ' - '.$adh->type;
  1222. if ($adh->datefin) {
  1223. $s .= '<br>'.$langs->trans("SubscriptionEndDate").': '.dol_print_date($adh->datefin, 'day');
  1224. if ($adh->hasDelay()) {
  1225. $s .= " ".img_warning($langs->trans("Late"));
  1226. }
  1227. } else {
  1228. $s .= '<br>'.$langs->trans("SubscriptionNotReceived");
  1229. if ($adh->statut > 0) {
  1230. $s .= " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated
  1231. }
  1232. }
  1233. if (empty($adh->statut) || $adh->statut == Adherent::STATUS_EXCLUDED) {
  1234. $s .= "</s>";
  1235. }
  1236. } else {
  1237. $s .= '<br>'.$langs->trans("ThirdpartyNotLinkedToMember");
  1238. }
  1239. $s .= '</span>';
  1240. }
  1241. ?>
  1242. $("#moreinfo").html('<?php print dol_escape_js($s); ?>');
  1243. });
  1244. <?php
  1245. if (!empty($conf->global->TAKEPOS_CUSTOMER_DISPLAY)) {
  1246. echo "function CustomerDisplay(){";
  1247. echo "var line1='".$CUSTOMER_DISPLAY_line1."'.substring(0,20);";
  1248. echo "line1=line1.padEnd(20);";
  1249. echo "var line2='".$CUSTOMER_DISPLAY_line2."'.substring(0,20);";
  1250. echo "line2=line2.padEnd(20);";
  1251. echo "$.ajax({
  1252. type: 'GET',
  1253. data: { text: line1+line2 },
  1254. url: '".getDolGlobalString('TAKEPOS_PRINT_SERVER')."/display/index.php',
  1255. });";
  1256. echo "}";
  1257. }
  1258. ?>
  1259. </script>
  1260. <?php
  1261. // Add again js for footer because this content is injected into index.php page so all init
  1262. // for tooltip and other js beautifiers must be reexecuted too.
  1263. if (!empty($conf->use_javascript_ajax)) {
  1264. print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
  1265. print '<script src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.'"></script>'."\n";
  1266. }
  1267. print '<!-- invoice.php place='.(int) $place.' invoice='.$invoice->ref.' mobilepage='.(empty($mobilepage) ? '' : $mobilepage).' $_SESSION["basiclayout"]='.(empty($_SESSION["basiclayout"])?'':$_SESSION["basiclayout"]).' conf->global->TAKEPOS_BAR_RESTAURANT='.getDolGlobalString('TAKEPOS_BAR_RESTAURANT').' -->'."\n";
  1268. print '<div class="div-table-responsive-no-min invoice">';
  1269. print '<table id="tablelines" class="noborder noshadow postablelines centpercent">';
  1270. if ($sectionwithinvoicelink && ($mobilepage == "invoice" || $mobilepage == "")) {
  1271. if (!empty($conf->global->TAKEPOS_SHOW_HT)) {
  1272. print '<tr><td colspan="5">'.$sectionwithinvoicelink.'</td></tr>';
  1273. } else {
  1274. print '<tr><td colspan="4">'.$sectionwithinvoicelink.'</td></tr>';
  1275. }
  1276. }
  1277. print '<tr class="liste_titre nodrag nodrop">';
  1278. print '<td class="linecoldescription">';
  1279. // In phone version only show when it is invoice page
  1280. if (empty($mobilepage) || $mobilepage == "invoice") {
  1281. print '<!-- hidden var used by some js functions -->';
  1282. print '<input type="hidden" name="invoiceid" id="invoiceid" value="'.$invoice->id.'">';
  1283. print '<input type="hidden" name="thirdpartyid" id="thirdpartyid" value="'.$invoice->socid.'">';
  1284. }
  1285. if (getDolGlobalString('TAKEPOS_BAR_RESTAURANT')) {
  1286. $sql = "SELECT floor, label FROM ".MAIN_DB_PREFIX."takepos_floor_tables where rowid=".((int) $place);
  1287. $resql = $db->query($sql);
  1288. $obj = $db->fetch_object($resql);
  1289. if ($obj) {
  1290. $label = $obj->label;
  1291. $floor = $obj->floor;
  1292. }
  1293. if ($mobilepage == "invoice" || $mobilepage == "") {
  1294. // If not on smartphone version or if it is the invoice page
  1295. //print 'mobilepage='.$mobilepage;
  1296. print '<span class="opacitymedium">'.$langs->trans('Place')."</span> <b>".(empty($label) ? '?' : $label)."</b><br>";
  1297. print '<span class="opacitymedium">'.$langs->trans('Floor')."</span> <b>".(empty($floor) ? '?' : $floor)."</b>";
  1298. } elseif (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  1299. print $mysoc->name;
  1300. } elseif ($mobilepage == "cats") {
  1301. print $langs->trans('Category');
  1302. } elseif ($mobilepage == "products") {
  1303. print $langs->trans('Label');
  1304. }
  1305. } else {
  1306. print $langs->trans("Products");
  1307. }
  1308. print '</td>';
  1309. // complete header by hook
  1310. $parameters=array();
  1311. $reshook=$hookmanager->executeHooks('completeTakePosInvoiceHeader', $parameters, $invoice, $action); // Note that $action and $object may have been modified by some hooks
  1312. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1313. print $hookmanager->resPrint;
  1314. if (empty($_SESSION["basiclayout"]) || $_SESSION["basiclayout"] != 1) {
  1315. print '<td class="linecolqty right">'.$langs->trans('ReductionShort').'</td>';
  1316. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  1317. if (getDolGlobalString('TAKEPOS_SHOW_HT')) {
  1318. print '<td class="linecolht right nowraponall">';
  1319. print '<span class="opacitymedium small">' . $langs->trans('TotalHTShort') . '</span><br>';
  1320. // In phone version only show when it is invoice page
  1321. if (empty($mobilepage) || $mobilepage == "invoice") {
  1322. 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>';
  1323. if (isModEnabled('multicurrency') && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
  1324. //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
  1325. include_once DOL_DOCUMENT_ROOT . '/multicurrency/class/multicurrency.class.php';
  1326. $multicurrency = new MultiCurrency($db);
  1327. $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
  1328. 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>';
  1329. }
  1330. print '</td>';
  1331. }
  1332. print '</td>';
  1333. }
  1334. print '<td class="linecolht right nowraponall">';
  1335. print '<span class="opacitymedium small">'.$langs->trans('TotalTTCShort').'</span><br>';
  1336. // In phone version only show when it is invoice page
  1337. if (empty($mobilepage) || $mobilepage == "invoice") {
  1338. 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>';
  1339. if (isModEnabled('multicurrency') && !empty($_SESSION["takeposcustomercurrency"]) && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
  1340. //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
  1341. include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  1342. $multicurrency = new MultiCurrency($db);
  1343. $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
  1344. 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>';
  1345. }
  1346. print '</td>';
  1347. }
  1348. print '</td>';
  1349. } elseif ($mobilepage == "invoice") {
  1350. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  1351. }
  1352. print "</tr>\n";
  1353. if (!empty($_SESSION["basiclayout"]) && $_SESSION["basiclayout"] == 1) {
  1354. if ($mobilepage == "cats") {
  1355. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1356. $categorie = new Categorie($db);
  1357. $categories = $categorie->get_full_arbo('product');
  1358. $htmlforlines = '';
  1359. foreach ($categories as $row) {
  1360. if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  1361. $htmlforlines .= '<div class="leftcat';
  1362. } else {
  1363. $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline';
  1364. }
  1365. $htmlforlines .= '" onclick="LoadProducts('.$row['id'].');">';
  1366. if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  1367. $htmlforlines .= '<img class="imgwrapper" width="33%" src="'.DOL_URL_ROOT.'/takepos/public/auto_order.php?genimg=cat&query=cat&id='.$row['id'].'"><br>';
  1368. } else {
  1369. $htmlforlines .= '<td class="left">';
  1370. }
  1371. $htmlforlines .= $row['label'];
  1372. if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  1373. $htmlforlines .= '</div>'."\n";
  1374. } else {
  1375. $htmlforlines .= '</td></tr>'."\n";
  1376. }
  1377. }
  1378. $htmlforlines .= '</table>';
  1379. $htmlforlines .= '</table>';
  1380. print $htmlforlines;
  1381. }
  1382. if ($mobilepage == "products") {
  1383. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1384. $object = new Categorie($db);
  1385. $catid = GETPOST('catid', 'int');
  1386. $result = $object->fetch($catid);
  1387. $prods = $object->getObjectsInCateg("product");
  1388. $htmlforlines = '';
  1389. foreach ($prods as $row) {
  1390. if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  1391. $htmlforlines .= '<div class="leftcat';
  1392. } else {
  1393. $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline';
  1394. }
  1395. $htmlforlines .= '" onclick="AddProduct(\''.$place.'\', '.$row->id.')">';
  1396. if (defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  1397. $htmlforlines .= '<img class="imgwrapper" width="33%" src="'.DOL_URL_ROOT.'/takepos/public/auto_order.php?genimg=pro&query=pro&id='.$row->id.'"><br>';
  1398. $htmlforlines .= $row->label.' '.price($row->price_ttc, 1, $langs, 1, -1, -1, $conf->currency);
  1399. $htmlforlines .= '</div>'."\n";
  1400. } else {
  1401. $htmlforlines .= '<td class="left">';
  1402. $htmlforlines .= $row->label;
  1403. $htmlforlines .= '<div class="right">'.price($row->price_ttc, 1, $langs, 1, -1, -1, $conf->currency).'</div>';
  1404. $htmlforlines .= '</tr>'."\n";
  1405. }
  1406. }
  1407. $htmlforlines .= '</table>';
  1408. print $htmlforlines;
  1409. }
  1410. if ($mobilepage == "places") {
  1411. $sql = "SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables";
  1412. $resql = $db->query($sql);
  1413. $rows = array();
  1414. $htmlforlines = '';
  1415. while ($row = $db->fetch_array($resql)) {
  1416. $rows[] = $row;
  1417. $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline';
  1418. $htmlforlines .= '" onclick="LoadPlace(\''.$row['label'].'\')">';
  1419. $htmlforlines .= '<td class="left">';
  1420. $htmlforlines .= $row['label'];
  1421. $htmlforlines .= '</td>';
  1422. $htmlforlines .= '</tr>'."\n";
  1423. }
  1424. $htmlforlines .= '</table>';
  1425. print $htmlforlines;
  1426. }
  1427. }
  1428. if ($placeid > 0) {
  1429. //In Phone basic layout hide some content depends situation
  1430. if (!empty($_SESSION["basiclayout"]) && $_SESSION["basiclayout"] == 1 && $mobilepage != "invoice" && $action != "order") {
  1431. return;
  1432. }
  1433. if (is_array($invoice->lines) && count($invoice->lines)) {
  1434. print '<!-- invoice.php show lines of invoices -->'."\n";
  1435. $tmplines = array_reverse($invoice->lines);
  1436. $htmlsupplements = array();
  1437. foreach ($tmplines as $line) {
  1438. if ($line->fk_parent_line != false) {
  1439. $htmlsupplements[$line->fk_parent_line] .= '<tr class="drag drop oddeven posinvoiceline';
  1440. if ($line->special_code == "4") {
  1441. $htmlsupplements[$line->fk_parent_line] .= ' order';
  1442. }
  1443. $htmlsupplements[$line->fk_parent_line] .= '" id="'.$line->id.'"';
  1444. if ($line->special_code == "4") {
  1445. $htmlsupplements[$line->fk_parent_line] .= ' title="'.dol_escape_htmltag($langs->trans("AlreadyPrinted")).'"';
  1446. }
  1447. $htmlsupplements[$line->fk_parent_line] .= '>';
  1448. $htmlsupplements[$line->fk_parent_line] .= '<td class="left">';
  1449. $htmlsupplements[$line->fk_parent_line] .= img_picto('', 'rightarrow');
  1450. if ($line->product_label) {
  1451. $htmlsupplements[$line->fk_parent_line] .= $line->product_label;
  1452. }
  1453. if ($line->product_label && $line->desc) {
  1454. $htmlsupplements[$line->fk_parent_line] .= '<br>';
  1455. }
  1456. if ($line->product_label != $line->desc) {
  1457. $firstline = dolGetFirstLineOfText($line->desc);
  1458. if ($firstline != $line->desc) {
  1459. $htmlsupplements[$line->fk_parent_line] .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc);
  1460. } else {
  1461. $htmlsupplements[$line->fk_parent_line] .= $line->desc;
  1462. }
  1463. }
  1464. $htmlsupplements[$line->fk_parent_line] .= '</td>';
  1465. // complete line by hook
  1466. $parameters=array('line' => $line);
  1467. $reshook=$hookmanager->executeHooks('completeTakePosInvoiceParentLine', $parameters, $invoice, $action); // Note that $action and $object may have been modified by some hooks
  1468. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1469. $htmlsupplements[$line->fk_parent_line] .= $hookmanager->resPrint;
  1470. if (empty($_SESSION["basiclayout"]) || $_SESSION["basiclayout"] != 1) {
  1471. $htmlsupplements[$line->fk_parent_line] .= '<td class="right">'.vatrate($line->remise_percent, true).'</td>';
  1472. $htmlsupplements[$line->fk_parent_line] .= '<td class="right">'.$line->qty.'</td>';
  1473. $htmlsupplements[$line->fk_parent_line] .= '<td class="right">'.price($line->total_ttc).'</td>';
  1474. }
  1475. $htmlsupplements[$line->fk_parent_line] .= '</tr>'."\n";
  1476. continue;
  1477. }
  1478. $htmlforlines = '';
  1479. $htmlforlines .= '<tr class="drag drop oddeven posinvoiceline';
  1480. if ($line->special_code == "4") {
  1481. $htmlforlines .= ' order';
  1482. }
  1483. $htmlforlines .= '" id="'.$line->id.'"';
  1484. if ($line->special_code == "4") {
  1485. $htmlforlines .= ' title="'.dol_escape_htmltag($langs->trans("AlreadyPrinted")).'"';
  1486. }
  1487. $htmlforlines .= '>';
  1488. $htmlforlines .= '<td class="left">';
  1489. if (!empty($_SESSION["basiclayout"]) && $_SESSION["basiclayout"] == 1) {
  1490. $htmlforlines .= '<span class="phoneqty">'.$line->qty."</span> x ";
  1491. }
  1492. if (isset($line->product_type)) {
  1493. if (empty($line->product_type)) {
  1494. $htmlforlines .= img_object('', 'product').' ';
  1495. } else {
  1496. $htmlforlines .= img_object('', 'service').' ';
  1497. }
  1498. }
  1499. if (empty($conf->global->TAKEPOS_SHOW_N_FIRST_LINES)) {
  1500. $tooltiptext = '';
  1501. if ($line->product_ref) {
  1502. $tooltiptext .= '<b>'.$langs->trans("Ref").'</b> : '.$line->product_ref.'<br>';
  1503. $tooltiptext .= '<b>'.$langs->trans("Label").'</b> : '.$line->product_label.'<br>';
  1504. if ($line->product_label != $line->desc) {
  1505. if ($line->desc) {
  1506. $tooltiptext .= '<br>';
  1507. }
  1508. $tooltiptext .= $line->desc;
  1509. }
  1510. }
  1511. if (getDolGlobalInt('TAKEPOS_SHOW_PRODUCT_REFERENCE') == 1) {
  1512. $htmlforlines .= $form->textwithpicto($line->product_label ? '<b>' . $line->product_ref . '</b> - ' . $line->product_label : dolGetFirstLineOfText($line->desc, 1), $tooltiptext);
  1513. } elseif (getDolGlobalInt('TAKEPOS_SHOW_PRODUCT_REFERENCE') == 2) {
  1514. $htmlforlines .= $form->textwithpicto($line->product_ref ? '<b>'.$line->product_ref.'<b>' : dolGetFirstLineOfText($line->desc, 1), $tooltiptext);
  1515. } else {
  1516. $htmlforlines .= $form->textwithpicto($line->product_label ? $line->product_label : ($line->product_ref ? $line->product_ref : dolGetFirstLineOfText($line->desc, 1)), $tooltiptext);
  1517. }
  1518. } else {
  1519. if ($line->product_label) {
  1520. $htmlforlines .= $line->product_label;
  1521. }
  1522. if ($line->product_label != $line->desc) {
  1523. if ($line->product_label && $line->desc) {
  1524. $htmlforlines .= '<br>';
  1525. }
  1526. $firstline = dolGetFirstLineOfText($line->desc, $conf->global->TAKEPOS_SHOW_N_FIRST_LINES);
  1527. if ($firstline != $line->desc) {
  1528. $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc);
  1529. } else {
  1530. $htmlforlines .= $line->desc;
  1531. }
  1532. }
  1533. }
  1534. if (!empty($line->array_options['options_order_notes'])) {
  1535. $htmlforlines .= "<br>(".$line->array_options['options_order_notes'].")";
  1536. }
  1537. if (!empty($_SESSION["basiclayout"]) && $_SESSION["basiclayout"] == 1) {
  1538. $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>';
  1539. }
  1540. if (empty($_SESSION["basiclayout"]) || $_SESSION["basiclayout"] != 1) {
  1541. $moreinfo = '';
  1542. $moreinfo .= $langs->transcountry("TotalHT", $mysoc->country_code).': '.price($line->total_ht);
  1543. if ($line->vat_src_code) {
  1544. $moreinfo .= '<br>'.$langs->trans("VATCode").': '.$line->vat_src_code;
  1545. }
  1546. $moreinfo .= '<br>'.$langs->transcountry("TotalVAT", $mysoc->country_code).': '.price($line->total_tva);
  1547. $moreinfo .= '<br>'.$langs->transcountry("TotalLT1", $mysoc->country_code).': '.price($line->total_localtax1);
  1548. $moreinfo .= '<br>'.$langs->transcountry("TotalLT2", $mysoc->country_code).': '.price($line->total_localtax2);
  1549. $moreinfo .= '<hr>';
  1550. $moreinfo .= $langs->transcountry("TotalTTC", $mysoc->country_code).': '.price($line->total_ttc);
  1551. //$moreinfo .= $langs->trans("TotalHT").': '.$line->total_ht;
  1552. if ($line->date_start || $line->date_end) {
  1553. $htmlforlines .= '<br><div class="clearboth nowraponall">'.get_date_range($line->date_start, $line->date_end).'</div>';
  1554. }
  1555. $htmlforlines .= '</td>';
  1556. // complete line by hook
  1557. $parameters=array('line' => $line);
  1558. $reshook=$hookmanager->executeHooks('completeTakePosInvoiceLine', $parameters, $invoice, $action); // Note that $action and $object may have been modified by some hooks
  1559. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1560. $htmlforlines .= $hookmanager->resPrint;
  1561. $htmlforlines .= '<td class="right">'.vatrate($line->remise_percent, true).'</td>';
  1562. $htmlforlines .= '<td class="right">';
  1563. if (isModEnabled('stock') && $user->hasRight('stock', 'mouvement', 'lire')) {
  1564. $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"];
  1565. if (getDolGlobalString($constantforkey) && $line->fk_product > 0 && empty($conf->global->TAKEPOS_HIDE_STOCK_ON_LINE)) {
  1566. $sql = "SELECT e.rowid, e.ref, e.lieu, e.fk_parent, e.statut, ps.reel, ps.rowid as product_stock_id, p.pmp";
  1567. $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,";
  1568. $sql .= " ".MAIN_DB_PREFIX."product_stock as ps";
  1569. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = ps.fk_product";
  1570. $sql .= " WHERE ps.reel != 0";
  1571. $sql .= " AND ps.fk_entrepot = ".((int) getDolGlobalString($constantforkey));
  1572. $sql .= " AND e.entity IN (".getEntity('stock').")";
  1573. $sql .= " AND ps.fk_product = ".((int) $line->fk_product);
  1574. $resql = $db->query($sql);
  1575. if ($resql) {
  1576. $obj = $db->fetch_object($resql);
  1577. $stock_real = price2num($obj->reel, 'MS');
  1578. $htmlforlines .= $line->qty;
  1579. if ($line->qty && $line->qty > $stock_real) {
  1580. $htmlforlines .= '<span style="color: var(--amountremaintopaycolor)">';
  1581. }
  1582. $htmlforlines .= ' <span class="posstocktoolow">('.$langs->trans("Stock").' '.$stock_real.')</span>';
  1583. if ($line->qty && $line->qty > $stock_real) {
  1584. $htmlforlines .= "</span>";
  1585. }
  1586. } else {
  1587. dol_print_error($db);
  1588. }
  1589. } else {
  1590. $htmlforlines .= $line->qty;
  1591. }
  1592. } else {
  1593. $htmlforlines .= $line->qty;
  1594. }
  1595. $htmlforlines .= '</td>';
  1596. if (getDolGlobalInt('TAKEPOS_SHOW_HT')) {
  1597. $htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">';
  1598. $htmlforlines .= price($line->total_ht, 1, '', 1, -1, -1, $conf->currency);
  1599. if (isModEnabled('multicurrency') && !empty($_SESSION["takeposcustomercurrency"]) && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
  1600. //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
  1601. include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  1602. $multicurrency = new MultiCurrency($db);
  1603. $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
  1604. $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>';
  1605. }
  1606. $htmlforlines .= '</td>';
  1607. }
  1608. $htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">';
  1609. $htmlforlines .= price($line->total_ttc, 1, '', 1, -1, -1, $conf->currency);
  1610. if (isModEnabled('multicurrency') && !empty($_SESSION["takeposcustomercurrency"]) && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
  1611. //Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
  1612. include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  1613. $multicurrency = new MultiCurrency($db);
  1614. $multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
  1615. $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>';
  1616. }
  1617. $htmlforlines .= '</td>';
  1618. }
  1619. $htmlforlines .= '</tr>'."\n";
  1620. $htmlforlines .= empty($htmlsupplements[$line->id]) ? '' : $htmlsupplements[$line->id];
  1621. print $htmlforlines;
  1622. }
  1623. } else {
  1624. print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td>';
  1625. if (!empty($conf->global->TAKEPOS_SHOW_HT)) {
  1626. print '<td></td>';
  1627. }
  1628. print '</tr>';
  1629. }
  1630. } else { // No invoice generated yet
  1631. print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td>';
  1632. if (!empty($conf->global->TAKEPOS_SHOW_HT)) {
  1633. print '<td></td>';
  1634. }
  1635. print '</tr>';
  1636. }
  1637. print '</table>';
  1638. if (($action == "valid" || $action == "history") && $invoice->type != Facture::TYPE_CREDIT_NOTE && empty($conf->global->TAKEPOS_NO_CREDITNOTE)) {
  1639. print '<button id="buttonprint" type="button" onclick="ModalBox(\'ModalCreditNote\')">'.$langs->trans('CreateCreditNote').'</button>';
  1640. if (getDolGlobalInt('TAKEPOS_PRINT_INVOICE_DOC_INSTEAD_OF_RECEIPT')) {
  1641. print ' <a target="_blank" class="button" href="' . DOL_URL_ROOT . '/document.php?token=' . newToken() . '&modulepart=facture&file=' . $invoice->ref . '/' . $invoice->ref . '.pdf">Invoice</a>';
  1642. }
  1643. }
  1644. if ($action == "search") {
  1645. print '<center>
  1646. <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')).'">
  1647. </center>';
  1648. }
  1649. print '</div>';
  1650. // llxFooter
  1651. if ((getDolGlobalString('TAKEPOS_PHONE_BASIC_LAYOUT') == 1 && $conf->browser->layout == 'phone') || defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
  1652. print '</body></html>';
  1653. }