api_bbus.class.php 89 KB

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