api_bbus.class.php 76 KB

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