api_bbus.class.php 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use Luracast\Restler\RestException;
  19. use Sabre\Xml\Element;
  20. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  21. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php';
  22. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
  23. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  24. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttribute.class.php';
  25. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttributeValue.class.php';
  26. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductCombination.class.php';
  27. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductCombination2ValuePair.class.php';
  28. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/sellproduct.class.php';
  29. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiuserhandler.class.php';
  30. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  31. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/jegy.class.php';
  32. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbloginlog.class.php';
  33. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbexchangerate.class.php';
  34. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticket.class.php';
  35. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbdevices.class.php';
  36. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbdevicesservicelocation.class.php';
  37. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbdevicesservicelocationproduct.class.php';
  38. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketinvoiceprinting.class.php';
  39. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/utils/globalconst.class.php';
  40. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/utils/emailtemplatehandler.php';
  41. include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
  42. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketnaplo.class.php';
  43. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbtickethandler.class.php';
  44. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/gpsposition.class.php';
  45. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/userloginnaplo.class.php';
  46. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/utils/countryhandler.class.php';
  47. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/utils/entityhandler.class.php';
  48. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/discountnaplo.class.php';
  49. require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/groupusers.class.php';
  50. require_once DOL_DOCUMENT_ROOT . '/custom/rollerstorage/class/packagehistory.class.php';
  51. require_once DOL_DOCUMENT_ROOT . '/product/inventory/class/inventory.class.php';
  52. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiproductlisthelper.class.php';
  53. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiinvoicehelper.class.php';
  54. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/ticket_checker.class.php';
  55. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_helper.class.php';
  56. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_log.class.php';
  57. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbapilock.class.php';
  58. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/exchangerateupdater.class.php';
  59. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketvalidationcoords.class.php';
  60. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
  61. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/roller_handling.class.php';
  62. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/product_sync.class.php';
  63. /**
  64. * API class for products
  65. *
  66. * @access protected
  67. * @class DolibarrApiAccess {@requires user,external}
  68. */
  69. class BBus extends DolibarrApi
  70. {
  71. use CurlApi;
  72. use RollerHandling;
  73. use ProductSync;
  74. private $code;
  75. private $printingTime;
  76. private $status = 0;
  77. private $device_id;
  78. private $service_location_id;
  79. private $bbTicketRowId;
  80. private $facture_id;
  81. private $isValid = true;
  82. private User $user;
  83. const EMAIL_TEMPLATE = 'multiticketprinting';
  84. const GLOBAL_CONF_SEND_TO_EMAIL = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL';
  85. const GLOBAL_CONF_EMAIL_FROM = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL_FROM';
  86. public function __construct()
  87. {
  88. global $db, $conf, $user;
  89. $this->db = $db;
  90. $this->user = $user;
  91. }
  92. /**
  93. * First ticket validation
  94. *
  95. * @param string $code
  96. *
  97. * @return array|mixed Data without useless information
  98. *
  99. * @url POST search
  100. */
  101. public function search($code)
  102. {
  103. $this->checkUserReadPermission();
  104. global $user;
  105. $this->code = $code;
  106. $this->facture_id = $this->getFactureRowIdByFactureId();
  107. $sql = "SELECT bt.*, pr.ref as product_ref, pr.label as product_label, btp.printing_date, btp.printing_date_timestamp
  108. FROM llx_bbus_bbticketinvoiceprinting as btp
  109. INNER JOIN llx_bbus_bbticket AS bt ON bt.rowid = btp.ticket_id
  110. INNER JOIN llx_product AS pr ON pr.rowid = bt.ticket_id
  111. WHERE btp.fk_facture = {$this->facture_id}
  112. AND btp.printing_date = (
  113. SELECT MIN(printing_date)
  114. FROM llx_bbus_bbticketinvoiceprinting AS btp2
  115. WHERE btp2.fk_facture = {$this->facture_id}
  116. )";
  117. $ticketsData = $this->db->query($sql);
  118. while ($row = pg_fetch_assoc($ticketsData)) {
  119. $now = date("Y-m-d H:i:s");
  120. if ($row['usage'] == $row['usable_occasions'] && $row['usable_occasions'] != 0) {
  121. $this->isValid = false;
  122. }
  123. if ($row['available_at'] < $now || ((!is_null($row['expire_at']) && !empty($row['expire_at'])) && $row['expire_at'] < $now)) {
  124. $this->isValid = false;
  125. }
  126. $row['facture_ref'] = $code;
  127. $row['isValid'] = $this->isValid;
  128. $sub = [];
  129. foreach ($row as $key => $value) {
  130. $sub[$key] = $value;
  131. }
  132. $json[] = $sub;
  133. }
  134. return $json;
  135. }
  136. /**
  137. * Értékesítések
  138. *
  139. * @param date $date Date
  140. *
  141. *
  142. * @return array|mixed Data without useless information
  143. *
  144. * @url POST getsaleditems
  145. */
  146. public function getsaleditems($date = null)
  147. {
  148. global $user;
  149. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  150. throw new RestException(403);
  151. }
  152. //$date = isset($date) ? $date : date("Y-m-d");
  153. $date = date("Y-m-d");
  154. $apiBbusHelper = new ApiBBusHelper();
  155. $facturesArray = $apiBbusHelper->getSaledItems($date);
  156. return $apiBbusHelper->getSaledItemsArray($facturesArray);
  157. }
  158. /** LOG OK
  159. * Get properties of a product object by barcode
  160. *
  161. * Return an array with product information.
  162. *
  163. * @param string $code Facture ID and timestamp of printing
  164. *
  165. * @return array|mixed Data without useless information
  166. *
  167. * @url POST ticketinfos
  168. */
  169. public function getinfos($code)
  170. {
  171. global $user;
  172. $ticketChecker = new TicketChecker();
  173. ApiBbusLog::getinfosLog('=== NEW TICKETINFOS ===');
  174. ApiBbusLog::getinfosLog("User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
  175. ApiBbusLog::getinfosLog("DOLAPIKEY: {$user->api_key}");
  176. $ticketsFromBbticketinvoiceprinting = [];
  177. $code_and_timstamp = explode('_', $code);
  178. $this->code = $code_and_timstamp[0];
  179. if (empty($this->code)) {
  180. ApiBbusLog::getinfosLog('Code or mac is empty!');
  181. ApiBbusLog::getinfosLog('=================');
  182. throw new RestException(404, 'Code or mac is empty!');
  183. }
  184. $this->printingTime = $code_and_timstamp[1];
  185. if (empty($this->printingTime)) {
  186. ApiBbusLog::getinfosLog('Timestamp is empty!');
  187. ApiBbusLog::getinfosLog('=================');
  188. throw new RestException(404, 'Timestamp is empty!');
  189. }
  190. if (!DolibarrApiAccess::$user->rights->bbus->ticket->validation) {
  191. ApiBbusLog::getinfosLog('No access: Ticket Validation!');
  192. ApiBbusLog::getinfosLog('=================');
  193. throw new RestException(403);
  194. }
  195. ApiBbusLog::getinfosLog("Code: {$this->code}");
  196. ApiBbusLog::getinfosLog("Code: {$this->printingTime}");
  197. //Kikeresem a facture_id-t
  198. $facture = new Facture($this->db);
  199. $sql = "SELECT * FROM " . $this->db->prefix() . $facture->table_element . " WHERE ref ILIKE '{$this->code}'";
  200. $factureResult = $this->db->query($sql);
  201. if (pg_num_rows($factureResult) < 1) {
  202. ApiBbusLog::getinfosLog('Invoice not found!');
  203. ApiBbusLog::getinfosLog('=================');
  204. throw new RestException(404, 'Invoice not found!');
  205. }
  206. while ($row = pg_fetch_assoc($factureResult)) {
  207. $selectedFacture_id = $row['rowid'];
  208. }
  209. ApiBbusLog::getinfosLog('Facture ID: ' . (string) $selectedFacture_id);
  210. $sql = "SELECT rowid FROM " . $this->db->prefix() . $facture->table_element . " WHERE fk_facture_source = {$selectedFacture_id} AND type = 2";
  211. $res = $this->db->query($sql);
  212. if (pg_num_rows($res) > 0) {
  213. ApiBbusLog::getinfosLog('Invoice has a Credit account!');
  214. ApiBbusLog::getinfosLog('=================');
  215. throw new RestException(404, 'Invoice has a Credit account.');
  216. }
  217. // Kikeresem az llx_bbus_bbticketinvoiceprinting táblából a timestamp-hez tartozo jegy Id(ka)t
  218. $bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
  219. $result = $bbticketinvoiceprinting->fetchAll('', '', 0, 0, ['customsql' => "printing_date_timestamp = '{$this->printingTime}' AND fk_facture = {$selectedFacture_id}"]);
  220. $this->checkResult($result, 'bbticketinvoiceprinting');
  221. foreach ($result as $device) {
  222. $ticketsFromBbticketinvoiceprinting[] = $device->ticket_id;
  223. }
  224. $inString = implode(', ', $ticketsFromBbticketinvoiceprinting);
  225. //echo $inString;exit;
  226. // A ticket_id alapjan, hogy a jegyek kozott szerepel-e es ervenyes-e
  227. $bbticket = new BbTicket($this->db);
  228. $sql = "SELECT tic.rowid as ticketrowid, tic.*, bbd.*, fac.* FROM " . $this->db->prefix() . $bbticket->table_element . " AS tic
  229. INNER JOIN public.llx_product as bbd ON tic.ticket_id = bbd.rowid
  230. INNER JOIN public.llx_facture as fac ON tic.fk_facture = fac.rowid
  231. WHERE tic.rowid IN ({$inString})";
  232. $statement = $this->db->query($sql);
  233. while ($row = pg_fetch_assoc($statement)) {
  234. $sub = [];
  235. foreach ($row as $key => $value) {
  236. $sub[$key] = $value;
  237. }
  238. $sub['error'] = false;
  239. if (strtotime($sub['available_at']) < dol_now()) {
  240. $sub['error'] = true;
  241. $sub['errorCode'] = 1;
  242. $sub['errorDate'] = $sub['available_at'];
  243. ApiBbusLog::getinfosLog('Status: Expired! Too Old.' . $sub['available_at']);
  244. ApiBbusLog::getinfosLog('=====================');
  245. } elseif (!is_null($sub['expire_at']) && strtotime($sub['expire_at']) < dol_now() ) {
  246. $sub['error'] = true;
  247. $sub['errorCode'] = 2;
  248. $sub['errorDate'] = $sub['expire_at'];
  249. ApiBbusLog::getinfosLog('Status: Expired!' . $sub['expire_at']);
  250. ApiBbusLog::getinfosLog('=====================');
  251. }
  252. if (intval($sub['usage']) > 0) {
  253. $sub['error'] = true;
  254. $sub['errorCode'] = 3;
  255. $sub['errorDate'] = $sub['validated_at'];
  256. ApiBbusLog::getinfosLog('Status: Used ticket' . $sub['validated_at']);
  257. ApiBbusLog::getinfosLog('=====================');
  258. }
  259. $sub['ticket_type'] = $ticketChecker->getTicketTypeByProductId($row['ticket_id']);
  260. $json[] = $sub;
  261. }
  262. ApiBbusLog::getinfosLog(json_encode($json));
  263. ApiBbusLog::getinfosLog('Status: OK!');
  264. ApiBbusLog::getinfosLog('=====================');
  265. return $json;
  266. }
  267. /**
  268. * Get properties of a product object by barcode
  269. *
  270. * Return an array with product information.
  271. *
  272. *
  273. * @return array|mixed Data without useless information
  274. *
  275. * @url GET product
  276. */
  277. public function getProducts()
  278. {
  279. global $user;
  280. $productsArray = [];
  281. $products = new Product($this->db);
  282. $sql = "SELECT price, default_vat_code, rowid FROM " . $this->db->prefix() . $products->table_element . " WHERE fk_product_type = 1 ORDER BY rowid ASC";
  283. $res = $this->db->query($sql);
  284. while ($row = pg_fetch_assoc($res)) {
  285. $productsArray[$row['rowid']] = $row;
  286. }
  287. return 'OK';
  288. }
  289. /** LOG OK
  290. * Validate a product bbticket id.
  291. *
  292. * Return an array with product validation data.
  293. *
  294. * @param string $code Facture ID and timestamp of printing
  295. * @param string $ticketid Ticketid (bbticket rowid)
  296. * @param string $imei IMEI (Mobile IMEI number)
  297. *
  298. * @return array|mixed Data without useless information
  299. *
  300. * @url POST ticketvalidationbyphone
  301. */
  302. public function validateTicket($code, $ticketid, $imei)
  303. {
  304. global $user;
  305. $logId = ApiBbusLog::getLogId();
  306. ApiBbusLog::ticketvalidationByPhone("{$logId} === NEW TICKETVALIDATION BY PHONE ===");
  307. ApiBbusLog::ticketvalidationByPhone("{$logId} User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
  308. ApiBbusLog::ticketvalidationByPhone("{$logId} DOLAPIKEY: {$user->api_key}");
  309. ApiBbusLog::ticketvalidationByPhone("{$logId} code: {$code}");
  310. $ticketChecker = new TicketChecker();
  311. $ticketChecker->setCode($code);
  312. $ticketChecker->setTimestamp($code, 'ticketvalidationByPhone', $logId);
  313. $ticketChecker->SetTicketidFromPhone($ticketid, $logId);
  314. $ticketChecker->setImei($imei, $logId);
  315. $this->checkUserValidatePermission();
  316. $ticketChecker->setFactureId('ticketvalidationByPhone', $logId);
  317. $ticketChecker->checkBbTicketInvoicePrinting();
  318. $selectedTicket = $ticketChecker->getDataOfTheSelectedTicket();
  319. $ticketChecker->setBbTicketRowId($selectedTicket->id);
  320. $ticketChecker->checkExceptionHandlers($selectedTicket, 'ticketvalidationByPhone', $logId);
  321. $ticketChecker->setMergedTickets($selectedTicket, 'ticketvalidationByPhone', $logId);
  322. $ticketChecker->saveData($selectedTicket);
  323. ApiBbusLog::ticketvalidationByPhone("{$logId} Status: OK!");
  324. ApiBbusLog::ticketvalidationByPhone("{$logId} =================");
  325. return 'OK';
  326. }
  327. /** LOG OK
  328. * Get properties of a product object by barcode
  329. *
  330. * Return an array with product information.
  331. *
  332. * @param string $code Facture ID and timestamp of printing
  333. * @param string $mac MAC adress of the device
  334. *
  335. * @return array|mixed Data without useless information
  336. *
  337. * @url POST barcode
  338. *
  339. * @throws RestException 401
  340. * @throws RestException 403
  341. * @throws RestException 404
  342. */
  343. public function getByBarcode(string $code, string $mac, string $lat = null, string $lon = null)
  344. {
  345. global $user;
  346. $logId = ApiBbusLog::getLogId();
  347. ApiBbusLog::getByBarcode("{$logId} === NEW OBU validation ===");
  348. ApiBbusLog::getByBarcode("{$logId} User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
  349. ApiBbusLog::getByBarcode("{$logId} DOLAPIKEY: {$user->api_key}");
  350. $bbticket = new BbTicket($this->db);
  351. $ticketChecker = new TicketChecker();
  352. if (empty($code) || empty($mac)) {
  353. ApiBbusLog::getByBarcode("{$logId} Code or mac is empty!");
  354. throw new RestException(404, 'Code or mac is empty!');
  355. }
  356. ApiBbusLog::getByBarcode("{$logId} Code: " . $code);
  357. ApiBbusLog::getByBarcode("{$logId} MAC: " . $mac);
  358. ApiBbusLog::getByBarcode("{$logId} Latitude: " . $lat);
  359. ApiBbusLog::getByBarcode("{$logId} Longitude: " . $lon);
  360. $ticketChecker->setMac($mac);
  361. $ticketChecker->setCode($code);
  362. $ticketChecker->setLat($lat);
  363. $ticketChecker->setLon($lon);
  364. $ticketChecker->setTimestamp($code, 'getByBarcode', $logId);
  365. $this->checkUserReadPermission();
  366. $ticketChecker->setFactureId('getByBarcode', $logId);
  367. $ticketChecker->setFilsArray();
  368. $ticketChecker->setTicketId($logId);
  369. $selectedTicket = $ticketChecker->getDataOfTheSelectedTicket();
  370. $ticketChecker->setBbTicketRowId($selectedTicket->id);
  371. $ticketChecker->check5Minutes($logId);
  372. $ticketChecker->checkExceptionHandlers($selectedTicket, 'getByBarcode', $logId);
  373. $ticketChecker->setMergedTickets($selectedTicket, 'getByBarcode', $logId);
  374. $ticketChecker->saveCoordinates($logId);
  375. $ticketChecker->saveData($selectedTicket);
  376. ApiBbusLog::getByBarcode("{$logId} Status: OK!");
  377. ApiBbusLog::getByBarcode("{$logId} =================");
  378. return 'OK';
  379. }
  380. /**
  381. * curlGetFilsArray
  382. *
  383. * Return an array with success information.
  384. *
  385. * @param string $ref
  386. *
  387. * @return array|mixed Data without useless information
  388. *
  389. * @url POST curlGetFilsArray
  390. *
  391. * @throws RestException 401
  392. * @throws RestException 403
  393. * @throws RestException 404
  394. */
  395. public function curlGetFilsArray($ref)
  396. {
  397. $fils = [];
  398. $sqlFAC = "SELECT rowid FROM llx_facture WHERE ref = '{$ref}'";
  399. $resultFAC = $this->db->query($sqlFAC);
  400. if ($this->db->num_rows($resultFAC)) {
  401. while ($facture = $this->db->fetch_object($resultFAC)) {
  402. $sql = "SELECT fdet.fk_product FROM llx_facture AS f
  403. INNER JOIN llx_facturedet as fdet ON fdet.fk_facture = f.rowid
  404. WHERE f.rowid = {$facture->rowid}";
  405. $result = $this->db->query($sql);
  406. while ($sqlDataResult = pg_fetch_assoc($result)) {
  407. $fils[] = $sqlDataResult['fk_product'];
  408. }
  409. }
  410. }
  411. return $fils;
  412. }
  413. /**
  414. * Post invoice ref and creation date for data recording
  415. *
  416. * Return an array with success information.
  417. *
  418. * @param string $ref Facture ref
  419. * @param string $datetime invoice creation date
  420. *
  421. * @return array|mixed Data without useless information
  422. *
  423. * @url POST printdate
  424. *
  425. * @throws RestException 401
  426. * @throws RestException 403
  427. * @throws RestException 404
  428. */
  429. public function dateHandler(string $ref, string $datetime)
  430. {
  431. global $user, $conf;
  432. ApiBbusLog::appLog("dateHandler");
  433. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  434. throw new RestException(403);
  435. }
  436. if (empty($ref)) {
  437. throw new RestException(401, 'Empty ref!');
  438. }
  439. if (empty($datetime)) {
  440. throw new RestException(401, 'Empty datetime!');
  441. }
  442. ApiBbusLog::appLog("dateHandler: Access granted");
  443. $printDate = DateTime::createFromFormat('Y-m-d H:i:s', $datetime);
  444. $now = new DateTime('now');
  445. $now = (clone $now)->modify('+2 minutes');
  446. $validDate = (clone $now)->modify('-5 minutes');
  447. $datetime = $printDate->format('Y-m-d H:i:s');
  448. $datetime_timestamp = strtotime($datetime);
  449. dol_syslog('printDate: ' . print_r($printDate, true), LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  450. dol_syslog('now: ' . print_r($now, true), LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  451. dol_syslog('validDate: ' . print_r($validDate, true), LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  452. //print_r($validDate);
  453. //print_r($printDate);
  454. //print_r($now);
  455. $server_host = $conf->global->LOCAL_SERVER_HOST;
  456. $sqlServerHost = "SELECT bbbs.server_host FROM llx_facture as f
  457. INNER JOIN llx_facturedet as fdet ON fdet.fk_facture = f.rowid
  458. INNER JOIN llx_product_extrafields as pe ON pe.fk_object = fdet.fk_product
  459. INNER JOIN llx_bbus_basicservices as bbbs ON bbbs.rowid = CAST(pe.basic_service AS integer)
  460. WHERE f.ref = '{$ref}'";
  461. $resultSH = $this->db->query($sqlServerHost);
  462. if ($this->db->num_rows($resultSH) > 0) {
  463. while ($row = $this->db->fetch_object($resultSH)) {
  464. $server_host = $row->server_host;
  465. }
  466. }
  467. if ($validDate <= $printDate && $printDate <= $now) {
  468. # Keresztvásárlás
  469. if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
  470. ApiBbusLog::appLog("dateHandler: local");
  471. ApiBbusLog::appLog("dateHandler: {$datetime_timestamp}");
  472. $this->localDateHandler($ref, $datetime, $datetime_timestamp, $now);
  473. } else {
  474. ApiBbusLog::appLog("dateHandler: curl");
  475. $this->curlDateHandler($ref, $datetime);
  476. }
  477. } else {
  478. ApiBbusLog::appLog("dateHandler: Invalid date");
  479. throw new RestException(401, 'Invalid date');
  480. }
  481. return 'OK';
  482. }
  483. private function localDateHandler($ref, $datetime, $datetime_timestamp, $now)
  484. {
  485. global $user;
  486. $helper = new ApiBBusHelper();
  487. $facture_id = $helper->getFactureIdForInvoicePrinting($ref);
  488. if (empty($facture_id)) {
  489. ApiBbusLog::appLog("localDateHandler: no facture_id because cross-shopping");
  490. $printedCopies = $this->checkPrintedCopiesWithRef($ref);
  491. } else {
  492. $printedCopies = $this->checkPrintedCopies($facture_id);
  493. }
  494. // Leellenőrzöm, hogy a számla volt-e már nyomtatva
  495. ApiBbusLog::appLog("printedCopies: {$printedCopies}");
  496. if ($printedCopies == 0) {
  497. ApiBbusLog::appLog("printedCopies: no copies");
  498. if (empty($facture_id)) {
  499. ApiBbusLog::appLog("No facture_id");
  500. $bbTicketsByFacture = $this->getTicketsByInvoiceNumber($ref);
  501. } else {
  502. ApiBbusLog::appLog("Facture_id: " . $facture_id);
  503. $bbTicketsByFacture = $this->getTicketsByFactureId($facture_id);
  504. }
  505. foreach ($bbTicketsByFacture as $ticket) {
  506. ApiBbusLog::appLog("Create BBticketInvoiceprinting record");
  507. // Rogzitem a bbticketinvoiceprinting tablaba a rekordot
  508. $helper->setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticket, $ref);
  509. }
  510. } else {
  511. ApiBbusLog::appLog("printedCopies: MULTIPRINT");
  512. if (empty($facture_id)) {
  513. $ticketIds = $helper->getTicketIdsForCrossShopping($ref);
  514. } else {
  515. $ticketIds = $helper->getTicketIdsByFactureId($facture_id, $ref);
  516. }
  517. $ticketObj = new stdClass();
  518. foreach ($ticketIds as $key => $value) {
  519. // Rogzitem a bbticketinvoiceprinting tablaba a rekordot
  520. $ticketObj->id = $key;
  521. $ticketObj->ticket_id = $value;
  522. $helper->setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticketObj, $ref);
  523. }
  524. // e-mail küldése
  525. $helper->sendMail($facture_id, $datetime, $now->format('Y-m-d H:i:s'));
  526. return 'Multiprinting';
  527. }
  528. }
  529. /* private function localDateHandler($ref, $datetime, $datetime_timestamp, $now)
  530. {
  531. global $user;
  532. $helper = new ApiBBusHelper();
  533. $facture_id = $helper->getFactureIdForInvoicePrinting($ref);
  534. // Leellenőrzöm, hogy a számla volt-e már nyomtatva
  535. $printedCopies = $this->checkPrintedCopies($facture_id);
  536. if ($printedCopies == 0) {
  537. $bbTicketsByFacture = $this->getTicketsByFactureId($facture_id);
  538. foreach ($bbTicketsByFacture as $ticket) {
  539. // Rogzitem a bbticketinvoiceprinting tablaba a rekordot
  540. $helper->setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticket, $ref);
  541. }
  542. } else {
  543. $ticketIds = $helper->getTicketIdsByFactureId($facture_id);
  544. $ticketObj = new stdClass();
  545. foreach ($ticketIds as $key => $value) {
  546. // Rogzitem a bbticketinvoiceprinting tablaba a rekordot
  547. $ticketObj->id = $key;
  548. $ticketObj->ticket_id = $value;
  549. $helper->setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticketObj, $ref);
  550. }
  551. // e-mail küldése
  552. $helper->sendMail($facture_id, $datetime, $now->format('Y-m-d H:i:s'));
  553. //return 'Multiprinting';
  554. }
  555. } */
  556. public function curlDateHandler($ref, $datetime)
  557. {
  558. $params = compact('ref', 'datetime');
  559. $datehandlerPostFields = json_encode($params);
  560. ApiBbusLog::appLog("dateHandler: {$datehandlerPostFields}");
  561. $this->curlRunner('bbus/printdate', $datehandlerPostFields, 'POST', true);
  562. }
  563. /**
  564. * Save customer data (zip or countrycode) in facture table
  565. *
  566. * Return a result.
  567. *
  568. * @param string $facture_id Facture rowid
  569. * @param string $customerdatazip Customer data ZIP
  570. * @param string $customerdatacountrycode Customer data Countrycode
  571. *
  572. * @return array|mixed Data without useless information
  573. *
  574. * @url POST customerDataHandler
  575. *
  576. * @throws RestException 401
  577. * @throws RestException 403
  578. * @throws RestException 404
  579. */
  580. public function customerDataHandler(string $facture_id, string $customerdatazip = null, string $customerdatacountrycode = null)
  581. {
  582. if (is_null($customerdatazip) && is_null($customerdatacountrycode)) {
  583. dol_syslog("Nem sikerult a facture updateje. Ref: " . $this->facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  584. throw new RestException(404, 'Empty params');
  585. }
  586. $sql = "UPDATE " . $this->db->prefix() . "facture_extrafields SET ";
  587. $sql .= !is_null($customerdatazip) ? "customer_data_zip = '{$customerdatazip}' " : "customer_data_countrycode = '{$customerdatacountrycode}' ";
  588. $sql .= "WHERE fk_object = '{$facture_id}'";
  589. $this->factureUpdate($sql, $facture_id);
  590. return "OK";
  591. }
  592. /**
  593. * Check user and eventdetail type permissions
  594. *
  595. * Return a result.
  596. *
  597. * @return array|mixed Data without useless information
  598. *
  599. * @url GET checkPermission
  600. */
  601. public function checkPermission()
  602. {
  603. global $user, $db, $conf;
  604. ApiBbusLog::appLog("checkPermission_START");
  605. $memcached = new Memcached();
  606. $memcached->addServer($conf->global->CONF_MEMCACHED, $conf->global->CONF_MEMCACHED_PORT);
  607. $key = '"' . $user->api_key . '"';
  608. $cacheValue = $memcached->get($key);
  609. if ($cacheValue === false) {
  610. $permissionArray = [];
  611. $groupUsersObj = new GroupUsers($db);
  612. $result = $groupUsersObj->fetchAll('desc', 'rowid', 1, 0, ["customsql" => "fk_user = {$user->id}"]);
  613. if ($result == -1 || empty($result)) {
  614. return $permissionArray;
  615. }
  616. dol_include_once('/eventwizard/class/eventdetails.class.php');
  617. $sqlBasicService = "SELECT pe.basic_service FROM llx_product as p
  618. INNER JOIN llx_product_extrafields as pe ON pe.fk_object = p.rowid";
  619. if (!$conf->global->CROSSSHOPPING_ENABLED) {
  620. $sqlBasicService .= " LEFT JOIN llx_bbus_basicservices as bs ON bs.basic_service_id::TEXT = pe.basic_service WHERE bs.server_host = 'excelia'";
  621. }
  622. $sqlBasicService .= " GROUP BY pe.basic_service";
  623. $resultBasicServices = $db->query($sqlBasicService);
  624. if ($db->num_rows($resultBasicServices) > 0) {
  625. while ($row = $db->fetch_object($resultBasicServices)) {
  626. $basicServices[] = $row->basic_service;
  627. }
  628. }
  629. $sqlBasicServicesTable = "SELECT basic_service_id, ref, is_event FROM llx_bbus_basicServices ORDER BY basic_service_id ASC";
  630. $resultBasicServicesObj = $db->query($sqlBasicServicesTable);
  631. if ($db->num_rows($resultBasicServicesObj) > 0) {
  632. while ($bsrow = $db->fetch_object($resultBasicServicesObj)) {
  633. foreach ($basicServices as $item) {
  634. if ($bsrow->basic_service_id == $item && $item != 2) {
  635. if ($bsrow->is_event == '1' && $this->isAvailablePlaces($item)) {
  636. $permissionArray[$item] = $bsrow->ref;
  637. } elseif ($bsrow->is_event != '1') {
  638. $permissionArray[$item] = $bsrow->ref;
  639. }
  640. }
  641. }
  642. }
  643. }
  644. $cacheValue = json_encode($permissionArray);
  645. $memcached->set($key, $cacheValue, 600); // 5 percig tároljuk
  646. ApiBbusLog::appLog("Adat betöltve a adatbázis-ból: " . $cacheValue);
  647. } else {
  648. ApiBbusLog::appLog("Adat betöltve a cache-ből: " . $cacheValue);
  649. }
  650. //$curlPermissionArray = $this->curlRunner('rollerstorageapi/checkPermission', '');
  651. //$permissionArray = $permissionArray + (array)json_decode($curlPermissionArray);
  652. //return $permissionArray;
  653. return json_decode($cacheValue, true);
  654. }
  655. private function isAvailablePlaces($item)
  656. {
  657. global $conf;
  658. $available = false;
  659. $server_host = $this->getServerHost($item);
  660. $sqlProducts = "SELECT fk_object, basic_service FROM llx_product_extrafields WHERE basic_service = '{$item}'";
  661. $resultProducts = $this->db->query($sqlProducts);
  662. if ($this->db->num_rows($resultProducts) > 0) {
  663. while ($prodductsRow = $this->db->fetch_object($resultProducts)) {
  664. $productsArray[] = $prodductsRow->fk_object;
  665. }
  666. $productsString = implode(",", $productsArray);
  667. /* print_r($productsArray);
  668. print $productsString;
  669. exit; */
  670. if (!empty($productsArray)) {
  671. //foreach ($productsArray as $key => $value) {
  672. ApiBbusLog::appLog("SERVER_HOST: " . $server_host);
  673. ApiBbusLog::appLog("CONF_SERVER_HOST: " . $conf->global->LOCAL_SERVER_HOST);
  674. if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
  675. ApiBbusLog::appLog($conf->global->LOCAL_SERVER_HOST);
  676. $availableResult = $this->localCheckAvailablePlacesForCheckPermission($productsString);
  677. } elseif ($server_host == $conf->global->CURL_SERVER_HOST) {
  678. ApiBbusLog::appLog($conf->global->CURL_SERVER_HOST);
  679. $postFields = '{"product_ids":"' . $productsString . '"}';
  680. $availableResult = $this->curlRunner('bbus/localCheckAvailablePlacesForCheckPermission', $postFields, 'POST', false);
  681. }
  682. if ($availableResult == 1) {
  683. $available = true;
  684. }
  685. //}
  686. }
  687. };
  688. return $available;
  689. }
  690. /**
  691. * localCheckAvailablePlacesForCheckPermission
  692. *
  693. * @param string $product_id Product rowid
  694. *
  695. * @return array|mixed Data without useless information
  696. *
  697. * @url POST localCheckAvailablePlacesForCheckPermission
  698. *
  699. * @throws RestException 401
  700. * @throws RestException 403
  701. * @throws RestException 404
  702. */
  703. public function localCheckAvailablePlacesForCheckPermission($product_id, $hotelsales = 0)
  704. {
  705. //$date_from = $this->getCutOffTimeDate($product_id);
  706. $date_from = $this->getDefaultCutOffTimeDate();
  707. $sql = "SELECT
  708. ac.id
  709. FROM llx_actioncomm as ac
  710. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  711. INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
  712. INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element";
  713. if ($hotelsales !== 0) {
  714. $sql .= " INNER JOIN llx_product_extrafields as pre ON pre.fk_object = ep.fk_product";
  715. }
  716. $sql .= " WHERE ac.code = 'AC_EVENT'";
  717. if ($hotelsales !== 0) {
  718. $sql .= " AND pre.hotelsales = 1";
  719. }
  720. $sql .= " AND ep.fk_product IN ({$product_id})
  721. AND ac.datep > '{$date_from}'
  722. ORDER BY ac.datep ASC";
  723. ApiBbusLog::appLog($sql);
  724. $result = $this->db->query($sql);
  725. return $this->db->num_rows($result) > 0 ? 1 : 0;
  726. }
  727. private function getDefaultCutOffTimeDate()
  728. {
  729. $date = date("Y-m-d H:i:s");
  730. $dateTimestamp = strtotime($date);
  731. $date = date("Y-m-d H:i:s", $dateTimestamp + 180 * 60);
  732. return $date;
  733. }
  734. private function getCutOffTimeDate($product_id)
  735. {
  736. $date = date("Y-m-d H:i:s");
  737. $sql = "SELECT cut_off_time_app FROM llx_product_extrafields WHERE fk_object = {$product_id}";
  738. if ($result = $this->db->query($sql)) {
  739. if ($this->db->num_rows($result) > 0) {
  740. while ($row = $this->db->fetch_object($result)) {
  741. $cutOffTime = $row->cut_off_time_app;
  742. }
  743. $dateTimestamp = strtotime($date);
  744. $date = date("Y-m-d H:i:s", $dateTimestamp + $cutOffTime * 60);
  745. }
  746. }
  747. return $date;
  748. }
  749. /**
  750. * Create naplo for userlogout
  751. *
  752. * Return a result.
  753. *
  754. * @return array|mixed Data without useless information
  755. *
  756. * @url POST logoutNaploCreator
  757. *
  758. * @throws RestException 401
  759. * @throws RestException 403
  760. * @throws RestException 404
  761. */
  762. public function logoutNaploCreator()
  763. {
  764. global $user, $db;
  765. $error = 0;
  766. $db->begin();
  767. $group_user_id = $this->getGroupUserIdByUserId($user->id);
  768. if ($group_user_id == -1) {
  769. $error++;
  770. }
  771. $result = $this->isLastStatusLogout($user);
  772. if ($result !== '') {
  773. return date('Y-m-d H:i:s', $result);
  774. }
  775. $userLoginNaplo = new UserLoginNaplo($db);
  776. $userLoginNaplo->login_logout_status = 1;
  777. $userLoginNaplo->user_id = $user->id;
  778. $result = $userLoginNaplo->create($user);
  779. if ($result < 0) {
  780. $error++;
  781. }
  782. $userNaploObj = new UserNaplo($db);
  783. $userNaploObj->user_id = $user->id;
  784. $userNaploObj->group_user_id = $group_user_id;
  785. $userNaploObj->status = 0;
  786. $result = $userNaploObj->create($user);
  787. if ($result < 0) {
  788. $error++;
  789. }
  790. $groupUsersObj = new GroupUsers($db);
  791. $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "settlements_groupusers WHERE fk_user = {$user->id}";
  792. $data = $db->query($sql);
  793. $dataArray = pg_fetch_assoc($data);
  794. $selectedGroupId = $dataArray['rowid'];
  795. if (isset($selectedGroupId)) {
  796. $resultKickOff = $groupUsersObj->deleteLine($user, $selectedGroupId);
  797. if (!$resultKickOff) {
  798. $error++;
  799. }
  800. }
  801. if ($error) {
  802. $db->rollback();
  803. }
  804. $db->commit();
  805. return 'OK';
  806. }
  807. /**
  808. * Get the discount unit From Product
  809. *
  810. * Return a result.
  811. *
  812. * @param int $product_id Product rowid
  813. *
  814. * @return string discount unit
  815. *
  816. * @url POST getDiscountUnit
  817. *
  818. * @throws RestException 401
  819. * @throws RestException 403
  820. * @throws RestException 404
  821. */
  822. public function getDiscountUnit(int $product_id)
  823. {
  824. global $db, $user;
  825. $ProductObj = new Product($db);
  826. $ProductObj->fetch($product_id);
  827. return $ProductObj->array_options['discount_period'];
  828. }
  829. /**
  830. * Create naplo for Discount
  831. *
  832. * Return a result.
  833. *
  834. * @param int $facture_id Facture rowid
  835. * @param int $product_id Product rowid
  836. * @param int $discount Discount
  837. * @param string $discount_unit Discount unit
  838. *
  839. * @return array|mixed Data without useless information
  840. *
  841. * @url POST createDiscountNaplo
  842. *
  843. * @throws RestException 401
  844. * @throws RestException 403
  845. * @throws RestException 404
  846. */
  847. public function createDiscountNaplo(int $facture_id, int $product_id, int $discount, string $discount_unit)
  848. {
  849. global $db, $user;
  850. $discountNaploObj = new DiscountNaplo($db);
  851. $discountNaploObj->fk_facture = $facture_id;
  852. $discountNaploObj->fk_product = $product_id;
  853. $discountNaploObj->discount = $discount;
  854. $discountNaploObj->discount_unit = $discount_unit;
  855. $result = $discountNaploObj->create($user);
  856. if ($result < 0) {
  857. return false;
  858. }
  859. return $result;
  860. }
  861. /**
  862. * Get the products from Product
  863. *
  864. * Return a result.
  865. *
  866. * @param int $entity entity
  867. *
  868. * @return array|mixed Data without useless information
  869. *
  870. * @url POST getHotelSalesProducts
  871. *
  872. * @throws RestException 401
  873. * @throws RestException 403
  874. * @throws RestException 404
  875. */
  876. public function getHotelSalesProducts(int $entity)
  877. {
  878. global $db, $user;
  879. $sql = "SELECT p.* FROM public.llx_product AS p
  880. INNER JOIN public.llx_product_extrafields as pe ON pe.fk_object = p.rowid
  881. WHERE p.entity = {$entity} AND pe.hotelsales = 1";
  882. $products = $this->db->query($sql);
  883. $row = pg_fetch_all($products);
  884. return $row;
  885. }
  886. private function getGroupUserIdByUserId($user_id)
  887. {
  888. global $db;
  889. $groupUsersObj = new GroupUsers($db);
  890. $result = $groupUsersObj->fetchAll('DESC', 'rowid', 1, 0, ["customsql" => "fk_user = {$user_id}"]);
  891. if (!empty($result)) {
  892. foreach ($result as $record) {
  893. return $record->fk_settlements_group;
  894. }
  895. }
  896. return -1;
  897. }
  898. private function isLastStatusLogout($user)
  899. {
  900. global $db;
  901. $userLoginNaplo = new UserLoginNaplo($db);
  902. $result = $userLoginNaplo->fetchAll('DESC', 'date_creation', 1, 0, array('user_id' => $user->id));
  903. foreach ($result as $lastrecord) {
  904. return $lastrecord->login_logout_status == 1 ? $lastrecord->date_creation : '';
  905. }
  906. }
  907. private function factureUpdate($sql, $facture_id)
  908. {
  909. $updated = $this->db->query($sql);
  910. if (!$updated) {
  911. dol_syslog("Nem sikerult a facture updateje. rowid: " . $facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  912. throw new RestException(404, 'Update failed');
  913. }
  914. }
  915. private function checkUserReadPermission()
  916. {
  917. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  918. throw new RestException(403);
  919. }
  920. }
  921. private function checkUserValidatePermission()
  922. {
  923. if (!DolibarrApiAccess::$user->rights->bbus->ticket->validation) {
  924. throw new RestException(403);
  925. }
  926. }
  927. private function getFactureRowIdByFactureId()
  928. {
  929. $facture = new Facture($this->db);
  930. $sqlFacture = "SELECT rowid FROM public.llx_facture WHERE ref ILIKE '%{$this->code}%'";
  931. $result = $this->db->query($sqlFacture);
  932. if (pg_num_rows($result) > 0) {
  933. while ($adatok = pg_fetch_assoc($result)) {
  934. $factureRowid = $adatok['rowid'];
  935. }
  936. } else {
  937. throw new RestException(404, 'Invoice not found.');
  938. }
  939. $sql = "SELECT rowid FROM llx_facture WHERE fk_facture_source = {$factureRowid} AND type = 2";
  940. $res = $this->db->query($sql);
  941. if (pg_num_rows($res) > 0) {
  942. throw new RestException(404, 'Invoice has a Credit account.');
  943. }
  944. return $factureRowid;
  945. }
  946. private function checkResult($result, $tableName)
  947. {
  948. if (!is_array($result) || empty($result)) {
  949. dol_syslog("A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  950. throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
  951. }
  952. }
  953. private function saveBbTicketNaplo($user)
  954. {
  955. $bbTicketNaplo = new BbTicketNaplo($this->db);
  956. $bbTicketNaplo->ticket_row_id = $this->bbTicketRowId;
  957. $bbTicketNaplo->bbservicelocation_id = isset($this->service_location_id) ? $this->service_location_id : null;
  958. $bbTicketNaplo->device_id = isset($this->device_id) ? $this->device_id : null;
  959. $bbTicketNaplo->status = $this->status;
  960. if ($bbTicketNaplo->create($user) < 0) {
  961. dol_syslog('Nem sikerult menteni a bbticketNaplo tablaba a rekordot.', LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  962. throw new RestException(500, 'Nem sikerult menteni a bbticketNaplo tablaba a rekordot.');
  963. }
  964. }
  965. private function getTicketsByFactureId($facture_id)
  966. {
  967. $bbticket = new BbTicket($this->db);
  968. $bbTicketsByFacture = $bbticket->fetchAll('', '', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  969. if ($bbTicketsByFacture < 1) {
  970. throw new RestException(404, 'BBTicket not found');
  971. }
  972. return $bbTicketsByFacture;
  973. }
  974. private function getTicketsByInvoiceNumber($ref)
  975. {
  976. $bbticket = new BbTicket($this->db);
  977. $bbTicketsByFacture = $bbticket->fetchAll('', '', 0, 0, ["customsql" => "invoice_number = '" . $ref . "'"]);
  978. if ($bbTicketsByFacture < 1) {
  979. ApiBbusLog::appLog("getTicketsByInvoiceNumber: BBTicket not found");
  980. throw new RestException(404, 'BBTicket not found');
  981. }
  982. ApiBbusLog::appLog("getTicketsByInvoiceNumber: I got it");
  983. return $bbTicketsByFacture;
  984. }
  985. private function checkPrintedCopies($facture_id)
  986. {
  987. $bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
  988. $copies = $bbticketinvoiceprinting->fetchAll('ASC', 'rowid', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  989. return (is_array($copies)) ? count($copies) : 0;
  990. }
  991. private function checkPrintedCopiesWithRef($ref)
  992. {
  993. $bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
  994. $copies = $bbticketinvoiceprinting->fetchAll('ASC', 'rowid', 0, 0, ["customsql" => "invoice_number = '" . $ref . "'"]);
  995. return (is_array($copies)) ? count($copies) : 0;
  996. }
  997. /**
  998. * @param string $facture_id Facture ref
  999. *
  1000. * @return array|mixed Data without useless information
  1001. *
  1002. * @url POST getRefFromFacture
  1003. *
  1004. * @throws RestException 401
  1005. * @throws RestException 403
  1006. * @throws RestException 404
  1007. */
  1008. public function getRefFromFacture(string $facture_id)
  1009. {
  1010. global $user;
  1011. $facture = new Facture($this->db);
  1012. $sql = "SELECT ref FROM " . $this->db->prefix() . $facture->table_element . " WHERE rowid = " . $facture_id;
  1013. $res = $this->db->query($sql);
  1014. while ($adatok = pg_fetch_assoc($res)) {
  1015. print_r($adatok['ref']);
  1016. exit;
  1017. }
  1018. return 'OK';
  1019. }
  1020. /**
  1021. * Get properties of a product object by barcode
  1022. *
  1023. * Return an array with product information.
  1024. *
  1025. * @param string $barcode Barcode of element
  1026. * @param int $includestockdata Load also information about stock (slower)
  1027. * @param bool $includesubproducts Load information about subproducts
  1028. * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product)
  1029. * @param bool $includetrans Load also the translations of product label and description
  1030. *
  1031. * @return array|mixed Data without useless information
  1032. *
  1033. * @url GET profileimage/{id}
  1034. *
  1035. * @throws RestException 401
  1036. * @throws RestException 403
  1037. * @throws RestException 404
  1038. */
  1039. public function getUserImage(int $id)
  1040. {
  1041. $image = null;
  1042. $dolApiKey = $_SERVER['HTTP_DOLAPIKEY'] ?? null;
  1043. if (empty($dolApiKey)) {
  1044. throw new RestException(401, 'Access not allowed');
  1045. }
  1046. $user = (new ApiUserHandler)->getUser($id, $dolApiKey);
  1047. if (empty($user->photo)) {
  1048. throw new RestException(404, 'Photo not found');
  1049. } else {
  1050. $originalFile = get_exdir(0, 0, 0, 0, $user, 'user') . 'photos/' . $user->photo;
  1051. $originalFile = DOL_DOCUMENT_ROOT . '/documents/users/' . $originalFile;
  1052. $filename = basename($originalFile);
  1053. $originalFileOsEncoded = dol_osencode($originalFile); // New file name encoded in OS encoding charset
  1054. $fileContent = file_get_contents($originalFileOsEncoded);
  1055. $image = [
  1056. 'filename' => $filename,
  1057. 'content-type' => dol_mimetype($filename),
  1058. 'filesize' => filesize($originalFile),
  1059. 'content' => base64_encode($fileContent),
  1060. 'encoding' => 'base64'
  1061. ];
  1062. }
  1063. return $image;
  1064. }
  1065. /**
  1066. * Create invoices from the order
  1067. *
  1068. * @param int $id_order (Row)Id of the order
  1069. * @param int $id_soc Id of 3th party
  1070. * @return array Response
  1071. * @url POST invoicesFromOrder
  1072. * @throws RestException 401
  1073. * @throws RestException 403
  1074. * @throws RestException 404
  1075. */
  1076. public function invoicesFromOrder(int $id_order, int $id_soc = 0): array
  1077. {
  1078. // echo ini_get('memory_limit');
  1079. // exit;
  1080. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  1081. throw new RestException(401, "Insuffisant rights");
  1082. }
  1083. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  1084. // Standard or deposit invoice, not from a Predefined template invoice
  1085. // Si facture standard
  1086. $this->now = time();
  1087. $this->invoices = [];
  1088. $element == 'order';
  1089. $element = $subelement = 'commande';
  1090. //etalon obj:
  1091. $object = new Facture($this->db);
  1092. // $extrafields = new ExtraFields($db);
  1093. $defaultDevSocId = 1;
  1094. $this->defaultSocId = (isset($_ENV['DEFAULT_SOCID']) && (int) $_ENV['DEFAULT_SOCID']) ? (int) $_ENV['DEFAULT_SOCID'] : $defaultDevSocId;
  1095. $object->socid = (empty((int) $id_soc)) ? $this->defaultSocId : (int) $id_soc;
  1096. $object->type = null;
  1097. $object->ref = null;
  1098. $object->date = $this->now;
  1099. // $object->date_pointoftax = $date_pointoftax;
  1100. // $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1101. // $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1102. // $object->ref_client = GETPOST('ref_client');
  1103. $object->model_pdf = null;
  1104. // $object->fk_project = GETPOST('projectid', 'int');
  1105. // $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  1106. // $object->mode_reglement_id = GETPOST('mode_reglement_id');
  1107. // $object->fk_account = GETPOST('fk_account', 'int');
  1108. // $object->amount = price2num(GETPOST('amount'));
  1109. // $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1110. // $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1111. // $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1112. // $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1113. // $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1114. // $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1115. $object->fetch_thirdparty();
  1116. // If creation from another object of another module (Example: origin=propal, originid=1)
  1117. $object->origin = $element;
  1118. $object->origin_id = $id_order;
  1119. // Possibility to add external linked objects with hooks
  1120. $object->linked_objects[$object->origin] = $object->origin_id;
  1121. // link with order if it is a shipping invoice
  1122. if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) {
  1123. $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
  1124. }
  1125. //
  1126. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  1127. $classname = ucfirst($subelement);
  1128. $srcobject = new $classname($this->db);
  1129. $result = $srcobject->fetch($id_order);
  1130. if ($result > 0) {
  1131. $lines = $srcobject->lines;
  1132. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  1133. $srcobject->fetch_lines();
  1134. $lines = $srcobject->lines;
  1135. }
  1136. /*
  1137. // If we create a standard invoice with a percent, we change amount by changing the qty
  1138. if (is_array($lines)) {
  1139. foreach ($lines as $line) {
  1140. // We keep ->subprice and ->pa_ht, but we change the qty
  1141. $line->qty = price2num($line->qty * $valuestandardinvoice / 100, 'MS');
  1142. }
  1143. }
  1144. */
  1145. $fk_parent_line = 0;
  1146. $num = count($lines);
  1147. $invNum = 0;
  1148. for ($i = 0; $i < $num; $i++) {
  1149. // if (!in_array($lines[$i]->id, $selectedLines)) {
  1150. // continue; // Skip unselected lines
  1151. // }
  1152. //!!! create invoice by line:
  1153. $quantity = $lines[$i]->qty;
  1154. for ($j = 0; $j < $quantity; $j++) {
  1155. $this->invoices[$invNum] = clone $object;
  1156. if ($id = $this->invoices[$invNum]->create(DolibarrApiAccess::$user)) {
  1157. $this->invoices[$invNum]->update_price(1, 'auto', 0, $mysoc);
  1158. $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
  1159. $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle);
  1160. if ($this->invoices[$invNum]->situation_counter == 1) {
  1161. $lines[$i]->situation_percent = 0;
  1162. }
  1163. if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) {
  1164. // Negative line, we create a discount line
  1165. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  1166. $discount = new DiscountAbsolute($db);
  1167. $discount->fk_soc = $this->invoices[$invNum]->socid;
  1168. $discount->amount_ht = abs($lines[$i]->total_ht);
  1169. $discount->amount_tva = abs($lines[$i]->total_tva);
  1170. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  1171. $discount->tva_tx = $lines[$i]->tva_tx;
  1172. $discount->fk_user = DolibarrApiAccess::$user->id;
  1173. $discount->description = $desc;
  1174. $discount->multicurrency_subprice = abs($lines[$i]->multicurrency_subprice);
  1175. $discount->multicurrency_amount_ht = abs($lines[$i]->multicurrency_total_ht);
  1176. $discount->multicurrency_amount_tva = abs($lines[$i]->multicurrency_total_tva);
  1177. $discount->multicurrency_amount_ttc = abs($lines[$i]->multicurrency_total_ttc);
  1178. $discountid = $discount->create(DolibarrApiAccess::$user);
  1179. if ($discountid > 0) {
  1180. $result = $this->invoices[$invNum]->insert_discount($discountid); // This include link_to_invoice
  1181. } else {
  1182. setEventMessages($discount->error, $discount->errors, 'errors');
  1183. $error++;
  1184. break;
  1185. }
  1186. } else {
  1187. // Positive line
  1188. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  1189. // Date start
  1190. $date_start = false;
  1191. if ($lines[$i]->date_debut_prevue) {
  1192. $date_start = $lines[$i]->date_debut_prevue;
  1193. }
  1194. if ($lines[$i]->date_debut_reel) {
  1195. $date_start = $lines[$i]->date_debut_reel;
  1196. }
  1197. if ($lines[$i]->date_start) {
  1198. $date_start = $lines[$i]->date_start;
  1199. }
  1200. // Date end
  1201. $date_end = false;
  1202. if ($lines[$i]->date_fin_prevue) {
  1203. $date_end = $lines[$i]->date_fin_prevue;
  1204. }
  1205. if ($lines[$i]->date_fin_reel) {
  1206. $date_end = $lines[$i]->date_fin_reel;
  1207. }
  1208. if ($lines[$i]->date_end) {
  1209. $date_end = $lines[$i]->date_end;
  1210. }
  1211. // Reset fk_parent_line for no child products and special product
  1212. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  1213. $fk_parent_line = 0;
  1214. }
  1215. // Extrafields
  1216. if (method_exists($lines[$i], 'fetch_optionals')) {
  1217. $lines[$i]->fetch_optionals();
  1218. $array_options = $lines[$i]->array_options;
  1219. }
  1220. $tva_tx = $lines[$i]->tva_tx;
  1221. if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
  1222. $tva_tx .= ' (' . $lines[$i]->vat_src_code . ')';
  1223. }
  1224. // View third's localtaxes for NOW and do not use value from origin.
  1225. // TODO Is this really what we want ? Yes if source is template invoice but what if proposal or order ?
  1226. $localtax1_tx = get_localtax($tva_tx, 1, $this->invoices[$invNum]->thirdparty);
  1227. $localtax2_tx = get_localtax($tva_tx, 2, $this->invoices[$invNum]->thirdparty);
  1228. $result = $this->invoices[$invNum]->addline(
  1229. $desc,
  1230. $lines[$i]->subprice,
  1231. // $lines[$i]->qty,
  1232. 1,
  1233. $tva_tx,
  1234. $localtax1_tx,
  1235. $localtax2_tx,
  1236. $lines[$i]->fk_product,
  1237. $lines[$i]->remise_percent,
  1238. $date_start,
  1239. $date_end,
  1240. 0,
  1241. $lines[$i]->info_bits,
  1242. $lines[$i]->fk_remise_except,
  1243. 'HT',
  1244. 0,
  1245. $product_type,
  1246. $lines[$i]->rang,
  1247. $lines[$i]->special_code,
  1248. $this->invoices[$invNum]->origin,
  1249. $lines[$i]->rowid,
  1250. $fk_parent_line,
  1251. $lines[$i]->fk_fournprice,
  1252. $lines[$i]->pa_ht,
  1253. $label,
  1254. $array_options,
  1255. $lines[$i]->situation_percent,
  1256. $lines[$i]->fk_prev_id,
  1257. $lines[$i]->fk_unit,
  1258. 0,
  1259. '',
  1260. 1
  1261. );
  1262. if ($result > 0) {
  1263. $lineid = $result;
  1264. } else {
  1265. $lineid = 0;
  1266. $error++;
  1267. break;
  1268. }
  1269. // Defined the new fk_parent_line
  1270. if ($result > 0 && $lines[$i]->product_type == 9) {
  1271. $fk_parent_line = $result;
  1272. }
  1273. }
  1274. }
  1275. $invNum++;
  1276. }
  1277. }
  1278. } else {
  1279. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1280. $error++;
  1281. }
  1282. $num = count($this->invoices);
  1283. $return = [
  1284. 'validated' => []
  1285. ];
  1286. // $used_mem = round(memory_get_usage(false) / 1024 / 1024); //mb
  1287. // $used_mem = round(memory_get_usage(true) / 1024 / 1024); //mb
  1288. // echo $used_mem. " / ".$allowed_mem;
  1289. // echo ini_get('memory_limit');
  1290. // exit;
  1291. for ($i = 0; $i < $num; $i++) {
  1292. //!!! validation
  1293. // $idwarehouse = 0;
  1294. // $notrigger = 0;
  1295. // $result = $this->invoices[$i]->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
  1296. $id = $this->invoices[$i]->id;
  1297. $result = $this->invoices[$i]->validate(DolibarrApiAccess::$user, '', null);
  1298. if ($result >= 0) {
  1299. // Define output language
  1300. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1301. global $langs;
  1302. $outputlangs = $langs;
  1303. $newlang = '';
  1304. if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1305. $newlang = GETPOST('lang_id', 'aZ09');
  1306. }
  1307. if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) {
  1308. $newlang = $this->invoices[$i]->thirdparty->default_lang;
  1309. }
  1310. if (!empty($newlang)) {
  1311. $outputlangs = new Translate("", $conf);
  1312. $outputlangs->setDefaultLang($newlang);
  1313. $outputlangs->load('products');
  1314. }
  1315. $model = $this->invoices[$i]->model_pdf;
  1316. $ret = $this->invoices[$i]->fetch($id); // Reload to get new records
  1317. // PDF
  1318. $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS)) ? 1 : 0;
  1319. $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC)) ? 1 : 0;
  1320. $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF)) ? 1 : 0;
  1321. $result = $this->invoices[$i]->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1322. if ($result < 0) {
  1323. //...
  1324. // setEventMessages($this->invoices[$i]->error, $this->invoices[$i]->errors, 'errors');
  1325. }
  1326. }
  1327. } else {
  1328. // if (count($this->invoices[$i]->errors)) {
  1329. // setEventMessages(null, $this->invoices[$i]->errors, 'errors');
  1330. // } else {
  1331. // setEventMessages($this->invoices[$i]->error, $this->invoices[$i]->errors, 'errors');
  1332. // }
  1333. }
  1334. // if ($result == 0) {
  1335. // throw new RestException(304, 'Error nothing done. May be object is already validated');
  1336. // }
  1337. // if ($result < 0) {
  1338. // throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
  1339. // }
  1340. // $this->invoices[$i] = $this->invoicees[$i]->fetch($id);
  1341. if (!$this->invoices[$i]) {
  1342. throw new RestException(404, 'Invoice not found');
  1343. }
  1344. $this->invoices[$i] = parent::_cleanObjectDatas($this->invoices[$i]);
  1345. unset($this->invoices[$i]->note);
  1346. unset($this->invoices[$i]->address);
  1347. unset($this->invoices[$i]->barcode_type);
  1348. unset($this->invoices[$i]->barcode_type_code);
  1349. unset($this->invoices[$i]->barcode_type_label);
  1350. unset($this->invoices[$i]->barcode_type_coder);
  1351. unset($this->invoices[$i]->canvas);
  1352. if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
  1353. throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
  1354. }
  1355. $return['validated'][] = $this->invoices[$i]->ref;
  1356. }
  1357. return $return;
  1358. }
  1359. /**
  1360. * Jegy generálás -> (order?->) invoice -> payment -> jegy -> qr on the bill
  1361. *
  1362. * Return an array with prcess information.
  1363. *
  1364. * @param array $orderDetails Order details
  1365. *
  1366. * @return array|mixed Data without useless information
  1367. *
  1368. * @url POST order
  1369. *
  1370. * @throws RestException 401
  1371. * @throws RestException 403
  1372. * @throws RestException 404
  1373. */
  1374. public function jegy(array $orderDetails)
  1375. {
  1376. $return = [
  1377. "request" => $orderDetails
  1378. ];
  1379. $Jegy = new Jegy();
  1380. $return['hash'] = [
  1381. $Jegy->generate_hash(),
  1382. $Jegy->generate_hash(1),
  1383. $Jegy->generate_hash(20),
  1384. $Jegy->generate_hash(50),
  1385. $Jegy->generate_hash(100),
  1386. ];
  1387. return $return;
  1388. }
  1389. /**
  1390. * Get app config
  1391. *
  1392. * Return an array with config params.
  1393. *
  1394. * @return array|mixed Data without useless information
  1395. *
  1396. * @url GET config
  1397. *
  1398. * @throws RestException 401
  1399. * @throws RestException 403
  1400. * @throws RestException 404
  1401. */
  1402. public function config(): array
  1403. {
  1404. global $user, $conf;
  1405. $helper = new ApiBBusHelper();
  1406. // company
  1407. $companyData = $helper->getCompany();
  1408. return [
  1409. 'exchange_rate' => ExchangeRateUpdater::getExchangeRate(ExchangeRateUpdater::EUR, $conf->entity),
  1410. 'invoice' => [
  1411. 'header' => [
  1412. 'name' => $companyData['company_data']['NOM'],
  1413. 'tax_number' => $companyData['company_data']['TVAINTRA'],
  1414. 'address' => [
  1415. 'zip' => $companyData['company_data']['ZIP'],
  1416. 'city' => $companyData['company_data']['TOWN'],
  1417. 'address' => $companyData['company_data']['ADDRESS']
  1418. ]
  1419. ],
  1420. 'customer' => $helper->getAppCustomers(),
  1421. 'vat_percent' => 27,
  1422. 'entity' => $user->entity,
  1423. 'account_id' => $helper->getAccountRowid($user->entity),
  1424. 'currencies' => $helper->getCurrenciesRowid($user->entity),
  1425. 'payments_mode' => $helper->getPaymentsMode($user->entity)
  1426. ]
  1427. ];
  1428. }
  1429. /**
  1430. * Get groupId for REACT
  1431. *
  1432. * Return an ID.
  1433. *
  1434. * @return integer Data without useless information
  1435. *
  1436. * @url GET getGroupId
  1437. *
  1438. * @throws RestException 401
  1439. * @throws RestException 403
  1440. * @throws RestException 404
  1441. */
  1442. public function getGroupId(): array
  1443. {
  1444. global $user, $db;
  1445. $sql = "SELECT fk_settlements_group FROM public.llx_settlements_groupusers WHERE fk_user = {$user->id} ORDER BY rowid DESC LIMIT 1";
  1446. $result = $db->query($sql);
  1447. while ($row = pg_fetch_assoc($result)) {
  1448. return $row;
  1449. }
  1450. return [];
  1451. }
  1452. /**
  1453. * Insert a row into login log table
  1454. *
  1455. * @param string $login Login name
  1456. *
  1457. * @return array|mixed Data without useless information
  1458. *
  1459. * @url POST savelogin
  1460. *
  1461. * @throws RestException 404
  1462. */
  1463. public function saveLogin(string $login)
  1464. {
  1465. $error = 0;
  1466. $this->db->begin();
  1467. $user = new User($this->db);
  1468. //$user->fetch(0, $login, 0, 0, 1);
  1469. $user->fetch(0, $login, 0, 0);
  1470. if (empty($user->id)) {
  1471. throw new RestException(404, 'User not found');
  1472. }
  1473. $log = new BbLoginLog($this->db);
  1474. $log->entity = 1;
  1475. $log->description = 'Login from App';
  1476. $id = $log->create($user);
  1477. if ($id < 1) {
  1478. $error++;
  1479. throw new RestException(500, 'Log failure');
  1480. }
  1481. $now = dol_now();
  1482. $userremoteip = getUserRemoteIP();
  1483. $sql = "UPDATE " . $this->db->prefix() . "user SET";
  1484. $sql .= " datepreviouslogin = datelastlogin,";
  1485. $sql .= " ippreviouslogin = iplastlogin,";
  1486. $sql .= " datelastlogin = '" . $this->db->idate($now) . "',";
  1487. $sql .= " iplastlogin = '" . $this->db->escape($userremoteip) . "',";
  1488. $sql .= " tms = tms"; // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
  1489. $sql .= " WHERE rowid = " . ((int) $user->id);
  1490. $resql = $this->db->query($sql);
  1491. if (!$resql) {
  1492. $error++;
  1493. $this->error = $this->db->lasterror() . ' sql=' . $sql;
  1494. }
  1495. if (!$error) {
  1496. $this->db->commit();
  1497. return 'OK';
  1498. } else {
  1499. $this->db->rollback();
  1500. }
  1501. }
  1502. /**
  1503. * Receive GPS coordinates of the device
  1504. *
  1505. * @param string $licplate License plate of the vehicle
  1506. * @param string $lat GPS latitude coordinate
  1507. * @param string $lon GPS longitude coordinate
  1508. *
  1509. * @return string|mixed Data without useless information
  1510. *
  1511. * @url GET /gps_coords
  1512. *
  1513. * @throws RestException 401
  1514. * @throws RestException 403
  1515. * @throws RestException 404
  1516. * @throws RestException 500
  1517. */
  1518. public function gpsCoords(string $licplate, string $lat, string $lon): string
  1519. {
  1520. if (!(new GpsPosition)->save($licplate, $lat, $lon)) {
  1521. throw new RestException(500, 'Save failure');
  1522. }
  1523. return 'OK';
  1524. }
  1525. /**
  1526. * Receive GPS coordinates of the device
  1527. *
  1528. * @param string $licplate License plate of the vehicle
  1529. * @param string $lat GPS latitude coordinate
  1530. * @param string $lon GPS longitude coordinate
  1531. *
  1532. * @return string|mixed Data without useless information
  1533. *
  1534. * @url POST /gps_position
  1535. *
  1536. * @throws RestException 401
  1537. * @throws RestException 403
  1538. * @throws RestException 404
  1539. * @throws RestException 500
  1540. */
  1541. public function gpsPosition(string $licplate, string $lat, string $lon): string
  1542. {
  1543. if (!(new GpsPosition)->save($licplate, $lat, $lon)) {
  1544. throw new RestException(500, 'Save failure');
  1545. }
  1546. return 'OK';
  1547. }
  1548. /**
  1549. * List of countries
  1550. *
  1551. * Return an array with country name and code.
  1552. *
  1553. * @param string $lang
  1554. * @param string $search
  1555. *
  1556. * @return array|mixed Data without useless information
  1557. *
  1558. * @url GET /countries
  1559. *
  1560. * @throws RestException 401
  1561. * @throws RestException 403
  1562. * @throws RestException 404
  1563. */
  1564. public function countries(string $lang = 'hu', string $search = ''): array
  1565. {
  1566. return (new CountryHandler)->getCountries($lang, $search);
  1567. }
  1568. /**
  1569. * List of entities
  1570. *
  1571. * Return an array with companies data.
  1572. *
  1573. * @return array|mixed Data without useless information
  1574. *
  1575. * @url GET /entities
  1576. *
  1577. * @throws RestException 401
  1578. * @throws RestException 403
  1579. * @throws RestException 404
  1580. */
  1581. public function entities(): array
  1582. {
  1583. return (new EntityHandler)->getEntities();
  1584. }
  1585. /**
  1586. * List of assets received
  1587. *
  1588. * Return an array with assets received.
  1589. *
  1590. * @return array|mixed Data without useless information
  1591. *
  1592. * @url GET /assets_received
  1593. *
  1594. * @throws RestException 401
  1595. * @throws RestException 403
  1596. * @throws RestException 404
  1597. */
  1598. public function assetsReceived(): array
  1599. {
  1600. global $user, $db;
  1601. $packageHistory = new PackageHistory($db);
  1602. $inventoryObj = new Inventory($db);
  1603. $sql = "SELECT pt.device_id, i.ref, i.title, ie.unique_identifier,
  1604. (SELECT ph.date_creation FROM " . $this->db->prefix() . $packageHistory->table_element . " as ph WHERE user_id = {$user->id} AND DATE(ph.date_creation) = CURRENT_DATE
  1605. ORDER BY ph.rowid DESC LIMIT 1) AS ph_date_creation
  1606. FROM llx_settlements_packagetool pt
  1607. INNER JOIN llx_inventory as i ON i.rowid = pt.device_id
  1608. INNER JOIN llx_inventory_extrafields as ie ON ie.fk_object = i.rowid
  1609. WHERE pt.package_id = (SELECT ph.package_id FROM public.llx_rollerstorage_packagehistory as ph WHERE user_id = {$user->id}
  1610. AND DATE(ph.date_creation) = CURRENT_DATE
  1611. ORDER BY ph.rowid DESC LIMIT 1)
  1612. ORDER BY pt.rowid DESC";
  1613. //print $sql;exit;
  1614. $result = $db->query($sql);
  1615. $changeSql = "SELECT ref, title FROM " . $this->db->prefix() . $inventoryObj->table_element . " WHERE ref ILIKE '%Change%'";
  1616. $resultCh = $db->query($changeSql);
  1617. if ($result > 0 && $resultCh > 0) {
  1618. while ($row = $db->fetch_object($result)) {
  1619. $row = (array) $row;
  1620. $date = $row['ph_date_creation'];
  1621. $device[] = [
  1622. "name" => isset($row['title']) ? $row['title'] : '',
  1623. "sku" => isset($row['unique_identifier']) ? $row['unique_identifier'] : ''
  1624. ];
  1625. }
  1626. $change = [];
  1627. while ($rowCh = $db->fetch_object($resultCh)) {
  1628. $rowCh = (array) $rowCh;
  1629. $ChangeArray = explode('_', $rowCh['ref']);
  1630. $key = isset($ChangeArray[1]) ? strtolower($ChangeArray[1]) : '';
  1631. if (!empty($key)) {
  1632. $change[$key] = isset($rowCh['title']) ? $rowCh['title'] : '';
  1633. }
  1634. }
  1635. } else {
  1636. return [];
  1637. }
  1638. return [
  1639. 'date' => $date,
  1640. 'devices' => $device,
  1641. 'change' => $change
  1642. ];
  1643. }
  1644. /**
  1645. * Save card payment log
  1646. *
  1647. * @param string $invoice_ref
  1648. * @param string $data
  1649. *
  1650. * @return array|mixed Data without useless information
  1651. *
  1652. * @url POST /cardpaymentlog
  1653. *
  1654. * @throws RestException 401
  1655. * @throws RestException 403
  1656. * @throws RestException 404
  1657. */
  1658. public function cardPaymentLog(string $invoice_ref, string $data)
  1659. {
  1660. $result = 'OK';
  1661. $facture = new Facture($this->db);
  1662. if ($facture->fetch(0, $invoice_ref) > 0) {
  1663. $facture->array_options['options_payment_log'] = $data;
  1664. $facture->updateExtraField('payment_log');
  1665. $json = json_decode($data, true);
  1666. if (!empty($json['authorization_number'])) {
  1667. $sql = "
  1668. UPDATE " . MAIN_DB_PREFIX . "paiement
  1669. SET num_paiement='" . $json['authorization_number'] . "'
  1670. WHERE rowid=(
  1671. SELECT fk_paiement
  1672. FROM " . MAIN_DB_PREFIX . "paiement_facture
  1673. WHERE fk_facture={$facture->id}
  1674. )
  1675. ";
  1676. $this->db->query($sql);
  1677. }
  1678. } else {
  1679. $result = 'Missing invoice';
  1680. }
  1681. return $result;
  1682. }
  1683. /**
  1684. * Products list with children
  1685. *
  1686. * @param string $sortfield Sort field
  1687. * @param string $sortorder Sort order
  1688. * @param int $limit Limit for list
  1689. * @param int $page Page number
  1690. * @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service)
  1691. * @param int $category Use this param to filter list by category
  1692. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)"
  1693. * @param bool $ids_only Return only IDs of product instead of all properties (faster, above all if list is long)
  1694. * @param int $variant_filter Use this param to filter list (0 = all, 1=products without variants, 2=parent of variants, 3=variants only)
  1695. * @param bool $pagination_data If this parameter is set to true the response will include pagination data. Default value is false. Page starts from 0
  1696. * @param int $includestockdata Load also information about stock (slower)
  1697. * @return array Array of product objects
  1698. *
  1699. * @url GET /products
  1700. *
  1701. * @throws RestException 401
  1702. * @throws RestException 403
  1703. * @throws RestException 404
  1704. */
  1705. public function products($sortfield = 't.ref', $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $ids_only = false, $variant_filter = 0, $pagination_data = false, $includestockdata = 0): array
  1706. {
  1707. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  1708. throw new RestException(403);
  1709. }
  1710. $productsArray = [];
  1711. $productsArray = (new ApiProductListHelper)->list($sortfield, $sortorder, $limit, $page, $mode, $category, $sqlfilters, $ids_only, $variant_filter, $pagination_data, $includestockdata);
  1712. return $productsArray;
  1713. }
  1714. /**
  1715. * Products list with children
  1716. *
  1717. * @param string $sortfield Sort field
  1718. * @param string $sortorder Sort order
  1719. * @param int $limit Limit for list
  1720. * @param int $page Page number
  1721. * @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service)
  1722. * @param int $category Use this param to filter list by category
  1723. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)"
  1724. * @param bool $ids_only Return only IDs of product instead of all properties (faster, above all if list is long)
  1725. * @param int $variant_filter Use this param to filter list (0 = all, 1=products without variants, 2=parent of variants, 3=variants only)
  1726. * @param bool $pagination_data If this parameter is set to true the response will include pagination data. Default value is false. Page starts from 0
  1727. * @param int $includestockdata Load also information about stock (slower)
  1728. * @return array Array of product objects
  1729. *
  1730. * @url GET /productshotel
  1731. *
  1732. * @throws RestException 401
  1733. * @throws RestException 403
  1734. * @throws RestException 404
  1735. */
  1736. public function productshotel($sortfield = 't.ref', $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $ids_only = false, $variant_filter = 0, $pagination_data = false, $includestockdata = 0): array
  1737. {
  1738. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  1739. throw new RestException(403);
  1740. }
  1741. return (new ApiProductListHelper)->listhotel($sortfield, $sortorder, $limit, $page, $mode, $category, $sqlfilters, $ids_only, $variant_filter, $pagination_data, $includestockdata);
  1742. }
  1743. /**
  1744. * Create invoice
  1745. *
  1746. * @param array $invoice Invoice data
  1747. * @param array $lines Invoice lines
  1748. * @param array $payment Invoice payment
  1749. * @param string $cardPaymentLog Card payment log data
  1750. *
  1751. * @return array|mixed Data without useless information
  1752. *
  1753. * @url POST /invoice
  1754. */
  1755. public function invoice(array $invoice, array $lines, array $payment, string $cardPaymentLog = '', string $sendId = '', $server_host_curl = false, $company_invoice = '')
  1756. {
  1757. global $user, $conf;
  1758. $lockLabel = 'CREATE_INVOICE';
  1759. if (empty($sendId)) {
  1760. $sendId = substr(md5(rand()), 0, 8);
  1761. }
  1762. /**
  1763. * LOG SECTION
  1764. */
  1765. ApiBbusLog::appLog("{$sendId} === NEW INVOICE ===");
  1766. dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
  1767. ApiBbusLog::appLog("{$sendId} REQUEST: {$sendId}");
  1768. dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
  1769. ApiBbusLog::appLog("{$sendId} User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
  1770. dol_syslog("{$sendId} User: {$user->firstname} {$user->lastname} (ID: {$user->id})", LOG_INFO, 0);
  1771. ApiBbusLog::appLog("{$sendId} " . json_encode([
  1772. 'invoice' => $invoice,
  1773. 'lines' => $lines,
  1774. 'payment' => $payment,
  1775. 'cardPaymentLog' => $cardPaymentLog
  1776. ]));
  1777. /**
  1778. * CHECK RIGHTS
  1779. */
  1780. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  1781. ApiBbusLog::appLog("{$sendId} Insufficient rights");
  1782. throw new RestException(401, 'Insufficient rights');
  1783. }
  1784. $apiInvoiceHelper = new ApiInvoiceHelper;
  1785. $BookingApi = new BookingApi;
  1786. /**
  1787. * handle invoice basic data
  1788. */
  1789. $invoiceObj = $apiInvoiceHelper->createInvoice($invoice, $sendId, $company_invoice);
  1790. ApiBbusLog::appLog("{$sendId} Invoice created");
  1791. /**
  1792. * handle invoice line(s)
  1793. */
  1794. $products = [];
  1795. foreach ($lines as $line) {
  1796. $invoiceObj = $apiInvoiceHelper->addLineToInvoice($invoiceObj, $line, $sendId);
  1797. $product = $apiInvoiceHelper->loadProductToResult($line);
  1798. if (!empty($product)) {
  1799. $products[] = $product;
  1800. }
  1801. }
  1802. $invoiceObj->fetch_lines();
  1803. foreach ($products as &$row) {
  1804. foreach ($invoiceObj->lines as $line) {
  1805. if ($line->product_ref == $row['ref']) {
  1806. //$row['price'] = $line->total_ttc;
  1807. $row['price'] = $line->multicurrency_total_ttc;
  1808. $row['total_tva'] = $line->total_tva;
  1809. //$row['total_tva'] = $line->multicurrency_total_tva;
  1810. }
  1811. }
  1812. }
  1813. /**
  1814. * validate
  1815. */
  1816. $invoiceObj = $apiInvoiceHelper->validateInvoice($invoiceObj, $sendId);
  1817. /**
  1818. * set payment
  1819. */
  1820. $apiInvoiceHelper->setPayment($invoiceObj, $payment, $sendId);
  1821. /**
  1822. * save card payment data
  1823. */
  1824. if (!empty($cardPaymentLog)) {
  1825. $invoiceObj = $apiInvoiceHelper->saveCardPaymentLog($invoiceObj, $cardPaymentLog, $sendId);
  1826. }
  1827. ApiBbusLog::appLog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}");
  1828. dol_syslog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}", LOG_INFO, 0);
  1829. //$bbApiLock->delete($user);
  1830. ApiBbusLog::appLog("{$sendId}####################################################################");
  1831. dol_syslog("{$sendId}####################################################################", LOG_INFO, 0);
  1832. #-------------- UPDATE BTICKET --------------
  1833. foreach ($products as $product) {
  1834. $server_host = '';
  1835. $proSQL = "SELECT bbs.server_host FROM llx_product as pr
  1836. INNER JOIN llx_product_extrafields as pre ON pre.fk_object = pr.rowid
  1837. INNER JOIN llx_bbus_basicservices as bbs ON bbs.rowid = CAST(pre.basic_service AS integer)
  1838. WHERE pr.rowid = {$product['id']}";
  1839. $proResult = $this->db->query($proSQL);
  1840. if ($this->db->num_rows($proResult) > 0) {
  1841. while ($proRow = $this->db->fetch_object($proResult)) {
  1842. $server_host = $proRow->server_host;
  1843. }
  1844. }
  1845. if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
  1846. $BookingApi->updateBbticket(get_object_vars($invoiceObj), null);
  1847. } else {
  1848. ApiBbusLog::appLog("{$sendId}: Update bbticket with curl");
  1849. $invoiceForCurl['id'] = $invoiceObj->id;
  1850. $invoiceForCurl['ref'] = $invoiceObj->ref;
  1851. $array['invoice'] = $invoiceForCurl;
  1852. $updateBBticketPostFields = json_encode($array);
  1853. ApiBbusLog::appLog("{$updateBBticketPostFields}");
  1854. $this->curlRunner('bookingapi/curlUpdateBbticket', $updateBBticketPostFields, 'POST', true);
  1855. }
  1856. }
  1857. return [
  1858. 'sendId' => $sendId,
  1859. 'invoice' => [
  1860. 'id' => $invoiceObj->id,
  1861. 'ref' => $invoiceObj->ref,
  1862. 'total' => $invoiceObj->multicurrency_total_ttc
  1863. ],
  1864. 'products' => $products,
  1865. ];
  1866. }
  1867. /**
  1868. * Get the saled factures data by user
  1869. *
  1870. * @param string $date Date
  1871. *
  1872. * @return array|mixed Data without useless information
  1873. *
  1874. * @url POST /saledfacturesbyuser
  1875. */
  1876. function saledfacturesbyuser(string $date)
  1877. {
  1878. global $user, $db;
  1879. $date = date("Y-m-d", dol_now());
  1880. $fulldate = date("Y-m-d H:i:s", dol_now());
  1881. $apiBbusHelper = new ApiBBusHelper();
  1882. $from = $apiBbusHelper->getGroupLoginDate($date);
  1883. $to = $apiBbusHelper->getGroupLogout($date, $from);
  1884. $array = [];
  1885. if (strtotime($fulldate) > strtotime($to)) {
  1886. return $array;
  1887. }
  1888. $sql = "SELECT
  1889. f.rowid as facture_rowid,
  1890. f.ref AS facture_ref,
  1891. f.datec,
  1892. f.multicurrency_code,
  1893. pa.libelle,
  1894. fe.payment_transaction_id::TEXT AS transaction_id,
  1895. fdet.fk_product AS product_id,
  1896. pr.label AS product_label,
  1897. pr.ref AS product_ref,
  1898. pr.description,
  1899. pass.fk_product_pere AS bundle_id,
  1900. pr2.label AS bundle_label,
  1901. pr2.ref AS bundle_ref,
  1902. fdet.multicurrency_total_tva AS base_tva,
  1903. fdet.multicurrency_total_ttc AS base_ttc,
  1904. fdete.discount_percent,
  1905. fdete.discount_hours,
  1906. pr.default_vat_code,
  1907. f.multicurrency_total_ttc AS bundle_ttc,
  1908. (SELECT rate FROM llx_multicurrency_rate AS mc WHERE mc.fk_multicurrency = f.fk_multicurrency AND mc.entity = {$user->entity} ORDER BY mc.rowid DESC LIMIT 1) AS rate,
  1909. (SELECT date_start FROM llx_booking_bookinghistory AS bh WHERE bh.fk_facture = f.rowid) AS date_start
  1910. FROM llx_facture AS f
  1911. INNER JOIN llx_facture_extrafields AS fe ON fe.fk_object = f.rowid
  1912. INNER JOIN llx_c_paiement AS pa ON pa.id = f.fk_mode_reglement
  1913. INNER JOIN llx_paiement_facture AS pafa ON pafa.fk_facture = f.rowid
  1914. INNER JOIN llx_paiement AS pai ON pai.rowid = pafa.fk_paiement
  1915. INNER JOIN llx_facturedet AS fdet ON fdet.fk_facture = f.rowid
  1916. INNER JOIN llx_product AS pr ON pr.rowid = fdet.fk_product
  1917. left JOIN llx_product_association AS pass ON pass.fk_product_fils = pr.rowid
  1918. LEFT JOIN llx_product AS pr2 ON pr2.rowid = pass.fk_product_pere
  1919. LEFT JOIN llx_facturedet_extrafields AS fdete ON fdet.rowid = fdete.fk_object
  1920. WHERE f.datec BETWEEN '{$from}' AND '{$to}'
  1921. AND f.fk_user_closing = $user->id
  1922. ORDER BY f.rowid DESC";
  1923. //print $sql;exit;
  1924. $data = $db->query($sql);
  1925. if ($db->num_rows($data > 0)) {
  1926. while ($row = $db->fetch_object($data)) {
  1927. $row->bundle_id = $row->bundle_id == '' ? $row->product_id : $row->bundle_id;
  1928. $row->bundle_label = $row->bundle_label == '' ? $row->product_label : $row->bundle_label;
  1929. $row->bundle_ref = $row->bundle_ref == '' ? $row->product_ref : $row->bundle_ref;
  1930. $array[$row->facture_rowid]['ref'] = $row->facture_ref;
  1931. $array[$row->facture_rowid]['bundle_name'] = $row->bundle_label;
  1932. $array[$row->facture_rowid]['currency'] = $row->multicurrency_code;
  1933. $array[$row->facture_rowid]['total_price'] = $row->bundle_ttc;
  1934. $array[$row->facture_rowid]['type'] = $row->libelle;
  1935. $array[$row->facture_rowid]['transaction_id'] = $row->transaction_id;
  1936. $array[$row->facture_rowid]['rate'] = $row->rate;
  1937. $array[$row->facture_rowid]['date'] = $row->datec;
  1938. $array[$row->facture_rowid]['lines'][$row->product_id] = (array) $row;
  1939. }
  1940. return $array;
  1941. } else {
  1942. return $array;
  1943. }
  1944. }
  1945. /**
  1946. * List of assets received
  1947. *
  1948. * Return an array with assets received.
  1949. *
  1950. * @return array|mixed Data without useless information
  1951. *
  1952. * @url GET /getAllUsersOfTheGroup
  1953. *
  1954. * @throws RestException 401
  1955. * @throws RestException 403
  1956. * @throws RestException 404
  1957. */
  1958. public function getAllUsersOfTheGroup(): array
  1959. {
  1960. global $user, $db;
  1961. $array = [];
  1962. $sql = "SELECT u.rowid, u.firstname, u.lastname, u.login, ue.nickname, u.email, u.office_phone, u.user_mobile, u.personal_mobile FROM llx_settlements_groupusers AS gu
  1963. INNER JOIN llx_user_extrafields as ue ON ue.fk_object = gu.fk_user
  1964. INNER JOIN llx_user as u ON u.rowid = gu.fk_user
  1965. WHERE gu.fk_settlements_group = (SELECT gu2.fk_settlements_group FROM llx_settlements_groupusers as gu2 WHERE gu2.fk_user = {$user->id})";
  1966. $data = $db->query($sql);
  1967. while ($row = $db->fetch_object($data)) {
  1968. $array[] = [
  1969. 'id' => $row->rowid,
  1970. 'name' => $row->firstname . ' ' . $row->lastname,
  1971. 'login' => $row->login,
  1972. 'email' => $row->email,
  1973. 'nickname' => $row->nickname ? $row->nickname : '',
  1974. 'office_phone' => $row->office_phone,
  1975. 'user_mobile' => $row->user_mobile,
  1976. 'personal_mobile' => $row->personal_mobile
  1977. ];
  1978. }
  1979. return $array;
  1980. }
  1981. /**
  1982. * Generate events
  1983. *
  1984. * @return array|mixed Data without useless information
  1985. *
  1986. * @url GET /genEvents
  1987. *
  1988. * @throws RestException 401
  1989. * @throws RestException 403
  1990. * @throws RestException 404
  1991. */
  1992. public function genEvents()
  1993. {
  1994. $period = new DatePeriod(
  1995. new DateTime('2024-05-09'),
  1996. new DateInterval('P1D'),
  1997. new DateTime('2024-09-01')
  1998. );
  1999. $size = 30;
  2000. $buffer = 5;
  2001. $dates = [];
  2002. foreach ($period as $date) {
  2003. if (rand(0, 1)) {
  2004. $eventDate = $date->format('Y-m-d');
  2005. $eventTimes = array_rand(
  2006. array_flip([
  2007. '16:00',
  2008. '18:00',
  2009. '20:00',
  2010. '22:00'
  2011. ]),
  2012. rand(1, 4)
  2013. );
  2014. /* print $eventDate;
  2015. print "\r\n";
  2016. print_r($eventTimes); */
  2017. if (is_array($eventTimes)) {
  2018. foreach ($eventTimes as $eventTime) {
  2019. $dates[$eventDate][] = [
  2020. 'start' => $eventTime,
  2021. 'duration' => '02:00:00',
  2022. ];
  2023. }
  2024. }
  2025. }
  2026. }
  2027. $dates = ['dates' => $dates];
  2028. dol_include_once('/eventwizard/class/eventdetails.class.php');
  2029. $object = new EventDetails($this->db);
  2030. $object->fetch(1);
  2031. $object->genEvents($dates);
  2032. return [];
  2033. }
  2034. /**
  2035. * Generate events
  2036. *
  2037. * @return array|mixed Data without useless information
  2038. *
  2039. * @url GET /updateeventextrafields
  2040. *
  2041. * @throws RestException 401
  2042. * @throws RestException 403
  2043. * @throws RestException 404
  2044. */
  2045. public function updateEventsExtrafields()
  2046. {
  2047. $sql = "SELECT ac.id FROM llx_actioncomm as ac
  2048. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  2049. WHERE ac.code = 'AC_EVENT'
  2050. AND ace.fk_object IS NULL";
  2051. $result1 = $this->db->query($sql);
  2052. while ($row1 = $this->db->fetch_object($result1)) {
  2053. $sql2 = "INSERT INTO llx_actioncomm_extrafields (fk_object, max_num, buffer)
  2054. VALUES ({$row1->id}, 30, 5)";
  2055. $result = $this->db->query($sql2);
  2056. }
  2057. }
  2058. /**
  2059. * Generate factures
  2060. *
  2061. * @return array|mixed Data without useless information
  2062. *
  2063. * @url POST /generateFactures
  2064. *
  2065. * @throws RestException 401
  2066. * @throws RestException 403
  2067. * @throws RestException 404
  2068. */
  2069. public function generateFactures()
  2070. {
  2071. $numberOfFactures = 1;
  2072. for ($i = 0; $i < $numberOfFactures; $i++) {
  2073. $currencyRand = rand(0, 1);
  2074. $currencyText = [0 => 'HUF', 1 => 'EUR'];
  2075. $currencyNumber = [0 => 3, 1 => 5];
  2076. $reglementRand = rand(14, 15);
  2077. //$reglementRand = rand(106, 107); ## STAGING
  2078. $mode_reglement_id = $reglementRand;
  2079. $paymentid = $reglementRand;
  2080. $accountid = [0 => 4, 1 => 5];
  2081. $deduction = rand(1, 5) == 3 ? 1 : null;
  2082. $storno = rand(1, 5) == 1 ? 1 : null;
  2083. $invoice = ["mode_reglement_id" => $mode_reglement_id, "array_options_app_facture" => 1, "array_options_commission_deduction" => $deduction, "array_options_marked_for_storno" => $storno, "multicurrency_code" => $currencyText[$currencyRand], "fk_multicurrency" => $currencyNumber[$currencyRand], "array_options_customer_data_zip" => null];
  2084. $linesHUFBundle = [
  2085. ["desc" => "", "subprice" => "787.4015", "qty" => 1, "tva_tx" => "27.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "102", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"],
  2086. ["desc" => "", "subprice" => "13333.3333", "qty" => 1, "tva_tx" => "5.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "108", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"]
  2087. ];
  2088. $linesEURBundle = [
  2089. ["desc" => "", "subprice" => "2.3622", "qty" => 1, "tva_tx" => "27.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "101", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"],
  2090. ["desc" => "", "subprice" => "33.3333", "qty" => 1, "tva_tx" => "5.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "107", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"]
  2091. ];
  2092. $linesEURSimple = [
  2093. ["desc" => "", "subprice" => "12.5984", "qty" => 1, "tva_tx" => "27.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "132", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"],
  2094. ];
  2095. $linesArray = [
  2096. 0 => $linesEURBundle,
  2097. 1 => $linesEURSimple,
  2098. 2 => $linesHUFBundle
  2099. ];
  2100. if ($currencyRand == 1) {
  2101. $lineRand = rand(0, 1);
  2102. $lines = $linesArray[$lineRand];
  2103. } else {
  2104. $lines = $linesArray[2];
  2105. }
  2106. $payment = ["datepaye" => time(), "paymentid" => $paymentid, "closepaidinvoices" => "yes", "accountid" => $accountid[$currencyRand]];
  2107. $comment = "{\"timestamp\":\"1704241200\",\"merchant_id\":\"000000000014202\",\"acquirer_id\":\"88105000003\",\"operation_number\":\"000037\",\"termid\":\"36002058\",\"pan\":\"428312******1789\",\"exp\":\"****\",\"stan\":\"000007\",\"authorization_number\":\"282597\",\"trans_type\":\"CLI\",\"amount\":\"2.0\",\"cvm\":\"2\",\"billnumber\":\"AcTbHmcWsMGcF6Nf\",\"card_transaction_id\":\"AcTbHmcWsMGcF6Nf\"}";
  2108. $payment['comment'] = $reglementRand == 15 ? '' : $comment;
  2109. //$payment['comment'] = $reglementRand == 107 ? '' : $comment; ## STAGING
  2110. $cardPaymentLog = "";
  2111. /* print_r($invoice);
  2112. print_r($lines);
  2113. print_r($payment);
  2114. exit; */
  2115. $invoiceNumber = $this->invoice($invoice, $lines, $payment, $cardPaymentLog, $sendId = '');
  2116. $ref = $invoiceNumber['invoice']['ref'];
  2117. $datetime = date("Y-m-d H:i:s", $payment['datepaye']);
  2118. $multiprint = rand(1, 5);
  2119. $this->dateHandler($ref, $datetime);
  2120. if ($multiprint == 2 || $multiprint == 3) {
  2121. $prints = rand(1, 5);
  2122. $dateofprint = $payment['datepaye'];
  2123. for ($i = 0; $i < $prints; $i++) {
  2124. $dateofprint = strtotime('+5 seconds', $dateofprint);
  2125. $datetime = date("Y-m-d H:i:s", $dateofprint);
  2126. $this->dateHandler($ref, $datetime);
  2127. }
  2128. }
  2129. }
  2130. return 'OK';
  2131. }
  2132. /**
  2133. * Generate events
  2134. *
  2135. * @return array|mixed Data without useless information
  2136. *
  2137. * @url GET /getDatetime
  2138. *
  2139. * @throws RestException 401
  2140. * @throws RestException 403
  2141. * @throws RestException 404
  2142. */
  2143. public function getDatetime()
  2144. {
  2145. $dateArray = [];
  2146. $now = dol_now();
  2147. $dateArray = ["timestamp" => $now, "date" => date("Y-m-d", $now), "datetime" => date("Y-m-d H:i:s", $now)];
  2148. return $dateArray;
  2149. }
  2150. /**
  2151. * Get the saled factures data by user
  2152. *
  2153. * @param string $ref Date
  2154. *
  2155. * @return array|mixed Data without useless information
  2156. *
  2157. * @url POST /curlgetdatecfromfacture
  2158. */
  2159. public function curlgetdatecfromfacture(string $ref)
  2160. {
  2161. $sql = "SELECT datec FROM llx_facture WHERE ref = '{$ref}'";
  2162. $result = $this->db->query($sql);
  2163. if ($this->db->num_rows($result) < 1) {
  2164. return [];
  2165. } else {
  2166. while ($row = $this->db->fetch_object($result)) {
  2167. return $row->datec;
  2168. }
  2169. }
  2170. }
  2171. /**
  2172. * Get the saled factures data by user
  2173. *
  2174. * @param string $ref Date
  2175. *
  2176. * @return array|mixed Data without useless information
  2177. *
  2178. * @url POST /curlgetproductidfromfacturedet
  2179. */
  2180. public function curlgetproductidfromfacturedet(string $ref)
  2181. {
  2182. ApiBbusLog::appLog("curlgetproductidfromfacturedet");
  2183. $helper = new ApiBBusHelper();
  2184. $facture_id = $helper->getFactureIdForInvoicePrinting($ref);
  2185. global $db;
  2186. $array = [];
  2187. $sql = "SELECT fk_product FROM public.llx_facturedet WHERE fk_facture = " . $facture_id;
  2188. $result = $db->query($sql);
  2189. while ($facturedetrecord = pg_fetch_assoc($result)) {
  2190. $array[] = $facturedetrecord['fk_product'];
  2191. }
  2192. return $array;
  2193. }
  2194. /**
  2195. * Create SQL queries for products clone
  2196. *
  2197. * @return array|mixed Data without useless information
  2198. *
  2199. * @url POST /giveMeAllProducts
  2200. *
  2201. * @throws RestException 401
  2202. * @throws RestException 403
  2203. * @throws RestException 404
  2204. */
  2205. public function giveMeAllProducts()
  2206. {
  2207. $productsArray = [];
  2208. $sql = "SELECT * FROM llx_product";
  2209. $result = $this->db->query($sql);
  2210. while ($row = $this->db->fetch_object($result)) {
  2211. $productsArray[$row->rowid]['product'] = $row;
  2212. $sqlef = "SELECT * FROM llx_product_extrafields WHERE fk_object = {$row->rowid}";
  2213. $resultef = $this->db->query($sqlef);
  2214. while ($rowef = $this->db->fetch_object($resultef)) {
  2215. $contentef = "-- new Extrafields row {$rowef->rowid}
  2216. DELETE FROM llx_product_extrafields WHERE fk_object = {$rowef->rowid};
  2217. INSERT INTO llx_product_extrafields (";
  2218. $valueContentef = "";
  2219. $keyNumberef = count((array)$rowef);
  2220. $keyNumberef - 2;
  2221. $counteref = 1;
  2222. foreach ($rowef as $efkey => $efvalue) {
  2223. if ($efkey == 'oneoccasion' || $efkey == 'online') {
  2224. $counteref++;
  2225. } else {
  2226. $contentef .= "{$efkey}";
  2227. if ($efkey == 'fk_user_author') {
  2228. $valueContentef .= intval(1);
  2229. } elseif ($efkey == 'fk_user_modif') {
  2230. $valueContentef .= intval(1);
  2231. } else {
  2232. $valueContentef .= "{$this->getvvalue($efvalue)}";
  2233. }
  2234. if ($counteref <= $keyNumberef - 1) {
  2235. $contentef .= ", ";
  2236. $valueContentef .= ", ";
  2237. } else {
  2238. $contentef .= ") VALUES (";
  2239. $valueContentef .= ") ON CONFLICT (rowid) DO NOTHING;";
  2240. }
  2241. $counteref++;
  2242. }
  2243. }
  2244. $asdef = $contentef . $valueContentef;
  2245. $productsArray[$row->rowid]['extrafields'] = $asdef;
  2246. }
  2247. $sqlprice = "SELECT * FROM llx_product_price WHERE fk_product = {$row->rowid}";
  2248. $resultprice = $this->db->query($sqlprice);
  2249. while ($rowprice = $this->db->fetch_object($resultprice)) {
  2250. $contentprice = "-- product price rowid: {$rowprice->rowid}
  2251. DELETE FROM llx_product_price WHERE rowid = {$rowprice->rowid};
  2252. INSERT INTO llx_product_price (";
  2253. $valueContentprice = "";
  2254. $keyNumber = count((array)$rowprice);
  2255. $counter = 1;
  2256. foreach ($rowprice as $pricekey => $pricevalue) {
  2257. //print $pricekey . "\r\n";
  2258. $contentprice .= "{$pricekey}";
  2259. if ($pricekey == 'fk_user_author') {
  2260. $valueContentprice .= intval(1);
  2261. } elseif ($pricekey == 'fk_user_modif') {
  2262. $valueContentprice .= intval(1);
  2263. } else {
  2264. $valueContentprice .= "{$this->getvvalue($pricevalue)}";
  2265. }
  2266. if ($counter <= $keyNumber - 1) {
  2267. $contentprice .= ", ";
  2268. $valueContentprice .= ", ";
  2269. } else {
  2270. $contentprice .= ") VALUES (";
  2271. $valueContentprice .= ") ON CONFLICT (rowid) DO NOTHING;";
  2272. }
  2273. $counter++;
  2274. }
  2275. $asdprice = $contentprice . $valueContentprice;
  2276. $productsArray[$row->rowid]['prices'] = $asdprice;
  2277. }
  2278. //exit;
  2279. }
  2280. foreach ($productsArray as $key => $value) {
  2281. if ($key > 4999) {
  2282. $content = "-- product rowid: {$key}
  2283. INSERT INTO llx_product_temp (";
  2284. $valueContent = "";
  2285. $keyNumber = count((array)$value['product']);
  2286. $counter = 1;
  2287. foreach ($value['product'] as $vkey => $vvalue) {
  2288. $content .= "{$vkey}";
  2289. if ($vkey == 'fk_user_author') {
  2290. $valueContent .= intval(1);
  2291. } elseif ($vkey == 'fk_user_modif') {
  2292. $valueContent .= intval(1);
  2293. } else {
  2294. $valueContent .= "{$this->getvvalue($vvalue)}";
  2295. }
  2296. if ($counter <= $keyNumber - 1) {
  2297. $content .= ", ";
  2298. $valueContent .= ", ";
  2299. } else {
  2300. $content .= ") VALUES (";
  2301. $valueContent .= ") ON CONFLICT (rowid) DO NOTHING;";
  2302. }
  2303. $counter++;
  2304. }
  2305. }
  2306. $asd = $content . $valueContent;
  2307. print $asd . "\r\n";
  2308. //print $value['extrafields'] . "\r\n";
  2309. //print $value['prices'] . "\r\n";
  2310. }
  2311. exit;
  2312. }
  2313. function getvvalue($value)
  2314. {
  2315. //$value = str_replace("'", '"', $value);
  2316. if (is_numeric($value)) {
  2317. $value = intval($value);
  2318. } else {
  2319. if (is_null($value)) {
  2320. $value = 'NULL';
  2321. } else {
  2322. $value = "'" . $value . "'";
  2323. }
  2324. }
  2325. return $value;
  2326. }
  2327. /**
  2328. * Get events ids
  2329. *
  2330. * @return array|mixed Data without useless information
  2331. *
  2332. * @url POST /getAllEventids
  2333. */
  2334. public function getAllEventids()
  2335. {
  2336. global $db;
  2337. $array = [];
  2338. $sql = "SELECT rowid FROM llx_bbus_basicservices WHERE is_event = '1'";
  2339. $result = $db->query($sql);
  2340. if ($db->num_rows($result) > 0) {
  2341. while ($row = $db->fetch_object($result)) {
  2342. $array[] = $row->rowid;
  2343. }
  2344. }
  2345. return $array;
  2346. }
  2347. }