api_bbus.class.php 74 KB

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