소스 검색

merges, check excelia and bbus differences

szollosil 1 년 전
부모
커밋
a628f2310c

+ 3 - 0
custom/bbus/class/api_bbus.class.php

@@ -485,6 +485,7 @@ class BBus extends DolibarrApi
 				$bbTicketsByFacture = $this->getTicketsByFactureId($facture_id);
 			}
 			foreach ($bbTicketsByFacture as $ticket) {
+				ApiBbusLog::appLog("Create BBticketInvoiceprinting record");
 				// Rogzitem a bbticketinvoiceprinting tablaba a rekordot
 				$helper->setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticket, $ref);
 			}
@@ -1844,6 +1845,8 @@ class BBus extends DolibarrApi
 		 * handle invoice basic data
 		 */
 		$invoiceObj = $apiInvoiceHelper->createInvoice($invoice, $sendId);
+		ApiBbusLog::appLog("{$sendId} Invoice created");
+
 		/**
 		 * handle invoice line(s)
 		 */

+ 23 - 1
custom/bbus/class/api_bbus.class.php.bak

@@ -635,9 +635,13 @@ class BBus extends DolibarrApi
 			}
 			if (!empty($productsArray)) {
 				foreach ($productsArray as $key => $value) {
+					ApiBbusLog::appLog("SERVER_HOST: " . $server_host);
+					ApiBbusLog::appLog("CONF_SERVER_HOST: " . $conf->global->LOCAL_SERVER_HOST);
 					if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
+						ApiBbusLog::appLog($conf->global->LOCAL_SERVER_HOST);
 						$availableResult = $this->localCheckAvailablePlacesForCheckPermission($key);
 					} elseif ($server_host == $conf->global->CURL_SERVER_HOST) {
+						ApiBbusLog::appLog($conf->global->CURL_SERVER_HOST);
 						$postFields = '{"product_id":"' . $key . '"}';
 						$availableResult = $this->curlRunner('bbus/localCheckAvailablePlacesForCheckPermission', $postFields, 'POST', false);
 					}
@@ -665,6 +669,7 @@ class BBus extends DolibarrApi
 	 */
 	public function localCheckAvailablePlacesForCheckPermission($product_id)
 	{
+		$date_from = $this->getCutOffTimeDate($product_id);
 		$sql = "SELECT 
 			ac.id
 			FROM llx_actioncomm as ac 
@@ -673,11 +678,28 @@ class BBus extends DolibarrApi
 			INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
 			WHERE ac.code = 'AC_EVENT'
 			AND ep.fk_product = {$product_id}
-			AND ac.datep > NOW() 
+			AND ac.datep > '{$date_from}' 
 			ORDER BY ac.datep ASC";
+		ApiBbusLog::appLog($sql);
+
 			$result = $this->db->query($sql);
 		return $this->db->num_rows($result) > 0 ? 1 : 0;
+	}
 		
+	private function getCutOffTimeDate($product_id)
+	{
+		$date = date("Y-m-d H:i:s");
+		$sql = "SELECT cut_off_time_app FROM llx_product_extrafields WHERE fk_object = {$product_id}";
+		if ($result = $this->db->query($sql)) {
+			if ($this->db->num_rows($result) > 0) {
+				while ($row = $this->db->fetch_object($result)) {
+					$cutOffTime = $row->cut_off_time_app;
+				}
+				$dateTimestamp = strtotime($date);
+				$date = date("Y-m-d H:i:s", $dateTimestamp + $cutOffTime * 60);
+			}
+		}
+		return $date;
 	}
 
 	/**

+ 5 - 37
custom/bbus/class/api_bbus_helper.class.php

@@ -120,7 +120,6 @@ class ApiBBusHelper
 			}
 			if (isset($record['pere'])) {
 				$resultArray[$record['pere']]['count']++;
-				;
 			} else {
 				$resultArray[$record['pere']]['count'] = 1;
 			}
@@ -150,6 +149,7 @@ class ApiBBusHelper
 		ApiBbusLog::appLog("{$sql}");
 		$resultBBT = $db->query($sql);
 		if (pg_num_rows($resultBBT) < 1) {
+			ApiBbusLog::appLog("Invoice not found");
 			return [];
 		}
 		while ($row = pg_fetch_assoc($resultBBT)) {
@@ -167,12 +167,12 @@ class ApiBBusHelper
 		$newCopy->printing_date_timestamp = $datetime_timestamp;
 		$newCopy->ticket_id = $ticket->id; //bbticket -> rowid
 		$newCopy->product_id = $ticket->ticket_id; // product -> rowid = bbticket->ticket_id
-		$newCopy->invoice_number = $ref; // product -> rowid = bbticket->ticket_id
+		$newCopy->invoice_number = $ref;
 		if ($newCopy->create($user) > 0) {
-			ApiBbusLog::appLog("Invoiceprinting saved");
+			ApiBbusLog::appLog("BBticketInvoiceprinting saved");
 			// successful saving
 		} else {
-			ApiBbusLog::appLog("Invoiceprinting Insert failed");
+			ApiBbusLog::appLog("BBticketInvoiceprinting  save FAILED");
 			dol_syslog("Nem sikerult a bbticketinvoiceprinting insertje. facture_id: {$facture_id} datetime: {$datetime}");
 			throw new RestException(404, 'Insert failed');
 		}
@@ -205,7 +205,7 @@ class ApiBBusHelper
 		return $this->curlRunner('bbus/curlgetproductidfromfacturedet', $params, 'POST', true);
 	}
 
-	private function getproductIdFromFActuredet($facture_id)
+	public function getproductIdFromFActuredet($facture_id)
 	{
 		global $db;
 		$array = [];
@@ -364,38 +364,6 @@ class ApiBBusHelper
 			}
 		}
 
-
-		/*
-																	$sql = "
-																		SELECT c.* 
-																		FROM ".MAIN_DB_PREFIX."settlements_groupusers gu
-																		INNER JOIN ".MAIN_DB_PREFIX."settlements_group AS g ON g.rowid = gu.fk_settlements_group
-																		INNER JOIN ".MAIN_DB_PREFIX."const AS c ON c.entity = g.fk_entity
-																		WHERE gu.fk_user = {$user->id} AND c.name IN (
-																			'MAIN_INFO_SOCIETE_COUNTRY', 
-																			'MAIN_INFO_SOCIETE_NOM', 
-																			'MAIN_INFO_SOCIETE_ADDRESS', 
-																			'MAIN_INFO_SOCIETE_TOWN',
-																			'MAIN_INFO_SOCIETE_ZIP',
-																			'MAIN_INFO_SOCIETE_STATE',
-																			'MAIN_INFO_TVAINTRA'
-																		)";
-																	$entityData = $this->db->query($sql);
-																	while ($row = $this->db->fetch_array($entityData)) {
-																		$newStr = substr($row['name'], strlen('MAIN_INFO_'));
-																		if ($newStr != 'TVAINTRA') {
-																			$newStr = substr($newStr, strlen('SOCIETE_'));
-																		}
-																		$result[$newStr] = $row['value'];
-
-																		if (!empty($row['entity']) && is_null($entity)) {
-																			$entity = intval($row['entity']);
-																		}
-
-																	}
-																	*/
-
-
 		return [
 			'company_data' => $result,
 			'entity' => $entity

+ 512 - 0
custom/bbus/class/api_bbus_helper.class.php.bak

@@ -0,0 +1,512 @@
+<?php
+
+use Luracast\Restler\RestException;
+
+include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/groupusers.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/userloginnaplo.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticket.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketinvoiceprinting.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
+
+
+class ApiBBusHelper
+{
+	use CurlApi;
+
+	public $db;
+	const EMAIL_TEMPLATE = 'multiticketprinting';
+	const GLOBAL_CONF_SEND_TO_EMAIL = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL';
+	const GLOBAL_CONF_EMAIL_FROM = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL_FROM';
+
+	public function __construct()
+	{
+		global $db, $user;
+
+		$this->db = $db;
+	}
+
+	public function getSaledItems($date)
+	{
+		global $user, $db;
+		$from = $this->getGroupLoginDate($date);
+		$to = $this->getGroupLogout($date, $from);
+		$fulldate = date("Y-m-d H:i:s", dol_now());
+		$facturesArray = [];
+		if(strtotime($fulldate) > strtotime($to)){
+			return $facturesArray;
+		}
+
+		$sql = "SELECT f.rowid, pa.fk_product_pere, pr.label, pa.fk_product_fils, fdet.multicurrency_total_ttc, fdet.multicurrency_code FROM
+		llx_facture AS f
+		INNER JOIN llx_facturedet AS fdet ON fdet.fk_facture = f.rowid
+		INNER JOIN llx_product_association AS pa ON pa.fk_product_fils = fdet.fk_product
+		INNER JOIN llx_product AS pr ON pr.rowid = pa.fk_product_pere
+		WHERE f.fk_user_author = {$user->id}
+		AND f.entity = {$user->entity}
+		AND f.fk_statut = 2
+		AND f.datec BETWEEN '{$from}' AND '{$to}'
+		UNION 
+		SELECT f.rowid, fdet.fk_product as fk_product_pere, pr.label, fdet.fk_product as fk_product_fils, fdet.multicurrency_total_ttc, fdet.multicurrency_code FROM
+		llx_facture AS f
+		INNER JOIN llx_facturedet AS fdet ON fdet.fk_facture = f.rowid
+		INNER JOIN llx_product AS pr ON pr.rowid = fdet.fk_product
+		INNER JOIN llx_product_extrafields as pre ON pre.fk_object = pr.rowid
+		WHERE f.fk_user_author = {$user->id}
+		AND f.entity = {$user->entity}
+		AND f.fk_statut = 2
+		AND pre.is_in_bundle IS NULL
+		AND f.datec BETWEEN '{$from}' AND '{$to}'";
+		//print  $sql;exit;
+		$facatures = $db->query($sql);
+		$this->checkValidation($facatures, 'Factures');
+		while ($row = pg_fetch_assoc($facatures)) {
+			$facturesArray[] = $row;
+		}
+		return $facturesArray;
+	}
+
+	public function getGroupLoginDate($date)
+	{
+		global $user, $db;
+		$sqlusernaploLogin = "SELECT date_creation FROM public.llx_settlements_usernaplo
+		WHERE user_id = $user->id
+		AND status = 1
+		ORDER BY rowid DESC LIMIT 1";
+		$resultLogin = $db->query($sqlusernaploLogin);
+		if(pg_num_rows($resultLogin) > 0 && strtotime($date) == strtotime(date('Y-m-d', dol_now()))){
+			while ($row = pg_fetch_assoc($resultLogin)) {
+				return $row['date_creation'];
+			}
+		}
+		return $date . ' 00:00:00';
+	}
+
+	public function getGroupLogout($date, $from)
+	{
+		global $user, $db;
+		$sqlusernaploLogin = "SELECT date_creation FROM public.llx_settlements_usernaplo
+		WHERE user_id = $user->id
+		AND status = 0
+		ORDER BY rowid DESC LIMIT 1";
+		$resultLogin = $db->query($sqlusernaploLogin);
+		if(pg_num_rows($resultLogin) > 0){
+			while ($row = pg_fetch_assoc($resultLogin)) {
+				$to = $row['date_creation'];
+			}
+		}
+		return $from > $to ? $date . ' ' . date('H:i:s', dol_now()) : $to;
+	}
+
+	public function getSaledItemsArray($facturesArray)
+	{
+		$pereArray = [];
+		foreach ($facturesArray as $item) {
+			$pereArray[$item['rowid']]['pere'] = $item['fk_product_pere'];
+			$pereArray[$item['rowid']]['label'] = $item['label'];
+			if (isset($item['rowid'])) {
+				$pereArray[$item['rowid']]['sum'] += $item['multicurrency_total_ttc'];
+			} else {
+				$pereArray[$item['rowid']]['sum'] = $item['multicurrency_total_ttc'];
+			}
+			$pereArray[$item['rowid']]['currency'] = $item['multicurrency_code'];
+		}
+		$resultArray = [];
+		foreach ($pereArray as $record) {
+			if (isset($record['pere'])) {
+				$resultArray[$record['pere']]['sum'] += $record['sum'];
+			} else {
+				$resultArray[$record['pere']]['sum'] = $record['sum'];
+			}
+			if (isset($record['pere'])) {
+				$resultArray[$record['pere']]['count']++;
+				;
+			} else {
+				$resultArray[$record['pere']]['count'] = 1;
+			}
+			$resultArray[$record['pere']]['label'] = $record['label'];
+			$resultArray[$record['pere']]['currency'] = $record['currency'];
+		}
+
+		$array = [];
+		foreach ($resultArray as $row) {
+			$array[] = $row;
+		}
+
+		return $array;
+	}
+
+	private function checkValidation($res, $name)
+	{
+		if (pg_num_rows($res) == 0) {
+			throw new RestException(404, $name . ' not found');
+		}
+	}
+
+	public function getFactureIdForInvoicePrinting($ref)
+	{
+		global $db;
+		$sql = "SELECT * FROM llx_facture WHERE ref = '{$ref}'";
+		ApiBbusLog::appLog("{$sql}");
+		$resultBBT = $db->query($sql);
+		if (pg_num_rows($resultBBT) < 1) {
+			return [];
+		}
+		while ($row = pg_fetch_assoc($resultBBT)) {
+			return $row['rowid'];
+		}
+	}
+
+	public function setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticket, $ref)
+	{
+		global $db;
+		$newCopy = new BbTicketInvoicePrinting($db);
+		$newCopy->fk_user_api_key = $user->api_key;
+		$newCopy->fk_facture = $facture_id;
+		$newCopy->printing_date = $datetime;
+		$newCopy->printing_date_timestamp = $datetime_timestamp;
+		$newCopy->ticket_id = $ticket->id; //bbticket -> rowid
+		$newCopy->product_id = $ticket->ticket_id; // product -> rowid = bbticket->ticket_id
+		$newCopy->invoice_number = $ref; // product -> rowid = bbticket->ticket_id
+		if ($newCopy->create($user) > 0) {
+			ApiBbusLog::appLog("Invoiceprinting saved");
+			// successful saving
+		} else {
+			ApiBbusLog::appLog("Invoiceprinting Insert failed");
+			dol_syslog("Nem sikerult a bbticketinvoiceprinting insertje. facture_id: {$facture_id} datetime: {$datetime}");
+			throw new RestException(404, 'Insert failed');
+		}
+	}
+
+	public function getTicketIdsByFactureId($facture_id, $ref)
+	{
+		$object = new stdClass();
+		$object->fk_facture = $facture_id;
+		$object->fk_product = $this->getproductIdFromFActuredet($facture_id);
+		$object->invoice_number = $ref;
+		$bbTicketHandler = new BbTicketHandler();
+		// uj rekordot veszek fel a bbticket tablaba és visszaterek a rogzitett rekordok roid-javal
+		return $bbTicketHandler->addTicketForPrinting($object);
+	}
+
+	public function getTicketIdsForCrossShopping($ref)
+	{
+		ApiBbusLog::appLog("getTicketIdsForCrossShopping");
+		$object = new stdClass();
+		$object->invoice_number = $ref;
+		$object->fk_product = $this->curlGetproductIdFromFActuredet($ref);
+		$bbTicketHandler = new BbTicketHandler();
+		// uj rekordot veszek fel a bbticket tablaba és visszaterek a rogzitett rekordok roid-javal
+		return $bbTicketHandler->addTicketForPrintingCrossShopping($object);
+	}
+	
+	function curlGetproductIdFromFActuredet($ref){
+		$params = '{"ref":"' . $ref . '"}';
+		return $this->curlRunner('bbus/curlgetproductidfromfacturedet', $params, 'POST', true);
+	}
+
+	private function getproductIdFromFActuredet($facture_id)
+	{
+		global $db;
+		$array = [];
+		$sql = "SELECT fk_product FROM public.llx_facturedet WHERE fk_facture = " . $facture_id;
+		$result = $db->query($sql);
+		while ($facturedetrecord = pg_fetch_assoc($result)) {
+			$array[] = $facturedetrecord['fk_product'];
+		}
+		return $array;
+	}
+
+	public function sendMail($fk_facture, $datetime, $now): void
+	{
+		$const = new GlobalConst;
+		$recipients = $const->load(self::GLOBAL_CONF_SEND_TO_EMAIL);
+		$emailFrom = $const->load(self::GLOBAL_CONF_EMAIL_FROM);
+		//$recipients = 'szollosi.laszlo@urbanms.hu';
+		//$emailFrom = 'bbus@urbanms.hu';
+		if (!empty($recipients) && !empty($emailFrom)) {
+			$emailTemplateHandler = new EmailTemplateHandler;
+			$template = $emailTemplateHandler->load(self::EMAIL_TEMPLATE);
+			$templateObject = new stdClass();
+			foreach ($template as $key => $value) {
+				$templateObject->$key = $value;
+			}
+			if ($templateObject) {
+				$vars = [
+					'__FACTURE__' => $fk_facture,
+					'__DATETIME__' => $datetime,
+					'__PRINTINGDATE__' => $now
+				];
+				$template = $emailTemplateHandler->prepareTemplate($templateObject, $vars);
+
+				$mail = new CMailFile(
+					$template->topic,
+					$recipients,
+					$emailFrom,
+					$template->content,
+					null,
+					null,
+					null,
+					'',
+					'',
+					0,
+					1
+				);
+				// Send Email
+				$mail->sendfile();
+
+				if ($mail->error) {
+					//print_r($mail->error);
+					//exit;
+					// do something...
+					dol_syslog('CRON ALERT EMAIL ERROR: ' . $mail->error, LOG_ERR);
+				}
+			}
+		}
+	}
+	/**
+	 * 
+	 */
+	public function getAppCustomers(): array
+	{		
+		$customers = [];
+
+		$table = (new Societe($this->db))->table_element;
+
+		$sql = "
+			SELECT soc.rowid AS id, soc.nom AS name, soc.address, soc.zip, soc.town, (CASE WHEN soc.nom ILIKE '%eur%' THEN 'EUR' ELSE 'HUF' END) AS currency
+			FROM ".MAIN_DB_PREFIX.$table." as soc
+			INNER JOIN ".MAIN_DB_PREFIX.$table."_extrafields as socex ON soc.rowid = socex.fk_object
+			WHERE socex.is_general_customer = 1
+			ORDER BY soc.rowid ASC 
+		";
+		$rows = $this->db->query($sql);		
+		if ($rows) {
+			while ($row = $this->db->fetch_object($rows)) {
+				
+				$row->full_address = implode(' ', [
+					$row->zip,
+					$row->town,
+					$row->address
+				]);
+				
+				$customers[$row->currency] = $row;				
+			}
+		}
+
+		return $customers;
+	}
+
+	function getAccountRowid($entity)
+	{
+		$sql = "SELECT ba.currency_code, ba.rowid FROM llx_bank_account as ba WHERE entity = {$entity} ORDER BY rowid ASC";
+		//$sql = "SELECT mc.code, mc.rowid FROM llx_multicurrency as mc WHERE entity = {$entity}";
+		$data = $this->db->query($sql);
+		$accounts = [];
+		while ($row = pg_fetch_array($data)) {
+			$accounts[$row['currency_code']] = $row['rowid'];
+			//$accounts[$row['code']] = $row['rowid'];
+		}
+		return $accounts;
+	}
+
+	function getCurrenciesRowid($entity)
+	{
+		$sql = "SELECT mc.rowid, mc.code FROM llx_multicurrency as mc WHERE entity = {$entity} ORDER BY rowid ASC";
+		$data = $this->db->query($sql);
+		$currencies = [];
+		while ($row = pg_fetch_array($data)) {
+			$currencies[$row['code']] = $row['rowid'];
+		}
+		return $currencies;
+	}
+
+	function getPaymentsMode($entity)
+	{
+		$paymentsModeArray = [];
+		$table = (new Paiement($this->db))->table_element;
+		$sql = "SELECT id, code, libelle FROM " . MAIN_DB_PREFIX. 'c_' . $table . " WHERE code IN ('LIQ', 'CB') AND entity = {$entity}";
+		$rows = $this->db->query($sql);
+		if(pg_num_rows($rows) > 0){
+			$result = pg_fetch_all($rows);
+			foreach($result as $record){
+				$paymentsModeArray[] = ['id' => $record['id'], 'label' => $record['libelle'], 'code' => $record['code']];
+			}
+		}
+		return $paymentsModeArray;
+	}
+
+	public function getCompany(): array
+	{
+		global $user;
+
+		$entity = null;
+		$result = [];
+
+		$data = $this->getCompanyData($user->id);
+		//print_r($data);exit;
+		if (empty($data)) {
+			$entityId = (empty($user->entity)) ? 1 : $user->entity;
+			$data = $this->getCompanyData(null, $entityId);
+		}
+
+		if (!empty($data)) {
+			foreach ($data as $row) {
+				$newStr = substr($row['name'], strlen('MAIN_INFO_'));
+				if ($newStr != 'TVAINTRA') {
+					$newStr = substr($newStr, strlen('SOCIETE_'));
+				}
+				$result[$newStr] = $row['value'];
+
+				if (!empty($row['entity']) && is_null($entity)) {
+					$entity = intval($row['entity']);
+				}
+			}
+		}
+
+
+		/*
+																	$sql = "
+																		SELECT c.* 
+																		FROM ".MAIN_DB_PREFIX."settlements_groupusers gu
+																		INNER JOIN ".MAIN_DB_PREFIX."settlements_group AS g ON g.rowid = gu.fk_settlements_group
+																		INNER JOIN ".MAIN_DB_PREFIX."const AS c ON c.entity = g.fk_entity
+																		WHERE gu.fk_user = {$user->id} AND c.name IN (
+																			'MAIN_INFO_SOCIETE_COUNTRY', 
+																			'MAIN_INFO_SOCIETE_NOM', 
+																			'MAIN_INFO_SOCIETE_ADDRESS', 
+																			'MAIN_INFO_SOCIETE_TOWN',
+																			'MAIN_INFO_SOCIETE_ZIP',
+																			'MAIN_INFO_SOCIETE_STATE',
+																			'MAIN_INFO_TVAINTRA'
+																		)";
+																	$entityData = $this->db->query($sql);
+																	while ($row = $this->db->fetch_array($entityData)) {
+																		$newStr = substr($row['name'], strlen('MAIN_INFO_'));
+																		if ($newStr != 'TVAINTRA') {
+																			$newStr = substr($newStr, strlen('SOCIETE_'));
+																		}
+																		$result[$newStr] = $row['value'];
+
+																		if (!empty($row['entity']) && is_null($entity)) {
+																			$entity = intval($row['entity']);
+																		}
+
+																	}
+																	*/
+
+
+		return [
+			'company_data' => $result,
+			'entity' => $entity
+		];
+	}
+
+	public function getCompanyData(int $userId = null, int $entity = null): array
+	{
+		$result = [];
+
+		$where = '';
+		if (!empty($userId)) {
+			$where = 'gu.fk_user = ' . $userId;
+		} else if (!empty($entity)) {
+			$where = 'c.entity = ' . $entity;
+		}
+
+		if (!empty($where)) {
+			$where .= ' AND ';
+		}
+
+		$sql = "
+			SELECT c.* 
+			FROM " . MAIN_DB_PREFIX . "settlements_groupusers gu
+			INNER JOIN " . MAIN_DB_PREFIX . "settlements_group AS g ON g.rowid = gu.fk_settlements_group
+			INNER JOIN " . MAIN_DB_PREFIX . "const AS c ON c.entity = g.fk_entity
+			WHERE {$where} c.name IN (
+				'MAIN_INFO_SOCIETE_COUNTRY', 
+				'MAIN_INFO_SOCIETE_NOM', 
+				'MAIN_INFO_SOCIETE_ADDRESS', 
+				'MAIN_INFO_SOCIETE_TOWN',
+				'MAIN_INFO_SOCIETE_ZIP',
+				'MAIN_INFO_SOCIETE_STATE',
+				'MAIN_INFO_TVAINTRA'
+			)";
+		$entityData = $this->db->query($sql);
+		if ($entityData) {
+			while ($row = $this->db->fetch_array($entityData)) {
+				$result[] = $row;
+			}
+		}
+
+		return $result;
+	}
+
+	public function getGroupUserIdByUserId($user_id)
+	{
+		global $db;
+		$groupUsersObj = new GroupUsers($db);
+		$result = $groupUsersObj->fetchAll('DESC', 'rowid', 1, 0, ["customsql" => "fk_user = {$user_id}"]);
+		if (!empty($result)) {
+			foreach ($result as $record) {
+				return $record->fk_settlements_group;
+			}
+		}
+		return -1;
+	}
+
+	public function isLastStatusLogout($user)
+	{
+		global $db;
+		$userLoginNaplo = new UserLoginNaplo($db);
+		$result = $userLoginNaplo->fetchAll('DESC', 'date_creation', 1, 0, array('user_id' => $user->id));
+		foreach ($result as $lastrecord) {
+			return $lastrecord->login_logout_status == 1 ? $lastrecord->date_creation : '';
+		}
+	}
+
+	public function factureUpdate($sql, $facture_id)
+	{
+		$updated = $this->db->query($sql);
+		if (!$updated) {
+			dol_syslog("Nem sikerult a facture updateje. rowid: " . $facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
+			throw new RestException(404, 'Update failed');
+		}
+	}
+
+	public function checkResult($result, $tableName)
+	{
+		if (!is_array($result) || empty($result)) {
+			dol_syslog("A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
+			throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
+		}
+	}
+
+	public function getTicketsByFacture($facture_id)
+	{
+		$bbticket = new BbTicket($this->db);
+		$bbTicketsByFacture = $bbticket->fetchAll('', '', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
+		if ($bbTicketsByFacture < 1) {
+			throw new RestException(404, 'BBTicket not found');
+		}
+		return $bbTicketsByFacture;
+	}
+
+	public function checkPrintedCopies($facture_id)
+	{
+		$bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
+		$copies = $bbticketinvoiceprinting->fetchAll('ASC', 'rowid', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
+		return (is_array($copies)) ? count($copies) : 0;
+	}
+
+	public function getbookingHistoryId($ref){
+		$sql = "SELECT rowid FROM llx_booking_bookinghistory WHERE invoice_number = '{$ref}' ORDER BY rowid DESC LIMIT 1";
+		$result = $this->db->query($sql);
+		if($this->db->num_rows($result) < 1){
+			return '';
+		}else{
+			while($row = $this->db->fetch_object($result)){
+				return $row->rowid;
+			}
+		}
+	}
+}

+ 2 - 3
custom/bbus/class/api_curl.class.php

@@ -2,15 +2,13 @@
 
 use Luracast\Restler\RestException;
 require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/basicservices.class.php';
-
-//require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_log.class.php';
-
 trait CurlApi
 {
 
 	private function curlInit($route, $postFields = '', $request = 'POST')
 	{
 		global $conf;
+		ApiBbusLog::appLog("{$conf->global->CURL_ROUTE}{$route} => {$postFields}");
 		$curl = curl_init();
 
 		curl_setopt_array($curl, array(
@@ -94,6 +92,7 @@ trait CurlApi
 	{
 		$basicServices = new BasicServices($this->db);
 		$resultBS = $basicServices->fetch($type_id);
+		ApiBbusLog::appLog("{$type_id} => {$basicServices->server_host}");
 		return $basicServices->server_host;
 	}
 }

+ 1 - 0
custom/bbus/class/api_curl.class.php.bak

@@ -71,6 +71,7 @@ trait CurlApi
 	public function curlCreateBBticket($product_id, $datec, $facture_id)
 	{
 		$postFields = '{"product_id":"' . $product_id . '","datec":"' . $datec . '","facture_id":"' . $facture_id . '"}';
+		ApiBbusLog::appLog("{$postFields}");
 		$curl = $this->curlInit('bookingapi/createbbticket', $postFields, 'POST');
 		$response = curl_exec($curl);
 		curl_close($curl);

+ 1 - 0
custom/bbus/class/apiinvoicehelper.class.php

@@ -84,6 +84,7 @@ class ApiInvoiceHelper
 	 */
 	public function addLineToInvoice(Facture $invoice, array $line, $sendId): Facture
 	{
+		ApiBbusLog::appLog("{$sendId} addLineToInvoice: START");
 		$tva_tx_array = explode('.', $line['tva_tx']);
 		$line['tva_tx'] = $line['tva_tx'] . '000 (' . $tva_tx_array[0] . ')';
 		//ApiBbusLog::appLog("{$sendId} - createInvoiceLINE_________START - " . microtime(true));

+ 511 - 0
custom/bbus/class/apiinvoicehelper.class.php.bak

@@ -0,0 +1,511 @@
+<?php
+use Luracast\Restler\RestException;
+
+require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
+
+
+/**
+ * 
+ * 
+ */
+class ApiInvoiceHelper
+{
+	private ApiInvoice $apiInvoice;
+	public $db;
+	/**
+	 * 
+	 */
+	public function __construct()
+	{
+		global $db;
+
+		$this->db = $db;
+	}
+	/**
+	 * Generate invoice with basic data
+	 */
+	public function createInvoice(array $invoice, $sendId): Facture
+	{
+		global $user;
+		ApiBbusLog::appLog("{$sendId} - createInvoice_________START - " . microtime(true));
+		$invoice['multicurrency_tx'] = $invoice['multicurrency_code'] === 'HUF' ? 1.00000000 : $invoice['multicurrency_tx'];
+		$invoice['array_options_sales_group'] = $this->getGroupId();
+		$this->apiInvoice = new ApiInvoice;
+		$this->apiInvoice->loadData($invoice);
+		$this->apiInvoice->prepareData();
+		$this->apiInvoice->validate();
+		ApiBbusLog::appLog("{$sendId} - createInvoice_________END - " . microtime(true));
+		return $this->apiInvoice->create();
+	}
+
+	function getGroupId()
+	{
+		global $user;
+		$sql = "SELECT fk_settlements_group FROM llx_settlements_groupusers WHERE fk_user = {$user->id}";
+		$result = $this->db->query($sql);
+		if ($this->db->num_rows($result) > 0) {
+			while ($row = $this->db->fetch_object($result)) {
+				return $row->fk_settlements_group;
+			}
+		}
+		return null;
+	}
+
+	function increaseParticipant($fk_event)
+	{
+		global $user;
+		$actionComObj = new ActionComm($this->db);
+		$actionComObj->fetch($fk_event);
+		$participants = (int) $actionComObj->array_options['options_participants'];
+		$increasedParticipants = $participants + 1;
+		$actionComObj->array_options['options_participants'] = (int) $increasedParticipants;
+		$actionComObj->label = $fk_event;
+		$actionComObj->update($user);
+	}
+
+	/**
+	 * GEnerate PROV invoice
+	 */
+	public function createInvoicePROV(array $invoice, $sendId): Facture
+	{
+		ApiBbusLog::eventLog("{$sendId} - createInvoice_________START - " . microtime(true));
+		$this->apiInvoice = new ApiInvoice;
+		$invoice['multicurrency_tx'] = $invoice['multicurrency_code'] === 'HUF' ? 1.00000000 : $invoice['multicurrency_tx'];
+		$invoice['array_options_sales_group'] = $this->getGroupId();
+		//print_r($invoice);exit;
+		$this->apiInvoice->loadData($invoice);
+		$this->apiInvoice->prepareData();
+		$this->apiInvoice->validate();
+		return $this->apiInvoice->create();
+	}
+	/**
+	 * Add product to invoice
+	 */
+	public function addLineToInvoice(Facture $invoice, array $line, $sendId): Facture
+	{
+		$tva_tx_array = explode('.', $line['tva_tx']);
+		$line['tva_tx'] = $line['tva_tx'] . '000 (' . $tva_tx_array[0] . ')';
+		//ApiBbusLog::appLog("{$sendId} - createInvoiceLINE_________START - " . microtime(true));
+		$apiInvoiceLine = new ApiInvoiceLine;
+		$apiInvoiceLine->setInvoice($invoice);
+		$apiInvoiceLine->loadData($line);
+		$apiInvoiceLine->prepareData();
+		$invoice = $apiInvoiceLine->create();
+
+		return $invoice;
+	}
+
+	function getProductLines($product_id)
+	{
+		$productObj = new Product($this->db);
+		$result = $productObj->fetch($product_id);
+		$productObj->fk_product = $product_id;
+		$productObj->subprice = $productObj->price_ttc;
+		$productObj->qty = 1; 
+		$lines[] = (array) $productObj;
+		return $lines;
+	}
+
+	function getProductLinesWithoutDiscount($product_id)
+	{
+		ApiBbusLog::appLog("getProductLinesWithoutDiscount: {$product_id}");
+
+		$productObj = new Product($this->db);
+		$result = $productObj->fetch($product_id);
+		$productObj->fk_product = $product_id;
+		$productObj->subprice = $productObj->price_ttc;
+		$productObj->qty = 1;
+		$productObj->array_options['options_discount_hours'] = null;
+		$productObj->array_options['options_discount_percent'] = null;
+		$lines[] = (array) $productObj;
+		return $lines;
+	}
+
+	/**
+	 * Validate invoice
+	 */
+	public function validateInvoice(Facture $invoice, $sendId): Facture
+	{
+		ApiBbusLog::appLog("{$sendId} - validateInvoice_________START - " . microtime(true));
+		return $this->apiInvoice->validateInvoice($invoice, 1);
+	}
+
+	/**
+	 * Validate invoice
+	 */
+	public function validateInvoiceFromPROV(Facture $invoice, $sendId, $facture_id): Facture
+	{
+		$this->apiInvoice = new ApiInvoice;
+		ApiBbusLog::eventLog("{$sendId} - validateInvoice_________START - " . microtime(true));
+		return $this->apiInvoice->validateInvoice($invoice, 1);
+	}
+
+	/**
+	 * Set payment
+	 * 
+	 * @return int Payment ID
+	 */
+	public function setPaymentFromPROV(Facture $invoice, array $payment, string $sendId): int
+	{
+		$this->apiInvoice = new ApiInvoice;
+		ApiBbusLog::eventLog("{$sendId} - setPayment_________START - " . microtime(true));
+		return $this->apiInvoice->setPayment($invoice, $payment, $sendId);
+	}
+
+	/**
+	 * Set payment
+	 * 
+	 * @return int Payment ID
+	 */
+	public function setPayment(Facture $invoice, array $payment, string $sendId): int
+	{
+		ApiBbusLog::appLog("{$sendId} - setPayment_________START - " . microtime(true));
+		return $this->apiInvoice->setPayment($invoice, $payment, $sendId);
+	}
+	/**
+	 * Save card payment log to invoice
+	 */
+	public function saveCardPaymentLog(Facture $invoice, string $cardPaymentLog, $sendId): Facture
+	{
+		//ApiBbusLog::appLog("{$sendId} - saveCardPaymentLog_________START - " . microtime(true));
+		$invoice->array_options['options_payment_log'] = $cardPaymentLog;
+		$invoice->updateExtraField('payment_log');
+
+		$json = json_decode($cardPaymentLog, true);
+		if (!empty($json['authorization_number'])) {
+			$sql = "
+				UPDATE " . MAIN_DB_PREFIX . "paiement 
+				SET num_paiement='" . $json['authorization_number'] . "' 
+				WHERE rowid=(
+					SELECT fk_paiement 
+					FROM " . MAIN_DB_PREFIX . "paiement_facture 
+					WHERE fk_facture={$invoice->id}
+				)
+			";
+			$this->db->query($sql);
+		}
+
+		return $invoice;
+	}
+	/**
+	 * Load product
+	 */
+	public function loadProductToResult(array $line): array
+	{
+		$result = [];
+
+		$product = new Product($this->db);
+		if ($product->fetch($line['fk_product']) > 0) {
+			$result = [
+				'id' => $product->id,
+				'ref' => $product->ref,
+				'label' => $product->label,
+				'description' => $product->description,
+				'vat' => $product->tva_tx,
+				'discount_period' => (empty($line['array_options']['discount_period'])) ? '' : $line['array_options']['discount_period'],
+				'discount_value' => (empty($line['array_options']['discount_value'])) ? '' : $line['array_options']['discount_value'],
+				'orig_price' => $product->price_ttc,
+				'price' => $product->price_ttc
+			];
+		}
+
+		return $result;
+	}
+}
+
+/**
+ * 
+ * 
+ */
+interface ApiInvoiceData
+{
+	public function loadData(array $data): void;
+	public function prepareData(): void;
+	public function validate(): void;
+	public function create(); // missing return type because of the different result objects
+}
+/**
+ * 
+ * 
+ */
+class ApiInvoiceLine implements ApiInvoiceData
+{
+	public $data;
+	public $invoice;
+	/**
+	 * 
+	 */
+	public function loadData(array $data): void
+	{
+		$this->data = (object) $data;
+	}
+	/**
+	 * 
+	 */
+	public function setInvoice(Facture $invoice): void
+	{
+		$this->invoice = $invoice;
+	}
+	/**
+	 * 
+	 */
+	public function prepareData(): void
+	{
+		$this->data->desc = sanitizeVal($this->data->desc, 'restricthtml');
+		$this->data->label = sanitizeVal($this->data->label);
+
+		if (($this->data->product_type != 9 && empty($this->data->fk_parent_line)) || $this->data->product_type == 9) {
+			$this->data->fk_parent_line = 0;
+		}
+	}
+	/**
+	 * 
+	 */
+	public function validate(): void
+	{
+		//
+	}
+	/**
+	 * 
+	 */
+	public function create(): Facture
+	{
+		$marginInfos = getMarginInfos($this->data->subprice, $this->data->remise_percent, $this->data->tva_tx, $this->data->localtax1_tx, $this->data->localtax2_tx, $this->data->fk_fournprice, $this->data->pa_ht);
+		$pa_ht = $marginInfos[0];
+
+		$updateRes = $this->invoice->addline(
+			$this->data->desc,
+			$this->data->subprice,
+			$this->data->qty,
+			$this->data->tva_tx,
+			$this->data->localtax1_tx,
+			$this->data->localtax2_tx,
+			$this->data->fk_product,
+			$this->data->remise_percent,
+			$this->data->date_start,
+			$this->data->date_end,
+			$this->data->fk_code_ventilation,
+			$this->data->info_bits,
+			$this->data->fk_remise_except,
+			$this->data->price_base_type ? $this->data->price_base_type : 'HT',
+			$this->data->subprice,
+			$this->data->product_type,
+			$this->data->rang,
+			$this->data->special_code,
+			$this->data->origin,
+			$this->data->origin_id,
+			$this->data->fk_parent_line,
+			empty($this->data->fk_fournprice) ? null : $this->data->fk_fournprice,
+			$pa_ht,
+			$this->data->label,
+			$this->data->array_options,
+			$this->data->situation_percent,
+			$this->data->fk_prev_id,
+			$this->data->fk_unit,
+			0,
+			$this->data->ref_ext
+		);
+
+		if ($updateRes < 0) {
+			throw new RestException(400, 'Unable to insert the new line. Check your inputs. ' . $this->invoice->error);
+		}
+
+		return $this->invoice;
+	}
+}
+/**
+ * 
+ * 
+ */
+class ApiInvoice implements ApiInvoiceData
+{
+	const SOCID = 1;
+
+	public $data;
+	public $invoice;
+	/**
+	 * 
+	 */
+	public function loadData(array $data): void
+	{
+		$this->invoice = null;
+		$this->data = $data;
+	}
+	/**
+	 * 
+	 */
+	public function prepareData(): void
+	{
+		global $user;
+
+		$this->data['socid'] = self::SOCID;
+		$this->data['entity'] = $user->entity;
+	}
+	/**
+	 * 
+	 */
+	public function validate(): void
+	{
+		$fields = [
+			'socid',
+			'entity'
+		];
+
+		foreach ($fields as $field) {
+			if (!isset($this->data[$field])) {
+				throw new RestException(400, "Invoice {$field} field missing");
+			}
+		}
+	}
+	/**
+	 * 
+	 */
+	public function create(): Facture
+	{
+		global $db;
+
+		$this->invoice = new Facture($db);
+
+		foreach ($this->data as $field => $value) {
+			if (preg_match('/^array_options/', $field)) {
+				$f = str_replace('array_options_', '', $field);
+				$this->invoice->array_options[$f] = $value;
+				continue;
+			}
+			$this->invoice->$field = $value;
+		}
+
+		if (!array_key_exists('date', $this->data)) {
+			$this->invoice->date = dol_now();
+		}
+
+		$this->invoice->type = 7;
+
+		if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($this->data['date_lim_reglement']) ? 0 : $this->data['date_lim_reglement'])) < 0) {
+			throw new RestException(500, 'Error creating invoice', array_merge([$this->invoice->error], $this->invoice->errors));
+		}
+
+		return $this->invoice;
+	}
+
+	/**
+	 * 
+	 */
+	public function validateInvoice(Facture $invoice, int $notrigger): Facture
+	{
+		$result = $invoice->validate(DolibarrApiAccess::$user, '', 0, $notrigger);
+		if ($result == 0) {
+			throw new RestException(304, 'Error nothing done. May be object is already validated');
+		}
+		if ($result < 0) {
+			throw new RestException(500, 'Error when validating Invoice: ' . $invoice->error);
+		}
+
+		return $invoice;
+	}
+
+	/**
+	 * 
+	 */
+	public function setPayment(Facture $invoice, array $data, string $sendId): int
+	{
+		ApiBbusLog::appLog("ApiinvoiceHelper: setPayment function");
+
+		global $db;
+
+		if (isModEnabled('banque')) {
+			if (empty($data['accountid'])) {
+				ApiBbusLog::appLog("ApiinvoiceHelper: setPayment accountid error");
+				throw new RestException(400, 'Account ID is mandatory');
+			}
+		}
+
+		if (empty($data['paymentid'])) {
+			ApiBbusLog::appLog("ApiinvoiceHelper: setPayment paymentid error");
+			throw new RestException(400, 'Payment ID or Payment Code is mandatory');
+		}
+
+		// Calculate amount to pay
+		$totalpaid = $invoice->getSommePaiement();
+		$totalcreditnotes = $invoice->getSumCreditNotesUsed();
+		$totaldeposits = $invoice->getSumDepositsUsed();
+		$resteapayer = price2num($invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
+
+		$db->begin();
+
+		$amounts = [];
+		$multicurrency_amounts = [];
+		// Clean parameters amount if payment is for a credit note
+		if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
+			$resteapayer = price2num($resteapayer, 'MT');
+			$amounts[$invoice->id] = -$resteapayer;
+			// Multicurrency
+			$newvalue = price2num($invoice->multicurrency_total_ttc, 'MT');
+			$multicurrency_amounts[$invoice->id] = -$newvalue;
+		} else {
+			$resteapayer = price2num($resteapayer, 'MT');
+			$amounts[$invoice->id] = $resteapayer;
+			// Multicurrency
+			$newvalue = price2num($invoice->multicurrency_total_ttc, 'MT');
+			$multicurrency_amounts[$invoice->id] = $newvalue;
+		}
+
+		// Creation of payment line
+		$paymentobj = new Paiement($db);
+		$paymentobj->datepaye = $data['datepaye'];
+		$paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
+		$paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
+		$paymentobj->paiementid = $data['paymentid'];
+		$paymentobj->paiementcode = dol_getIdFromCode($db, $data['paymentid'], 'c_paiement', 'id', 'code', 1);
+		$paymentobj->num_payment = $data['num_payment'];
+		$paymentobj->note_private = (is_array($data['comment'])) ? json_encode($data['comment']) : $data['comment'];
+
+		$paymentId = $paymentobj->create(DolibarrApiAccess::$user, ($data['closepaidinvoices'] == 'yes' ? 1 : 0)); // This include closing invoices
+		ApiBbusLog::appLog("paymentId created");
+
+
+		if ($paymentId < 0) {
+			$db->rollback();
+			ApiBbusLog::appLog("{$sendId} Payment error : " . $paymentobj->error);
+			throw new RestException(400, 'Payment error : ' . $paymentobj->error);
+		}
+
+		if (isModEnabled('banque')) {
+			$label = '(CustomerInvoicePayment)';
+
+			$chqemetteur = '';
+			$chqbank = '';
+
+			if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
+				ApiBbusLog::appLog("{$sendId} Emetteur is mandatory when payment code is " . $paymentobj->paiementcode);
+				throw new RestException(400, 'Emetteur is mandatory when payment code is ' . $paymentobj->paiementcode);
+			}
+			if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
+				$label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
+			}
+
+			$result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $data['accountid'], $chqemetteur, $chqbank);
+			if ($result < 0) {
+				$db->rollback();
+				ApiBbusLog::appLog("{$sendId} Add payment to bank error : " . $paymentobj->error);
+				throw new RestException(400, 'Add payment to bank error : ' . $paymentobj->error);
+			}
+		}
+
+		# 
+		# set Facture -> payment_transaction_id
+		#
+
+		if (!empty($data['comment'])) {
+			$commentJSON = json_decode($data['comment']);
+			$invoice->array_options['options_payment_transaction_id'] = $commentJSON->card_transaction_id;
+			$invoice->updateExtraField('payment_transaction_id');
+		}
+
+		$db->commit();
+		ApiBbusLog::appLog("{$sendId} PAYMENT CREATED: {$paymentId}");
+
+		return $paymentId;
+	}
+}