invoice.php 83 KB

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