invoice.php 70 KB

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