invoice.php 70 KB

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