invoice.php 87 KB

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