Sfoglia il codice sorgente

Daily closing sum counting and printed factures problems fixed AND ROLLERRENT FIRST COMMIT

szollosil 1 anno fa
parent
commit
02341da236
29 ha cambiato i file con 6833 aggiunte e 62 eliminazioni
  1. 6 0
      custom/bbus/class/api_bbus.class.php
  2. 88 31
      custom/bbus/class/api_bbus.class.php.bak
  3. 5 0
      custom/bbus/class/api_bbus_log.class.php
  4. 99 15
      custom/bbus/class/commissionhandler.class.php
  5. 335 0
      custom/bbus/class/commissionhandler.class.php.bak
  6. 216 0
      custom/bbus/class/roller_handling.class.php
  7. 163 0
      custom/bbus/class/roller_handling_helper.class.php
  8. 17 0
      custom/bbus/class/ticket_checker.class.php
  9. 118 1
      custom/booking/class/api_booking.class.php
  10. 147 0
      custom/rollerstorage/admin/rollerrenthistory_extrafields.php
  11. 1118 0
      custom/rollerstorage/class/rollerrenthistory.class.php
  12. 1118 0
      custom/rollerstorage/class/rollerrenthistory.class.php.back
  13. 110 0
      custom/rollerstorage/lib/rollerstorage_rollerrenthistory.lib.php
  14. 321 0
      custom/rollerstorage/rollerrenthistory_agenda.php
  15. 621 0
      custom/rollerstorage/rollerrenthistory_card.php
  16. 228 0
      custom/rollerstorage/rollerrenthistory_contact.php
  17. 261 0
      custom/rollerstorage/rollerrenthistory_document.php
  18. 850 0
      custom/rollerstorage/rollerrenthistory_list.php
  19. 221 0
      custom/rollerstorage/rollerrenthistory_note.php
  20. 28 0
      custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory.key.sql
  21. 34 0
      custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory.sql
  22. 34 0
      custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory.sql.back
  23. 19 0
      custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory_extrafields.key.sql
  24. 23 0
      custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory_extrafields.sql
  25. 50 13
      custom/settlements/class/daily_closing.class.php
  26. 343 0
      custom/settlements/class/daily_closing.class.php.bak
  27. 1 1
      custom/settlements/core/tpl/dailyclosing_open.tpl.php
  28. 255 0
      custom/settlements/core/tpl/dailyclosing_open.tpl.php.bak
  29. 4 1
      includes/restler/framework/Luracast/Restler/RestException.php

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

@@ -62,6 +62,7 @@ require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbapilock.class.php';
 require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/exchangerateupdater.class.php';
 require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketvalidationcoords.class.php';
 require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/roller_handling.class.php';
 
 /**
  * API class for products
@@ -72,6 +73,7 @@ require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
 class BBus extends DolibarrApi
 {
 	use CurlApi;
+	use RollerHandling;
 
 	private $code;
 	private $printingTime;
@@ -184,6 +186,7 @@ class BBus extends DolibarrApi
 	public function getinfos($code)
 	{
 		global $user;
+		$ticketChecker = new TicketChecker();
 		ApiBbusLog::getinfosLog('=== NEW TICKETINFOS ===');
 		ApiBbusLog::getinfosLog("User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
 		ApiBbusLog::getinfosLog("DOLAPIKEY: {$user->api_key}");
@@ -253,9 +256,12 @@ class BBus extends DolibarrApi
 			$sub = [];
 			foreach ($row as $key => $value) {
 				$sub[$key] = $value;
+				//print $key . ' - ' . $value . "\r\n";
 			}
+			$sub['ticket_type'] = $ticketChecker->getTicketTypeByProductId($row['ticket_id']);
 			$json[] = $sub;
 		}
+		ApiBbusLog::getinfosLog(json_encode($json));
 		ApiBbusLog::getinfosLog('Status: OK!');
 		ApiBbusLog::getinfosLog('=====================');
 		return $json;

+ 88 - 31
custom/bbus/class/api_bbus.class.php.bak

@@ -62,6 +62,7 @@ require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbapilock.class.php';
 require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/exchangerateupdater.class.php';
 require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketvalidationcoords.class.php';
 require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/roller_handling.class.php';
 
 /**
  * API class for products
@@ -72,6 +73,7 @@ require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
 class BBus extends DolibarrApi
 {
 	use CurlApi;
+	use RollerHandling;
 
 	private $code;
 	private $printingTime;
@@ -184,6 +186,7 @@ class BBus extends DolibarrApi
 	public function getinfos($code)
 	{
 		global $user;
+		$ticketChecker = new TicketChecker();
 		ApiBbusLog::getinfosLog('=== NEW TICKETINFOS ===');
 		ApiBbusLog::getinfosLog("User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
 		ApiBbusLog::getinfosLog("DOLAPIKEY: {$user->api_key}");
@@ -253,9 +256,12 @@ class BBus extends DolibarrApi
 			$sub = [];
 			foreach ($row as $key => $value) {
 				$sub[$key] = $value;
+				//print $key . ' - ' . $value . "\r\n";
 			}
+			$sub['ticket_type'] = $ticketChecker->getTicketTypeByProductId($row['ticket_id']);
 			$json[] = $sub;
 		}
+		ApiBbusLog::getinfosLog(json_encode($json));
 		ApiBbusLog::getinfosLog('Status: OK!');
 		ApiBbusLog::getinfosLog('=====================');
 		return $json;
@@ -320,7 +326,7 @@ class BBus extends DolibarrApi
 		$selectedTicket = $ticketChecker->getDataOfTheSelectedTicket();
 
 		$ticketChecker->setBbTicketRowId($selectedTicket->id);
-
+//----
 		$ticketChecker->checkExceptionHandlers($selectedTicket, 'ticketvalidationByPhone', $logId);
 
 		$ticketChecker->setMergedTickets($selectedTicket, 'ticketvalidationByPhone', $logId);
@@ -394,6 +400,40 @@ class BBus extends DolibarrApi
 		return 'OK';
 	}
 
+	/**
+	 * curlGetFilsArray
+	 *
+	 * Return an array with success information.
+	 *
+	 * @param  string $ref
+	 * 
+	 * @return array|mixed Data without useless information
+	 *
+	 * @url POST curlGetFilsArray
+	 *
+	 * @throws RestException 401
+	 * @throws RestException 403
+	 * @throws RestException 404
+	 */
+	public function curlGetFilsArray($ref)
+	{
+		$fils = [];
+		$sqlFAC = "SELECT rowid FROM llx_facture WHERE ref = '{$ref}'";
+		$resultFAC = $this->db->query($sqlFAC);
+		if ($this->db->num_rows($resultFAC)) {
+			while ($facture = $this->db->fetch_object($resultFAC)) {
+				$sql = "SELECT fdet.fk_product FROM llx_facture AS f
+			INNER JOIN llx_facturedet as fdet ON fdet.fk_facture = f.rowid
+			WHERE f.rowid = {$facture->rowid}";
+				$result = $this->db->query($sql);
+				while ($sqlDataResult = pg_fetch_assoc($result)) {
+					$fils[] = $sqlDataResult['fk_product'];
+				}
+			}
+		}
+		return $fils;
+	}
+
 	/**
 	 * Post invoice ref and creation date for data recording
 	 *
@@ -485,6 +525,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);
 			}
@@ -586,40 +627,54 @@ class BBus extends DolibarrApi
 	public function checkPermission()
 	{
 		global $user, $db;
-		$permissionArray = [];
-		$groupUsersObj = new GroupUsers($db);
-		$result = $groupUsersObj->fetchAll('desc', 'rowid', 1, 0, ["customsql" => "fk_user = {$user->id}"]);
-		if ($result == -1 || empty($result)) {
-			return $permissionArray;
-		}
-		dol_include_once('/eventwizard/class/eventdetails.class.php');
-		$sqlBasicService = "SELECT pe.basic_service FROM llx_product as p
+		ApiBbusLog::appLog("checkPermission_START");
+		$memcached = new Memcached();
+		$memcached->addServer("szollosil-excelia-urbanms-memcached", 11211);
+		$key = '"' . $user->api_key . '"';
+
+		$cacheValue = $memcached->get($key);
+		if ($cacheValue === false) {
+			$permissionArray = [];
+			$groupUsersObj = new GroupUsers($db);
+			$result = $groupUsersObj->fetchAll('desc', 'rowid', 1, 0, ["customsql" => "fk_user = {$user->id}"]);
+			if ($result == -1 || empty($result)) {
+				return $permissionArray;
+			}
+			dol_include_once('/eventwizard/class/eventdetails.class.php');
+			$sqlBasicService = "SELECT pe.basic_service FROM llx_product as p
 			INNER JOIN llx_product_extrafields as pe ON pe.fk_object = p.rowid
 			GROUP BY pe.basic_service";
-		$resultBasicServices = $db->query($sqlBasicService);
-		if ($db->num_rows($resultBasicServices) > 0) {
-			while ($row = $db->fetch_object($resultBasicServices)) {
-				$basicServices[] = $row->basic_service;
+			$resultBasicServices = $db->query($sqlBasicService);
+			if ($db->num_rows($resultBasicServices) > 0) {
+				while ($row = $db->fetch_object($resultBasicServices)) {
+					$basicServices[] = $row->basic_service;
+				}
 			}
-		}
-		$sqlBasicServicesTable = "SELECT basic_service_id, ref, is_event FROM llx_bbus_basicServices ORDER BY basic_service_id ASC";
-		$resultBasicServicesObj = $db->query($sqlBasicServicesTable);
-		if ($db->num_rows($resultBasicServicesObj) > 0) {
-			while ($bsrow = $db->fetch_object($resultBasicServicesObj)) {
-				foreach ($basicServices as $item) {
-					if ($bsrow->basic_service_id == $item && $item != 2) {
-						if ($bsrow->is_event == '1' && $this->isAvailablePlaces($item)) {
-							$permissionArray[$item] = $bsrow->ref;
-						} elseif ($bsrow->is_event != '1') {
-							$permissionArray[$item] = $bsrow->ref;
+			$sqlBasicServicesTable = "SELECT basic_service_id, ref, is_event FROM llx_bbus_basicServices ORDER BY basic_service_id ASC";
+			$resultBasicServicesObj = $db->query($sqlBasicServicesTable);
+			if ($db->num_rows($resultBasicServicesObj) > 0) {
+				while ($bsrow = $db->fetch_object($resultBasicServicesObj)) {
+					foreach ($basicServices as $item) {
+						if ($bsrow->basic_service_id == $item && $item != 2) {
+							if ($bsrow->is_event == '1' && $this->isAvailablePlaces($item)) {
+								$permissionArray[$item] = $bsrow->ref;
+							} elseif ($bsrow->is_event != '1') {
+								$permissionArray[$item] = $bsrow->ref;
+							}
 						}
 					}
 				}
 			}
+			$cacheValue = json_encode($permissionArray);
+			$memcached->set($key, $cacheValue, 600); // 5 percig tároljuk
+			ApiBbusLog::appLog("Adat betöltve a adatbázis-ból: " . $cacheValue);
+		} else {
+			ApiBbusLog::appLog("Adat betöltve a cache-ből: " . $cacheValue);
 		}
 		//$curlPermissionArray = $this->curlRunner('rollerstorageapi/checkPermission', '');
 		//$permissionArray = $permissionArray + (array)json_decode($curlPermissionArray);
-		return $permissionArray;
+		//return $permissionArray;
+		return json_decode($cacheValue, true);
 	}
 
 	private function isAvailablePlaces($item)
@@ -680,12 +735,12 @@ class BBus extends DolibarrApi
 			AND ep.fk_product = {$product_id}
 			AND ac.datep > '{$date_from}' 
 			ORDER BY ac.datep ASC";
-		ApiBbusLog::appLog($sql);
+		//ApiBbusLog::appLog($sql);
 
-			$result = $this->db->query($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");
@@ -1807,7 +1862,7 @@ class BBus extends DolibarrApi
 	 * 
 	 * @url POST /invoice
 	 */
-	public function invoice(array $invoice, array $lines, array $payment, string $cardPaymentLog = '', string $sendId = '', $server_host_curl = false)
+	public function invoice(array $invoice, array $lines, array $payment, string $cardPaymentLog = '', string $sendId = '', $server_host_curl = false, $company_invoice = '')
 	{
 		global $user;
 		$lockLabel = 'CREATE_INVOICE';
@@ -1843,7 +1898,9 @@ class BBus extends DolibarrApi
 		/**
 		 * handle invoice basic data
 		 */
-		$invoiceObj = $apiInvoiceHelper->createInvoice($invoice, $sendId);
+		$invoiceObj = $apiInvoiceHelper->createInvoice($invoice, $sendId, $company_invoice);
+		ApiBbusLog::appLog("{$sendId} Invoice created");
+
 		/**
 		 * handle invoice line(s)
 		 */
@@ -1958,7 +2015,7 @@ class BBus extends DolibarrApi
 		pr.default_vat_code, 
 		f.multicurrency_total_ttc AS bundle_ttc, 
 		(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,
-		(SELECT date_start FROM llx_eventwizard_eventhistory AS evev WHERE evev.fk_facture = f.rowid) AS date_start
+		(SELECT date_start FROM llx_booking_bookinghistory AS bh WHERE bh.fk_facture = f.rowid) AS date_start
 				FROM llx_facture AS f
 				INNER JOIN llx_facture_extrafields AS fe ON fe.fk_object = f.rowid
 				INNER JOIN llx_c_paiement AS pa ON pa.id = f.fk_mode_reglement

+ 5 - 0
custom/bbus/class/api_bbus_log.class.php

@@ -32,4 +32,9 @@ class ApiBbusLog
 	{
 		dol_syslog($message, LOG_INFO, 0, '_LunaTours');
 	}
+
+	public static function ScooterRentLog(string $message): void
+	{
+		dol_syslog($message, LOG_INFO, 0, '_ScooterRent');
+	}
 }

+ 99 - 15
custom/bbus/class/commissionhandler.class.php

@@ -1,9 +1,13 @@
 <?php
 
 require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_log.class.php';
 
 class CommissionHandler
 {
+    use CurlApi;
+
     public function __construct()
     {
         global $db, $user;
@@ -122,59 +126,139 @@ class CommissionHandler
 
     function getCommisonByUserId($user_id, $currency, $from, $to, $allComissionInvoicesOfUserInTheGroupFromUserInvoice)
     {
+        $to = date('Y-m-d H:i:s', dol_now());
+        $crossShoppingFacturesString = "'MrNSTR2409-001003'";
+
+        $params = ["from" => $from, "to" => $to, "factures" => $crossShoppingFacturesString];
+        $postFields = json_encode($params);
+        $crossShoppingFactures = $this->curlRunner('bookingapi/getPrintedFacturesRefs', $postFields, 'POST', true);
         global $db;
         $commissions = 0;
-        $sql = "SELECT f.rowid, f.total_ttc, fe.commission
+        $sql = "SELECT f.rowid, f.total_ttc, fe.commission, f.ref, bbt.rowid as bbt_rowid, bbtip.rowid as bbtip_rowid
         FROM llx_facture as f 
         INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid 
-        WHERE EXISTS (SELECT * FROM llx_bbus_bbticketinvoiceprinting as bbip WHERE bbip.fk_facture = f.rowid ORDER BY bbip.rowid DESC LIMIT 1) AND";
+        LEFT JOIN llx_bbus_bbticket as bbt ON bbt.fk_facture = f.rowid
+        LEFT JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.invoice_number = f.ref WHERE ";
+        if ($crossShoppingFactures != '') {
+            $sql .= " f.ref not in ({$crossShoppingFactures}) AND";
+        }
         if (!empty($allComissionInvoicesOfUserInTheGroupFromUserInvoice)) {
             $sql .= " f.rowid NOT IN({$allComissionInvoicesOfUserInTheGroupFromUserInvoice}) AND";
         }
         $sql .= "
         fk_user_closing = {$user_id} 
         AND multicurrency_code = '{$currency}' 
-        --AND fe.marked_for_storno IS NULL 
         AND fe.commission_deduction is NULL
         AND date_closing BETWEEN '{$from}' AND '{$to}'";
         //print $sql;
         $result = $db->query($sql);
         if ($db->num_rows($result) != 0) {
             while ($row = pg_fetch_assoc($result)) {
+                if (is_null($row['bbt_rowid']) || !is_null($row['bbtip_rowid'])) {
                 $commissions += $this->getAmountOfCommission($row);
             }
         }
+        }
+        if ($crossShoppingFactures != '') {
+            $sqlCS = "SELECT f.rowid, f.total_ttc, fe.commission, f.ref
+        FROM llx_facture as f 
+        INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid WHERE f.ref in ({$crossShoppingFactures}) AND";
+            if (!empty($allComissionInvoicesOfUserInTheGroupFromUserInvoice)) {
+                $sqlCS .= " f.rowid NOT IN({$allComissionInvoicesOfUserInTheGroupFromUserInvoice}) AND";
+            }
+            $sqlCS .= "
+        fk_user_closing = {$user_id} 
+        AND multicurrency_code = '{$currency}' 
+        AND fe.commission_deduction is NULL
+        AND date_closing BETWEEN '{$from}' AND '{$to}'";
+            //print $sqlCS;
+            $resultCS = $db->query($sqlCS);
+            if ($db->num_rows($resultCS) != 0) {
+                while ($rowCS = pg_fetch_assoc($resultCS)) {
+                    $commissions += $this->getAmountOfCommission($rowCS);
+                }
+            }
+        }
         return $commissions;
     }
 
     function getCashCommisonByUserId($user_id, $currency, $from, $to, $allComissionInvoicesOfUserInTheGroupFromUserInvoice, $entity, $code)
     {
-        $commissions = 0;
-        //$from = date('Y-m-d H:i:s', strtotime("-1 day", strtotime($from)));
-        //print $from;exit;
+
         $to = date('Y-m-d H:i:s', dol_now());
-        $sql = "SELECT f.rowid, f.multicurrency_total_ttc, fe.commission
+        $crossShoppingFacturesString = "";
+        $sqlForCrossShoppingFactures = "SELECT f.ref
         FROM llx_facture as f 
         INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid 
-        WHERE EXISTS (SELECT * FROM llx_bbus_bbticketinvoiceprinting as bbip WHERE bbip.fk_facture = f.rowid ORDER BY bbip.rowid DESC LIMIT 1) AND";
+        LEFT JOIN llx_bbus_bbticket as bbt ON bbt.fk_facture = f.rowid
+        LEFT JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.invoice_number = f.ref WHERE";
         if (!empty($allComissionInvoicesOfUserInTheGroupFromUserInvoice)) {
-            $sql .= " f.rowid NOT IN({$allComissionInvoicesOfUserInTheGroupFromUserInvoice}) AND";
+            $sqlForCrossShoppingFactures .= " f.rowid NOT IN({$allComissionInvoicesOfUserInTheGroupFromUserInvoice}) AND";
         }
-        $sql .= " (SELECT a.rowid FROM llx_facture as a WHERE a.fk_facture_source = f.rowid AND fk_user_closing = {$user_id}) Is NULL AND
+        $sqlForCrossShoppingFactures .= " (SELECT a.rowid FROM llx_facture as a WHERE a.fk_facture_source = f.rowid AND fk_user_closing = {$user_id}) Is NULL AND
         fk_user_closing = {$user_id} 
         AND fk_mode_reglement = (SELECT id FROM public.llx_c_paiement WHERE entity = {$entity} AND code = '{$code}')
         AND multicurrency_code = '{$currency}' 
-        --AND fe.marked_for_storno is NuLL 
-        AND fe.commission_deduction is NULL
         AND date_closing BETWEEN '{$from}' AND '{$to}'";
-        //print $sql . '<br>';
+        $resultForCrossShoppingFactures = $this->db->query($sqlForCrossShoppingFactures);
+        if ($this->db->num_rows($resultForCrossShoppingFactures) > 0) {
+            while ($factureCSRow = pg_fetch_assoc($resultForCrossShoppingFactures)) {
+                if ($crossShoppingFacturesString == "") {
+                    $crossShoppingFacturesString .= "'" . $factureCSRow['ref'] . "'";
+                } else {
+                    $crossShoppingFacturesString .= ",'" . $factureCSRow['ref'] . "'";
+                }
+            }
+        }
+
+        $params = ["from" => $from, "to" => $to, "factures" => $crossShoppingFacturesString];
+        $postFields = json_encode($params);
+        $crossShoppingFactures = $this->curlRunner('bookingapi/getPrintedFacturesRefs', $postFields, 'POST', true);
+        $sql = $this->createSQL($from, $to, $currency, $code, $entity, $user_id, $allComissionInvoicesOfUserInTheGroupFromUserInvoice, $crossShoppingFactures);
+        $commissions = $this->getMulticurrencyTotalTTC($sql);
+        $sqlCroSho = $this->createSQL($from, $to, $currency, $code, $entity, $user_id, $allComissionInvoicesOfUserInTheGroupFromUserInvoice, $crossShoppingFactures, true);
+        $commissionsCroSho = $this->getMulticurrencyTotalTTC($sqlCroSho);
+        return $commissions + $commissionsCroSho;
+    }
+
+    function getMulticurrencyTotalTTC($sql)
+    {
+        $commissions = 0;
         $result = $this->db->query($sql);
-        while ($row = pg_fetch_assoc($result)) {
-            $commissions += $row['multicurrency_total_ttc'];
+        while ($factureRow = pg_fetch_assoc($result)) {
+            //if (is_null($factureRow['bbt_rowid']) || !is_null($factureRow['bbtip_rowid'])) {
+            $commissions += $factureRow['multicurrency_total_ttc'];
+            //}
         }
         return $commissions;
     }
 
+    function createSQL($from, $to, $currency, $code, $entity, $user_id, $allComissionInvoicesOfUserInTheGroupFromUserInvoice, $crossShoppingFactures, $crossShopping = false)
+    {
+        $sql = "SELECT f.rowid, f.multicurrency_total_ttc, fe.commission, f.ref, bbt.rowid as bbt_rowid, bbtip.rowid as bbtip_rowid
+        FROM llx_facture as f 
+        INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid
+        LEFT JOIN llx_bbus_bbticket as bbt ON bbt.fk_facture = f.rowid
+        LEFT JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.invoice_number = f.ref WHERE";
+        if ($crossShopping && $crossShoppingFactures != "") {
+            $sql .= " f.ref in ({$crossShoppingFactures}) AND";
+        } else {
+            if ($crossShoppingFactures != "") {
+                $sql .= " f.ref not in ({$crossShoppingFactures}) AND";
+            }
+        }
+        if (!empty($allComissionInvoicesOfUserInTheGroupFromUserInvoice)) {
+            $sql .= " f.rowid NOT IN({$allComissionInvoicesOfUserInTheGroupFromUserInvoice}) AND";
+        }
+        $sql .= " (SELECT a.rowid FROM llx_facture as a WHERE a.fk_facture_source = f.rowid AND fk_user_closing = {$user_id}) Is NULL AND
+        fk_user_closing = {$user_id} 
+        AND fk_mode_reglement = (SELECT id FROM public.llx_c_paiement WHERE entity = {$entity} AND code = '{$code}')
+        AND multicurrency_code = '{$currency}' 
+        AND date_closing BETWEEN '{$from}' AND '{$to}'";
+
+        return $sql;
+    }
+
     function getCashCommisonByUserIdHistory($user_id, $currency, $allComissionInvoicesOfUserInTheGroupFromUserInvoice, $id, $entity, $code)
     {
         global $db;

+ 335 - 0
custom/bbus/class/commissionhandler.class.php.bak

@@ -0,0 +1,335 @@
+<?php
+
+require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
+
+class CommissionHandler
+{
+    public function __construct()
+    {
+        global $db, $user;
+
+        $this->db = $db;
+        $this->user = $user;
+    }
+
+    function getCommissionFromProduct($id)
+    {
+        $remiseSUM = 0;
+        $commission = 0;
+        $commission_type = '';
+        $sqlRemise = "SELECT fdet.remise_percent FROM llx_facture as f
+        INNER JOIN llx_facturedet as fdet ON fdet.fk_facture = f.rowid
+        WHERE f.rowid = {$id}";
+        $resultRemise = $this->db->query($sqlRemise);
+        while ($remise = pg_fetch_assoc($resultRemise)) {
+            $remiseSUM += $remise['remise_percent'];
+        }
+        $sql = "SELECT fk_product FROM public.llx_facturedet WHERE fk_facture = {$id}";
+        $result = $this->db->query($sql);
+        while ($row = pg_fetch_assoc($result)) {
+            $product = new Product($this->db);
+            $res = $product->fetch($row['fk_product']);
+            if ($res > 0) {
+                if($remiseSUM > 0 && $product->array_options['options_reduced_commission'] > 0){
+                    $commission_type = $this->getCommissionType($product->array_options['options_reduced_commission_type']);
+                    if($commission_type != '%'){
+                        $commission += $product->array_options['options_reduced_commission'];
+                    }else{
+                        $commission = $product->array_options['options_reduced_commission'];
+                    }
+                }else{
+                    $commission_type = $this->getCommissionType($product->array_options['options_commission_type']);
+                    if($commission_type != '%'){
+                        $commission += $product->array_options['options_commission_value'];
+                    }else{
+                        $commission = $product->array_options['options_commission_value'];
+                    }
+                    
+                }
+            }
+        }
+        return number_format($commission, 8, '.', '') . '_' . $commission_type;
+    }
+
+    private function getCommissionType($type)
+    {
+        switch ($type) {
+            case '1':
+                return '%';
+                break;
+            case '2':
+                return 'Ft';
+                break;
+            case '3':
+                return '€';
+                break;
+        }
+    }
+
+    function updateCommission($object)
+    {
+        global $user, $db;
+        $commission = $this->getCommissionFromProduct($object->id);
+        $facture = new Facture($db);
+        $result = $facture->fetch($object->id);
+        if ($result > 0) {
+            $facture->array_options['options_commission'] = $commission;
+            $facture->update($user);
+        }
+
+        //$objectFacture->commission = $commission;
+        //$objectFacture->update($user);
+    }
+
+    function getAllCommissionByUserId($user, $date, $currency)
+    {
+        $result = 0;
+        $sql = "SELECT f.rowid, f.total_ttc, fe.commission FROM llx_facture as f
+        INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid
+        WHERE 
+        fk_user_closing = {$user['user_id']} AND
+        multicurrency_code = '{$currency}' AND
+        date_closing < '{$date} 00:00:00'";
+        $result = $this->db->query($sql);
+        while ($row = pg_fetch_assoc($result)) {
+            $commissions += $this->getAmountOfCommission($row);
+        }
+        return round($commissions, 3);
+    }
+
+    function getAllCommission($allUsersString, $currency, $from, $to, $allComissionInvoicesOfUserInTheGroupFromUserInvoice)
+    {
+        $commissions = 0;
+        $sql = "SELECT f.rowid, f.total_ttc, fe.commission FROM llx_facture as f
+        INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid
+        WHERE f.fk_user_closing IN ({$allUsersString})
+        AND EXISTS (SELECT * FROM llx_bbus_bbticketinvoiceprinting as bbip WHERE bbip.fk_facture = f.rowid ORDER BY bbip.rowid DESC LIMIT 1) AND ";
+        if (!empty($allComissionInvoicesOfUserInTheGroupFromUserInvoice)) {
+            $sql .= " f.rowid NOT IN({$allComissionInvoicesOfUserInTheGroupFromUserInvoice}) AND";
+        }
+        $sql .= " multicurrency_code = '{$currency}' AND
+        date_closing BETWEEN '{$from}' AND '{$to}' 
+        --AND fe.marked_for_storno IS NULL 
+        AND fe.commission_deduction is NULL
+        AND (SELECT a.rowid FROM llx_facture as a WHERE a.fk_facture_source = f.rowid AND fk_user_closing IN ({$allUsersString})) Is NULL";
+        //print $sql.'<br>';
+        $result = $this->db->query($sql);
+        while ($row = pg_fetch_assoc($result)) {
+            $commissions += $this->getAmountOfCommission($row);
+        }
+        return $commissions;
+    }
+
+    function getCommisonByUserId($user_id, $currency, $from, $to, $allComissionInvoicesOfUserInTheGroupFromUserInvoice)
+    {
+        global $db;
+        $commissions = 0;
+        $sql = "SELECT f.rowid, f.total_ttc, fe.commission
+        FROM llx_facture as f 
+        INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid 
+        WHERE EXISTS (SELECT * FROM llx_bbus_bbticketinvoiceprinting as bbip WHERE bbip.fk_facture = f.rowid ORDER BY bbip.rowid DESC LIMIT 1) AND";
+        if (!empty($allComissionInvoicesOfUserInTheGroupFromUserInvoice)) {
+            $sql .= " f.rowid NOT IN({$allComissionInvoicesOfUserInTheGroupFromUserInvoice}) AND";
+        }
+        $sql .= "
+        fk_user_closing = {$user_id} 
+        AND multicurrency_code = '{$currency}' 
+        --AND fe.marked_for_storno IS NULL 
+        AND fe.commission_deduction is NULL
+        AND date_closing BETWEEN '{$from}' AND '{$to}'";
+        //print $sql;
+        $result = $db->query($sql);
+        if ($db->num_rows($result) != 0) {
+            while ($row = pg_fetch_assoc($result)) {
+                $commissions += $this->getAmountOfCommission($row);
+            }
+        }
+        return $commissions;
+    }
+
+    function getCashCommisonByUserId($user_id, $currency, $from, $to, $allComissionInvoicesOfUserInTheGroupFromUserInvoice, $entity, $code)
+    {
+        $commissions = 0;
+        //$from = date('Y-m-d H:i:s', strtotime("-1 day", strtotime($from)));
+        //print $from;exit;
+        $to = date('Y-m-d H:i:s', dol_now());
+        $sql = "SELECT f.rowid, f.multicurrency_total_ttc, fe.commission
+        FROM llx_facture as f 
+        INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid 
+        WHERE EXISTS (SELECT * FROM llx_bbus_bbticketinvoiceprinting as bbip WHERE bbip.fk_facture = f.rowid ORDER BY bbip.rowid DESC LIMIT 1) AND";
+        if (!empty($allComissionInvoicesOfUserInTheGroupFromUserInvoice)) {
+            $sql .= " f.rowid NOT IN({$allComissionInvoicesOfUserInTheGroupFromUserInvoice}) AND";
+        }
+        $sql .= " (SELECT a.rowid FROM llx_facture as a WHERE a.fk_facture_source = f.rowid AND fk_user_closing = {$user_id}) Is NULL AND
+        fk_user_closing = {$user_id} 
+        AND fk_mode_reglement = (SELECT id FROM public.llx_c_paiement WHERE entity = {$entity} AND code = '{$code}')
+        AND multicurrency_code = '{$currency}' 
+        --AND fe.marked_for_storno is NuLL 
+        AND fe.commission_deduction is NULL
+        AND date_closing BETWEEN '{$from}' AND '{$to}'";
+        //print $sql . '<br>';
+        $result = $this->db->query($sql);
+        while ($row = pg_fetch_assoc($result)) {
+            $commissions += $row['multicurrency_total_ttc'];
+        }
+        return $commissions;
+    }
+
+    function getCashCommisonByUserIdHistory($user_id, $currency, $allComissionInvoicesOfUserInTheGroupFromUserInvoice, $id, $entity, $code)
+    {
+        global $db;
+        $from = $this->calculateFromDate($id);
+        $to = $this->calculateToDate($user_id, $from);
+        $commissions = 0;
+
+        $sql = "SELECT f.rowid, f.multicurrency_total_ttc, fe.commission
+        FROM llx_facture as f 
+        INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid 
+        WHERE EXISTS (SELECT * FROM llx_bbus_bbticketinvoiceprinting as bbip WHERE bbip.fk_facture = f.rowid ORDER BY bbip.rowid DESC LIMIT 1) AND";
+        if (!empty($allComissionInvoicesOfUserInTheGroupFromUserInvoice)) {
+            $sql .= " f.rowid NOT IN({$allComissionInvoicesOfUserInTheGroupFromUserInvoice}) AND";
+        }
+        $sql .= " (SELECT a.rowid FROM llx_facture as a WHERE a.fk_facture_source = f.rowid AND fk_user_closing = {$user_id}) Is NULL AND
+        fk_user_closing = {$user_id} 
+        AND fk_mode_reglement = (SELECT id FROM public.llx_c_paiement WHERE entity = {$entity} AND code = '{$code}')
+        AND multicurrency_code = '{$currency}' 
+        AND date_closing BETWEEN '{$from}' AND '{$to}'";
+        //print $sql . '<br>';
+        $result = $db->query($sql);
+        while ($row = pg_fetch_assoc($result)) {
+            $commissions += $row['multicurrency_total_ttc'];
+        }
+        return $commissions;
+    }
+
+    public function calculateFromDate($id)
+    {
+        global $db;
+        $packageHistoryObj = new PackageHistory($db);
+        $packageHistoryObj->fetch($id);
+        return date('Y-m-d H:i:s', $packageHistoryObj->date_creation);
+    }
+
+    public function calculateToDate($user_id, $from)
+    {
+        global $db;
+        $sql1 = "SELECT date_creation FROM public.llx_rollerstorage_packagehistory
+        WHERE user_id = {$user_id}
+        AND date_creation > '{$from}'
+        ORDER BY rowid DESC";
+        $result1 = $db->query($sql1);
+        while ($row1 = pg_fetch_assoc($result1)) {
+            $toDate = $row1['date_creation'];
+        }
+        $now = dol_now();
+        return is_null($toDate) ? date('Y-m-d H:i:s', $now) : $toDate;
+    }
+
+    public function getAmountOfCommission($row)
+    {
+        $total_ttc = $row['total_ttc'];
+        $commission = $row['commission'];
+        if (isset($commission) && $commission != '_' && !is_null($commission)) {
+            $array = explode('_', $commission);
+            $number = $array[0];
+            $type = $array[1];
+            if ($type !== '%') {
+                return $number;
+            } else {
+                //print number_format($number / 100, 4, '.', '');
+                return $total_ttc * number_format($number / 100, 4, '.', '');
+            }
+        } else {
+            return 0;
+        }
+
+    }
+
+    function getOccassionOfThisPeriodByDateAndUserId_HUF($user_id, $from, $to)
+    {
+        $commissions = 0;
+        $sql = "SELECT f.rowid, f.total_ttc, fe.commission FROM llx_facture as f
+        INNER JOIN llx_facture_extrafields as fe ON fe.fk_object = f.rowid
+        WHERE 
+        fk_user_closing = {$user_id}  AND
+        multicurrency_code = 'HUF' AND
+        date_closing BETWEEN '{$from}' AND '{$to}' ";
+        $result = $this->db->query($sql);
+        while ($row = pg_fetch_assoc($result)) {
+            $commissions += $this->getAmountOfCommission($row);
+        }
+        return $commissions;
+    }
+
+    function getCommisonByUserIdForAMonth($user_id, $year = null, $month = null)
+    {
+        global $db;
+        $commissions = 0;
+        $sql = "SELECT sum(amount) FROM llx_financialreport_userinvoice
+        WHERE user_id = {$user_id}
+        AND payment_type = 2";
+        if (!is_null($year) && !is_null($month)) {
+            $sql .= " AND DATE_PART('year', date_creation) = {$year} AND DATE_PART('month', date_creation) = {$month}";
+        }
+        $result = $db->query($sql);
+        while ($row = pg_fetch_assoc($result)) {
+            return $row['sum'];
+        }
+    }
+
+    function getUserMinimumCommission($user_id)
+    {
+        global $db;
+        $userObj = new User($db);
+        $sql = "SELECT ue.minimum_monthly_commission FROM llx_user as u INNER JOIN llx_user_extrafields as ue ON ue.fk_object = u.rowid WHERE u.rowid = {$user_id}";
+        $result = $db->query($sql);
+        while($row = $db->fetch_object($result))
+        {
+            return $row->minimum_monthly_commission;
+        }
+    }
+
+    function getTotalCommission($user_id, $from, $to)
+    {
+        global $db;
+        $helper = new HelperUserInvoice($db);
+        $allComissionInvoicesOfUserInTheGroupFromUserInvoice = $helper->getAllComissionInvoicesOfUserInTheGroupFromUserInvoice($user_id, $from, date("Y-m-d H:i:s", dol_now()));
+        $commissionHUF = $this->getCommisonByUserId($user_id, 'HUF', $from, $to, $allComissionInvoicesOfUserInTheGroupFromUserInvoice);
+        $commissionEUR = $this->getCommisonByUserId($user_id, 'EUR', $from, $to, $allComissionInvoicesOfUserInTheGroupFromUserInvoice);
+        $fullCommission = $commissionHUF + $commissionEUR;
+        return $fullCommission;
+    }
+
+    function getTotalCommissionFromThisPeriod($user_id, $from, $to)
+    {
+        global $db;
+        $from = date("Y-m-d H:i:s", strtotime('-1 hour', strtotime($from)));
+        $array = [];
+        $sql = "SELECT label, amount, date_creation FROM " . MAIN_DB_PREFIX . "financialreport_userinvoice WHERE user_id = {$user_id} AND payment_type = 2 AND date_creation BETWEEN '{$from}' AND '{$to}'";
+        $data = $db->query($sql);
+        if(pg_num_rows($data) > 0){
+            while ($row = pg_fetch_assoc($data)) {
+                $array[] = $row;
+            }
+        }
+        return $array;
+    }
+
+    function getDailyMinimumCommission()
+    {
+        global $db;
+        $date = date('Y-m-d H:i:s', dol_now());
+        $sql = "SELECT option.amount FROM public.llx_financialreport_commissioninterval AS interval
+        INNER JOIN llx_financialreport_commissionoptions as option ON option.rowid = interval.option_id
+        WHERE '{$date}' BETWEEN interval.interval_start AND interval.interval_end";
+        //WHERE '2023-01-01 10:10:10' BETWEEN interval.interval_start AND interval.interval_end";
+        $result = $db->query($sql);
+        if(pg_num_rows($result) > 0){
+            while ($row = pg_fetch_assoc($result)) {
+                return $row['amount'];
+            }
+        }
+        return 0;
+    }
+
+}

+ 216 - 0
custom/bbus/class/roller_handling.class.php

@@ -0,0 +1,216 @@
+<?php
+
+require_once DOL_DOCUMENT_ROOT . '/custom/rollerstorage/class/rollerrenthistory.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/roller_handling_helper.class.php';
+
+use Luracast\Restler\RestException;
+
+trait RollerHandling
+{
+	use RollerHandligHelper;
+
+	/**
+	 * Get status of a roller by barcode
+	 *
+	 * Return an array with product information.
+	 *
+	 * @param  string $code	Roller QR code
+	 *
+	 * @return array|mixed Data without useless information
+	 *
+	 * @url POST RENT_checkScooterStatus
+	 */
+
+	// Kellenek még a foglalási adatok ha vanank egy tömbben. HA nincs ,akkor üres tömb.
+	public function RENT_checkScooterStatus(string $code)
+	{
+		ApiBbusLog::ScooterRentLog("RENT_checkScooterStatus: ___START___");
+		$scooterData = $this->getAllScooterDataByCode($code);
+		ApiBbusLog::ScooterRentLog("RENT_checkScooterStatus: ___END___");
+		return $scooterData;
+	}
+
+
+	/**
+	 * Get status of a roller by barcode and Invoice number
+	 *
+	 * Return an array with product information.
+	 *
+	 * @param  string $code	Roller QR code
+	 * @param  string $invoice_number	Invoice number
+	 *
+	 * @return array|mixed Data without useless information
+	 *
+	 * @url POST RENT_checkScooterStatusAfterTicketValidation
+	 */
+
+	// Kellenek még a foglalási adatok ha vanank egy tömbben. HA nincs ,akkor üres tömb.
+	public function RENT_checkScooterStatusAfterTicketValidation(string $code, $invoice_number)
+	{
+		ApiBbusLog::ScooterRentLog("RENT_checkScooterStatusAfterTicketValidation: ___START___");
+		$scooterDataArray = [];
+		$scooterData = $this->getAllScooterDataByCode($code);
+		$scooterDataArray['scooter'] = $scooterData;
+		$scooterDataArray['isRented'] = $this->db->num_rows($this->checkRentHistory($scooterData->rowid, $invoice_number)) > 0;
+		ApiBbusLog::ScooterRentLog("RENT_checkScooterStatusAfterTicketValidation: ___END___");
+		return $scooterDataArray;
+	}
+
+
+	/**
+	 * Get available statuses of a roller
+	 *
+	 * Return an array with product information.
+	 *
+	 * @return array|mixed Data without useless information
+	 *
+	 * @url GET RENT_GetAvailableStatuses
+	 */
+	public function RENT_GetAvailableStatuses()
+	{
+		ApiBbusLog::ScooterRentLog("RENT_GetAvailableStatuses: ___START___");
+		$statuses = [];
+		$sql = "SELECT status_id FROM llx_rollerstorage_statuses WHERE status_id != 112";
+		$result = $this->db->query($sql);
+		if ($this->db->num_rows($result) > 0) {
+			while ($row = $this->db->fetch_object($result)) {
+				$statuses[] = $row->status_id;
+			}
+			ApiBbusLog::ScooterRentLog("RENT_GetAvailableStatuses: ___END___");
+			return $statuses;
+		}
+		ApiBbusLog::ScooterRentLog("RENT_GetAvailableStatuses: ___END___");
+		return $statuses;
+	}
+
+
+	/**
+	 * Set status of a scooter
+	 *
+	 * @param  string $statuscode
+	 * @param  string $rowid
+	 *
+	 * @return array|mixed Data without useless information
+	 *
+	 * @url POST RENT_setScooterStatus
+	 */
+	public function RENT_setScooterStatus($statuscode, $rowid)
+	{
+		ApiBbusLog::ScooterRentLog("RENT_setScooterStatus: ___START___");
+		$sql = "UPDATE llx_inventory SET status = {$statuscode} WHERE rowid = {$rowid}";
+		$result = $this->db->query($sql);
+		$inventoryObj = new Inventory($this->db);
+		$resultupdated = $inventoryObj->fetch($rowid);
+		ApiBbusLog::ScooterRentLog("Scooter status changed to {$inventoryObj->status}!");
+		ApiBbusLog::ScooterRentLog("RENT_setScooterStatus: ___END___");
+		return $inventoryObj->status;
+	}
+
+	/**
+	 * Connect scooter and event
+	 *
+	 * @param  string $inventory_id
+	 * @param  string $invoice_number
+	 * @param  int $ticket_id
+	 *
+	 * @return array|mixed Data without useless information
+	 *
+	 * @url POST RENT_ConnectFactureAndScooter
+	 */
+	public function RENT_ConnectFactureAndScooter($inventory_id, $invoice_number, $ticket_id, $isReplaced = false)
+	{
+		ApiBbusLog::ScooterRentLog("RENT_ConnectFactureAndScooter: ___START___");
+		$error = 0;
+		$this->db->begin();
+		$ScooterRentHistoryId = $this->CreateScooterRentHistoryRecord($inventory_id, $invoice_number);
+		(int)$ScooterRentHistoryId > 0 ?: $error++;
+		ApiBbusLog::ScooterRentLog("RentHistoryRecord: {$ScooterRentHistoryId}");
+		$this->RENT_setScooterStatus("112", $inventory_id) == '112' ?: $error++;
+		if(!$isReplaced){
+			$sql = "SELECT * FROM llx_bbus_bbticket WHERE rowid = {$ticket_id}";
+			$result = $this->db->query($sql);
+			while ($row = $this->db->fetch_object($result)) {
+				$this->updateScooterBbticket($row) > 0 ?: $error++;
+			}
+		}
+		$this->checkError($error);
+		$this->db->commit();
+		ApiBbusLog::ScooterRentLog("RENT_ConnectFactureAndScooter: ___END___");
+		return "OK";
+	}
+
+	/**
+	 * Scooter Take back
+	 *
+	 * @param  string $code Scooter title code
+	 *
+	 * @return array|mixed Data without useless information
+	 *
+	 * @url POST RENT_isExpired
+	 */
+	public function RENT_isExpired($code)
+	{
+		ApiBbusLog::ScooterRentLog("RENT_isExpired: ___START___");
+		$scooterData = $this->getScooterRowidByCode($code);
+		$invoice_number = $this->getInvoiceNumberByInvetoryId($scooterData);
+		return $this->checkExpireDate($invoice_number);
+	}
+
+	/**
+	 * Scooter Take back
+	 *
+	 * @param  string $code
+	 * @param  int $roller_status
+	 *
+	 * @return array|mixed Data without useless information
+	 *
+	 * @url POST RENT_scooterTakeBack
+	 */
+	public function RENT_scooterTakeBack($code, $roller_status)
+	{
+		ApiBbusLog::ScooterRentLog("RENT_scooterReplacement: ___START___");
+
+		# Ezt hívjuk meg akkor is, ha csere van (státusz: 110 (In stock) / 114 (Faulty)) és akkor is ha rendes visszavételezés történik, de ebben az esetben 111-es státusszal.
+		$error = 0;
+		$scooterData = $this->getScooterRowidByCode($code);
+		$invoice_number = $this->getInvoiceNumberByInvetoryId($scooterData);
+		$this->db->begin();
+		# Create RollerRentHistory Record
+		$ScooterRentHistoryId = $this->CreateScooterRentHistoryRecord($scooterData, $invoice_number, 0);
+		(int)$ScooterRentHistoryId > 0 ?: $error++;
+		# Update Rollerstatus in llx_inventory
+		$this->RENT_setScooterStatus($roller_status, $scooterData)  == $roller_status ?: $error++;
+		$this->checkError($error);
+		$this->db->commit();
+		ApiBbusLog::ScooterRentLog("RENT_scooterReplacement: ___END___");
+		return 'OK';
+	}
+
+	/**
+	 * Scooter Take back
+	 *
+	 * @param  string $code_1
+	 * @param  string $scooter_1_status
+	 * @param  string $code_2
+	 *
+	 * @return array|mixed Data without useless information
+	 *
+	 * @url POST RENT_scooterReplacement
+	 */
+	public function RENT_scooterReplacement($code_1, $scooter_1_status, $code_2)
+	{
+		ApiBbusLog::ScooterRentLog("RENT_scooterReplacement: ___START___");
+		$this->RENT_scooterTakeBack($code_1, $scooter_1_status);
+		$scooter_2_data = $this->RENT_checkScooterStatus($code_2);
+		if($scooter_2_data->status == '110'){
+			$scooter_1_data = $this->RENT_checkScooterStatus($code_1);
+			$invoice_number = $this->getInvoiceNumberByInvetoryId($scooter_1_data->rowid);
+			$ticket_id = $this->getTicketIdByInvoiceNumber($invoice_number);
+			$this->RENT_ConnectFactureAndScooter($scooter_2_data->rowid, $invoice_number, $ticket_id, true);
+		}else{
+			return $scooter_2_data->status;
+		}
+		ApiBbusLog::ScooterRentLog("RENT_scooterReplacement: ___END___");
+		return 'OK';
+	}
+}

+ 163 - 0
custom/bbus/class/roller_handling_helper.class.php

@@ -0,0 +1,163 @@
+<?php
+
+use Luracast\Restler\RestException;
+
+trait RollerHandligHelper
+{
+    public function getAllScooterDataByCode($code)
+    {
+        $deviceTypes = ['5' => 'Seev Citycoco', '6' => 'WIZTEM'];
+        $sql = "SELECT 
+            i.rowid, i.entity, i.ref, i.fk_warehouse, i.status, i.title
+            , ent.ref, ent.lieu
+            , ie.device_type
+            FROM llx_inventory as i 
+            INNER JOIN llx_entrepot AS ent ON ent.rowid = i.fk_warehouse
+            INNER JOIN llx_inventory_extrafields as ie ON ie.fk_object = i.rowid
+            WHERE i.title ILIKE '%{$code}%'";
+        $result = $this->db->query($sql);
+        if ($this->db->num_rows($result) > 0) {
+            while ($row = $this->db->fetch_object($result)) {
+                $row->device_type = $deviceTypes[$row->device_type];
+                return $row;
+            }
+        }
+        return [];
+    }
+
+    public function getScooterRowidByCode($code)
+    {
+        $sql = "SELECT * FROM llx_inventory as i WHERE i.title ILIKE '%{$code}%'";
+        $result = $this->db->query($sql);
+        if ($this->db->num_rows($result) > 0) {
+            while ($row = $this->db->fetch_object($result)) {
+                return $row->rowid;
+            }
+        }
+        return [];
+    }
+
+    private function CreateScooterRentHistoryRecord($inventory_id, $invoice_number, $status = 1)
+    {
+        ApiBbusLog::ScooterRentLog('RentHistoryRecord: ___START___');
+        global $user;
+        $rollerRentHistoryObj = new RollerRentHistory($this->db);
+        $rollerRentHistoryObj->inventory_id = $inventory_id;
+        $rollerRentHistoryObj->invoice_number = $invoice_number;
+        $rollerRentHistoryObj->status = $status;
+        return $rollerRentHistoryObj->create($user);
+    }
+
+    private function checkError($error)
+    {
+        if ($error > 0) {
+            $this->db->rollback();
+            ApiBbusLog::ScooterRentLog('ConnectFactureAndScooter Rollback...');
+            throw new RestException(509);
+        }
+    }
+
+    private function updateScooterBbticket($selectedTicket)
+    {
+        $ticketChecker = new TicketChecker();
+        $validated_at = date('Y-m-d H:i:s');
+        $duration = $this->getDurationByProductId($selectedTicket->ticket_id);
+        $expire_at = $this->getExpireAt($selectedTicket, $duration, $validated_at);
+        $usage = $this->setUsage($selectedTicket);
+        $sql = "UPDATE " . $this->db->prefix() . "bbus_bbticket SET validated_at = '" . $validated_at . "', expire_at = '" . $expire_at . "'";
+        $sql .= ", usage = '" . $usage . "'";
+        $sql .= " WHERE rowid = " . $selectedTicket->rowid;
+        return $this->db->query($sql);
+    }
+
+    private function getDurationByProductId($ticket_id)
+    {
+        $sql = "SELECT p.duration as duration  FROM " . $this->db->prefix() . "product AS p WHERE rowid = " . $ticket_id;
+        $result = $this->db->query($sql);
+        while ($row = $this->db->fetch_object($result)) {
+            return $row->duration;
+        }
+    }
+
+    private function getExpireAt($obj, $duration, $validated_at)
+    {
+        return date('Y-m-d H:i:s', strtotime($validated_at . ' +' . substr($duration, 0, -1) . ' ' . $this->getIntervalTimeByDuration()));
+    }
+
+    private function setUsage($selectedTicket)
+    {
+        $usage = (int)$selectedTicket->usage + 1;
+        return $usage;
+    }
+
+    private function getIntervalTimeByDuration()
+    {
+        $duration = $this->duration[-1];
+        switch ($duration) {
+            case 'h':
+                return 'hours';
+            case 'd':
+                return 'days';
+            case 'w':
+                return 'weeks';
+            case 'm':
+                return 'months';
+            case 'y':
+                return 'years';
+            default:
+                return 'hours';
+        }
+    }
+
+    public function checkRentHistory($rowid, $invoice_number)
+    {
+        $sql = "SELECT * FROM llx_rollerstorage_rollerrenthistory WHERE inventory_id = {$rowid} AND invoice_number = '{$invoice_number}' AND status = 1";
+        return $this->db->query($sql);
+    }
+
+    public function getInvoiceNumberByInvetoryId($inventory_id)
+    {
+        $invoice_number = '';
+        $sql = "SELECT * FROM llx_rollerstorage_rollerrenthistory WHERE inventory_id = {$inventory_id} AND status = 1 ORDER BY date_creation DESC LIMIT 1";
+        $result = $this->db->query($sql);
+        if ($this->db->num_rows($result) > 0) {
+            while ($row = $this->db->fetch_object($result)) {
+                $invoice_number = $row->invoice_number;
+            }
+        }
+        return $invoice_number;
+    }
+
+    public function getBbticketDataByInvoiceNumber($invoice_number)
+    {
+        $bbTicketData = [];
+        $sql = "SELECT * FROM llx_bbus_bbticket WHERE invoice_number = '{$invoice_number}'";
+        $result = $this->db->query($sql);
+        if ($this->db->num_rows($result) > 0) {
+            while ($row = $this->db->fetch_object($result)) {
+                $bbTicketData = $row;
+            }
+        }
+        return $bbTicketData;
+    }
+
+    public function checkExpireDate($invoice_number)
+    {
+        $now = date("Y-m-d H:i:s", dol_now());
+        if ($invoice_number !== '') {
+            $ticketData = $this->getBbticketDataByInvoiceNumber($invoice_number);
+            if (strtotime($ticketData->expire_at) < strtotime($now)) {
+                return true;
+            }
+        } else {
+            throw new RestException(508);
+        }
+        return false;
+    }
+
+    public function getTicketIdByInvoiceNumber($invoice_number)
+    {
+        $bbticketObj = $this->getBbticketDataByInvoiceNumber($invoice_number);
+        return $bbticketObj->ticket_id;
+    }
+}

+ 17 - 0
custom/bbus/class/ticket_checker.class.php

@@ -2,6 +2,9 @@
 
 use Luracast\Restler\RestException;
 
+require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/basicservices.class.php';
+
 class TicketChecker
 {
     private $db;
@@ -481,4 +484,18 @@ class TicketChecker
             throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
         }
     }
+
+    public function getTicketTypeByProductId($product_id){
+        $productObj = new Product($this->db);
+        $result = $productObj->fetch($product_id);
+        if($result > 0){
+            $basicServicesObj = new BasicServices($this->db);
+            $resultBS = $basicServicesObj->fetch($productObj->array_options['options_basic_service']);
+            if($resultBS > 0){
+                return $basicServicesObj->server_host;
+            }
+        }else{
+            return false;
+        }
+    }
 }

+ 118 - 1
custom/booking/class/api_booking.class.php

@@ -1262,7 +1262,8 @@ class BookingApi extends DolibarrApi
 	 * @throws RestException 401 Not allowed
 	 * @throws RestException 404 Not found
 	 */
-	public function localCheckAvailablePlaces($product_id){
+	public function localCheckAvailablePlaces($product_id)
+	{
 		$date_from = $this->getCutOffTimeDate($product_id);
 		$sql = "SELECT 
 		ac.id, 
@@ -1459,4 +1460,120 @@ class BookingApi extends DolibarrApi
 		$available_at = date('Y-m-d H:i:s', strtotime($date . ' +' . $validperiod . ' days'));
 		return $available_at;
 	}
+
+	/**
+	 * Get printed factures refs
+	 *
+	 * Return an array with details
+	 *
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @param 	string		$from
+	 * @param 	string		$to
+	 * @param 	string		$factures
+	 * 
+	 * @url	POST getPrintedFacturesRefs
+	 
+
+	 * @throws RestException 401 Not allowed
+	 * @throws RestException 404 Not found
+	 * @throws RestException 506 No available spaces
+	 * 
+	 */
+	public function getPrintedFacturesRefs(string $from, string $to, string $factures = "")
+	{
+		$refs = "";
+		if ($factures != "") {
+			global $db, $conf;
+			$curluser_id = $conf->global->CURL_USER_ID;
+			$sql = "SELECT bbt.invoice_number 
+				FROM llx_bbus_bbticket as bbt 
+				INNER JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.ticket_id = bbt.rowid 
+				WHERE bbt.fk_user_creat = {$curluser_id} AND bbt.invoice_number IN ({$factures}) AND bbt.date_creation BETWEEN '{$from}' AND '{$to}' ORDER BY bbt.rowid DESC";
+			$result = $db->query($sql);
+			if ($db->num_rows($result) > 0) {
+				while ($row = $db->fetch_object($result)) {
+					if ($refs == "") {
+						$refs .= "'" . $row->invoice_number . "'";
+					} else {
+						$refs .= ",'" . $row->invoice_number . "'";
+					}
+				}
+			}
+		}
+		return $refs;
+	}
+
+	/**
+	 * Get printed factures refs in array
+	 *
+	 * Return an array with details
+	 *
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @param 	string		$from
+	 * @param 	string		$to
+	 * @param 	string		$factures
+	 * 
+	 * @url	POST getPrintedFacturesRefsArray
+	 
+
+	 * @throws RestException 401 Not allowed
+	 * @throws RestException 404 Not found
+	 * @throws RestException 506 No available spaces
+	 * 
+	 */
+	public function getPrintedFacturesRefsArray(string $from, string $to, string $factures)
+	{
+		$refs = [];
+		global $db, $conf;
+		$curluser_id = $conf->global->CURL_USER_ID;
+		$sql = "SELECT bbt.invoice_number 
+				FROM llx_bbus_bbticket as bbt 
+				INNER JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.ticket_id = bbt.rowid 
+				WHERE bbt.fk_user_creat = {$curluser_id} AND bbt.invoice_number IN ({$factures}) AND bbt.date_creation BETWEEN '{$from}' AND '{$to}' ORDER BY bbt.rowid DESC";
+		$result = $db->query($sql);
+		if ($db->num_rows($result) > 0) {
+			while ($row = $db->fetch_object($result)) {
+				$refs[] = $row->invoice_number;
+			}
+		}
+		return $refs;
+	}
+
+	/**
+	 * Get number of a facture's printer count
+	 *
+	 * Return an array with details
+	 *
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @param 	string		$invoice_number
+	 * 
+	 * @url	POST getFacturesNumberOfPrints
+	 
+
+	 * @throws RestException 401 Not allowed
+	 * @throws RestException 404 Not found
+	 * @throws RestException 506 No available spaces
+	 * 
+	 */
+	public function getFacturesNumberOfPrints(string $invoice_number)
+	{
+		$number = 0;
+		global $db;
+		$sql = "SELECT tip.fk_facture, tip.product_id, count(tip.product_id)  FROM llx_bbus_bbticketinvoiceprinting as tip
+        WHERE tip.invoice_number = '{$invoice_number}'
+        GROUP BY tip.fk_facture, tip.product_id";
+		$result = $db->query($sql);
+		if ($db->num_rows($result) > 0) {
+			while ($row = $db->fetch_object($result)) {
+				$array[$row->fk_facture][$row->product_id] = $row->count;
+			}
+			$firstKey = array_key_first($array);
+			$firstValue = $array[$firstKey];
+			$number = reset($firstValue);
+		}
+		return $number;
+	}
 }

+ 147 - 0
custom/rollerstorage/admin/rollerrenthistory_extrafields.php

@@ -0,0 +1,147 @@
+<?php
+/* Copyright (C) 2001-2002	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
+ * Copyright (C) 2003		Jean-Louis Bergamo		<jlb@j1b.org>
+ * Copyright (C) 2004-2011	Laurent Destailleur		<eldy@users.sourceforge.net>
+ * Copyright (C) 2012		Regis Houssin			<regis.houssin@inodbox.com>
+ * Copyright (C) 2014		Florian Henry			<florian.henry@open-concept.pro>
+ * Copyright (C) 2015		Jean-François Ferry		<jfefe@aternatik.fr>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *      \file       admin/rollerrenthistory_extrafields.php
+ *		\ingroup    rollerstorage
+ *		\brief      Page to setup extra fields of rollerrenthistory
+ */
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+	$i--; $j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
+	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
+	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../../main.inc.php")) {
+	$res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+	$res = @include "../../../main.inc.php";
+}
+if (!$res) {
+	die("Include of main fails");
+}
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+require_once '../lib/rollerstorage.lib.php';
+
+// Load translation files required by the page
+$langs->loadLangs(array('rollerstorage@rollerstorage', 'admin'));
+
+$extrafields = new ExtraFields($db);
+$form = new Form($db);
+
+// List of supported format
+$tmptype2label = ExtraFields::$type2label;
+$type2label = array('');
+foreach ($tmptype2label as $key => $val) {
+	$type2label[$key] = $langs->transnoentitiesnoconv($val);
+}
+
+$action = GETPOST('action', 'aZ09');
+$attrname = GETPOST('attrname', 'alpha');
+$elementtype = 'rollerstorage_rollerrenthistory'; //Must be the $table_element of the class that manage extrafield
+
+if (!$user->admin) {
+	accessforbidden();
+}
+
+
+/*
+ * Actions
+ */
+
+require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php';
+
+
+
+/*
+ * View
+ */
+
+$textobject = $langs->transnoentitiesnoconv("RollerRentHistory");
+
+$help_url = '';
+$page_name = "RollerstorageSetup";
+
+llxHeader('', $langs->trans("RollerstorageSetup"), $help_url);
+
+
+$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
+print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup');
+
+
+$head = rollerstorageAdminPrepareHead();
+
+print dol_get_fiche_head($head, 'rollerrenthistory_extrafields', $langs->trans($page_name), -1, 'rollerstorage@rollerstorage');
+
+require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
+
+print dol_get_fiche_end();
+
+
+// Buttons
+if ((float) DOL_VERSION < 17) {	// On v17+, the "New Attribute" button is included into tpl.
+	if ($action != 'create' && $action != 'edit') {
+		print '<div class="tabsAction">';
+		print '<a class="butAction reposition" href="'.$_SERVER["PHP_SELF"].'?action=create">'.$langs->trans("NewAttribute").'</a>';
+		print "</div>";
+	}
+}
+
+
+/*
+ * Creation of an optional field
+ */
+if ($action == 'create') {
+	print '<br><div id="newattrib"></div>';
+	print load_fiche_titre($langs->trans('NewAttribute'));
+
+	require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
+}
+
+/*
+ * Edition of an optional field
+ */
+if ($action == 'edit' && !empty($attrname)) {
+	print "<br>";
+	print load_fiche_titre($langs->trans("FieldEdition", $attrname));
+
+	require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php';
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 1118 - 0
custom/rollerstorage/class/rollerrenthistory.class.php

@@ -0,0 +1,1118 @@
+<?php
+/* Copyright (C) 2017  Laurent Destailleur <eldy@users.sourceforge.net>
+ * Copyright (C) 2024 László Szollősi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ * \file        class/rollerrenthistory.class.php
+ * \ingroup     rollerstorage
+ * \brief       This file is a CRUD class file for RollerRentHistory (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for RollerRentHistory
+ */
+class RollerRentHistory extends CommonObject
+{
+	/**
+	 * @var string ID of module.
+	 */
+	public $module = 'rollerstorage';
+
+	/**
+	 * @var string ID to identify managed object.
+	 */
+	public $element = 'rollerrenthistory';
+
+	/**
+	 * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+	 */
+	public $table_element = 'rollerstorage_rollerrenthistory';
+
+	/**
+	 * @var int  Does this object support multicompany module ?
+	 * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+	 */
+	public $ismultientitymanaged = 0;
+
+	/**
+	 * @var int  Does object support extrafields ? 0=No, 1=Yes
+	 */
+	public $isextrafieldmanaged = 1;
+
+	/**
+	 * @var string String with name of icon for rollerrenthistory. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'rollerrenthistory@rollerstorage' if picto is file 'img/object_rollerrenthistory.png'.
+	 */
+	public $picto = 'fa-file';
+
+
+	const STATUS_DRAFT = 0;
+	const STATUS_VALIDATED = 1;
+	const STATUS_CANCELED = 9;
+
+
+	/**
+	 *  'type' field format:
+	 *  	'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',
+	 *  	'select' (list of values are in 'options'),
+	 *  	'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]',
+	 *  	'chkbxlst:...',
+	 *  	'varchar(x)',
+	 *  	'text', 'text:none', 'html',
+	 *   	'double(24,8)', 'real', 'price',
+	 *  	'date', 'datetime', 'timestamp', 'duration',
+	 *  	'boolean', 'checkbox', 'radio', 'array',
+	 *  	'mail', 'phone', 'url', 'password', 'ip'
+	 *		Note: Filter must be a Dolibarr filter syntax string. Example: "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.status:!=:0) or (t.nature:is:NULL)"
+	 *  'label' the translation key.
+	 *  'picto' is code of a picto to show before value in forms
+	 *  'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM' or 'isModEnabled("multicurrency")' ...)
+	 *  'position' is the sort order of field.
+	 *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+	 *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+	 *  'noteditable' says if field is not editable (1 or 0)
+	 *  'alwayseditable' says if field can be modified also when status is not draft ('1' or '0')
+	 *  'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+	 *  'index' if we want an index in database.
+	 *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+	 *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+	 *  'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
+	 *  'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
+	 *  'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+	 *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+	 *  'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+	 *  'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
+	 *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+	 *  'comment' is not used. You can store here any text of your choice. It is not used by application.
+	 *	'validate' is 1 if need to validate with $this->validateField()
+	 *  'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
+	 *
+	 *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+	 */
+
+	// BEGIN MODULEBUILDER PROPERTIES
+	/**
+	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+	 */
+	public $fields=array(
+		'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+		'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>'1', 'position'=>10, 'notnull'=>1, 'visible'=>0, 'default'=>'1', 'index'=>1,),
+		'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'validate'=>'1', 'comment'=>"Reference of object"),
+		'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
+		'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
+		'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'picto'=>'user', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid', 'csslist'=>'tdoverflowmax150',),
+		'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'picto'=>'user', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2, 'csslist'=>'tdoverflowmax150',),
+		'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>'1', 'position'=>2000, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Piszkozat', '1'=>'Hiteles&iacute;tve', '9'=>'Megszak&iacute;tva'), 'validate'=>'1',),
+		'event_id' => array('type'=>'integer', 'label'=>'Event', 'enabled'=>'1', 'position'=>512, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
+		'inventory_id' => array('type'=>'integer', 'label'=>'Scooter', 'enabled'=>'1', 'position'=>513, 'notnull'=>1, 'visible'=>1, 'noteditable'=>'1',),
+		'facture_id' => array('type'=>'integer', 'label'=>'Facture', 'enabled'=>'1', 'position'=>514, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
+		'ticket_id' => array('type'=>'integer', 'label'=>'Ticket', 'enabled'=>'1', 'position'=>515, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
+		'product_id' => array('type'=>'integer', 'label'=>'Product', 'enabled'=>'1', 'position'=>516, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
+		'invoice_number' => array('type'=>'varchar(255)', 'label'=>'InvoiceNumber', 'enabled'=>'1', 'position'=>517, 'notnull'=>1, 'visible'=>1, 'noteditable'=>'1',),
+	);
+	public $rowid;
+	public $entity;
+	public $ref;
+	public $date_creation;
+	public $tms;
+	public $fk_user_creat;
+	public $fk_user_modif;
+	public $status;
+	public $event_id;
+	public $inventory_id;
+	public $facture_id;
+	public $ticket_id;
+	public $product_id;
+	public $invoice_number;
+	// END MODULEBUILDER PROPERTIES
+
+
+	// If this object has a subtable with lines
+
+	// /**
+	//  * @var string    Name of subtable line
+	//  */
+	// public $table_element_line = 'rollerstorage_rollerrenthistoryline';
+
+	// /**
+	//  * @var string    Field with ID of parent key if this object has a parent
+	//  */
+	// public $fk_element = 'fk_rollerrenthistory';
+
+	// /**
+	//  * @var string    Name of subtable class that manage subtable lines
+	//  */
+	// public $class_element_line = 'RollerRentHistoryline';
+
+	// /**
+	//  * @var array	List of child tables. To test if we can delete object.
+	//  */
+	// protected $childtables = array();
+
+	// /**
+	//  * @var array    List of child tables. To know object to delete on cascade.
+	//  *               If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+	//  *               call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+	//  */
+	// protected $childtablesoncascade = array('rollerstorage_rollerrenthistorydet');
+
+	// /**
+	//  * @var RollerRentHistoryLine[]     Array of subtable lines
+	//  */
+	// public $lines = array();
+
+
+
+	/**
+	 * Constructor
+	 *
+	 * @param DoliDb $db Database handler
+	 */
+	public function __construct(DoliDB $db)
+	{
+		global $conf, $langs;
+
+		$this->db = $db;
+
+		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
+			$this->fields['rowid']['visible'] = 0;
+		}
+		if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
+			$this->fields['entity']['enabled'] = 0;
+		}
+
+		// Example to show how to set values of fields definition dynamically
+		/*if ($user->rights->rollerstorage->rollerrenthistory->read) {
+			$this->fields['myfield']['visible'] = 1;
+			$this->fields['myfield']['noteditable'] = 0;
+		}*/
+
+		// Unset fields that are disabled
+		foreach ($this->fields as $key => $val) {
+			if (isset($val['enabled']) && empty($val['enabled'])) {
+				unset($this->fields[$key]);
+			}
+		}
+
+		// Translate some data of arrayofkeyval
+		if (is_object($langs)) {
+			foreach ($this->fields as $key => $val) {
+				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+					foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+						$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+					}
+				}
+			}
+		}
+	}
+
+	/**
+	 * Create object into database
+	 *
+	 * @param  User $user      User that creates
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, Id of created object if OK
+	 */
+	public function create(User $user, $notrigger = false)
+	{
+		$resultcreate = $this->createCommon($user, $notrigger);
+
+		//$resultvalidate = $this->validate($user, $notrigger);
+
+		return $resultcreate;
+	}
+
+	/**
+	 * Clone an object into another one
+	 *
+	 * @param  	User 	$user      	User that creates
+	 * @param  	int 	$fromid     Id of object to clone
+	 * @return 	mixed 				New object created, <0 if KO
+	 */
+	public function createFromClone(User $user, $fromid)
+	{
+		global $langs, $extrafields;
+		$error = 0;
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$object = new self($this->db);
+
+		$this->db->begin();
+
+		// Load source object
+		$result = $object->fetchCommon($fromid);
+		if ($result > 0 && !empty($object->table_element_line)) {
+			$object->fetchLines();
+		}
+
+		// get lines so they will be clone
+		//foreach($this->lines as $line)
+		//	$line->fetch_optionals();
+
+		// Reset some properties
+		unset($object->id);
+		unset($object->fk_user_creat);
+		unset($object->import_key);
+
+		// Clear fields
+		if (property_exists($object, 'ref')) {
+			$object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+		}
+		if (property_exists($object, 'label')) {
+			$object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+		}
+		if (property_exists($object, 'status')) {
+			$object->status = self::STATUS_DRAFT;
+		}
+		if (property_exists($object, 'date_creation')) {
+			$object->date_creation = dol_now();
+		}
+		if (property_exists($object, 'date_modification')) {
+			$object->date_modification = null;
+		}
+		// ...
+		// Clear extrafields that are unique
+		if (is_array($object->array_options) && count($object->array_options) > 0) {
+			$extrafields->fetch_name_optionals_label($this->table_element);
+			foreach ($object->array_options as $key => $option) {
+				$shortkey = preg_replace('/options_/', '', $key);
+				if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
+					//var_dump($key);
+					//var_dump($clonedObj->array_options[$key]); exit;
+					unset($object->array_options[$key]);
+				}
+			}
+		}
+
+		// Create clone
+		$object->context['createfromclone'] = 'createfromclone';
+		$result = $object->createCommon($user);
+		if ($result < 0) {
+			$error++;
+			$this->error = $object->error;
+			$this->errors = $object->errors;
+		}
+
+		if (!$error) {
+			// copy internal contacts
+			if ($this->copy_linked_contact($object, 'internal') < 0) {
+				$error++;
+			}
+		}
+
+		if (!$error) {
+			// copy external contacts if same company
+			if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
+				if ($this->copy_linked_contact($object, 'external') < 0) {
+					$error++;
+				}
+			}
+		}
+
+		unset($object->context['createfromclone']);
+
+		// End
+		if (!$error) {
+			$this->db->commit();
+			return $object;
+		} else {
+			$this->db->rollback();
+			return -1;
+		}
+	}
+
+	/**
+	 * Load object in memory from the database
+	 *
+	 * @param int    $id   Id object
+	 * @param string $ref  Ref
+	 * @return int         <0 if KO, 0 if not found, >0 if OK
+	 */
+	public function fetch($id, $ref = null)
+	{
+		$result = $this->fetchCommon($id, $ref);
+		if ($result > 0 && !empty($this->table_element_line)) {
+			$this->fetchLines();
+		}
+		return $result;
+	}
+
+	/**
+	 * Load object lines in memory from the database
+	 *
+	 * @return int         <0 if KO, 0 if not found, >0 if OK
+	 */
+	public function fetchLines()
+	{
+		$this->lines = array();
+
+		$result = $this->fetchLinesCommon();
+		return $result;
+	}
+
+
+	/**
+	 * Load list of objects in memory from the database.
+	 *
+	 * @param  string      $sortorder    Sort Order
+	 * @param  string      $sortfield    Sort field
+	 * @param  int         $limit        limit
+	 * @param  int         $offset       Offset
+	 * @param  array       $filter       Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+	 * @param  string      $filtermode   Filter mode (AND or OR)
+	 * @return array|int                 int <0 if KO, array of pages if OK
+	 */
+	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+	{
+		global $conf;
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$records = array();
+
+		$sql = "SELECT ";
+		$sql .= $this->getFieldList('t');
+		$sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+			$sql .= " WHERE t.entity IN (".getEntity($this->element).")";
+		} else {
+			$sql .= " WHERE 1 = 1";
+		}
+		// Manage filter
+		$sqlwhere = array();
+		if (count($filter) > 0) {
+			foreach ($filter as $key => $value) {
+				if ($key == 't.rowid') {
+					$sqlwhere[] = $key." = ".((int) $value);
+				} elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+					$sqlwhere[] = $key." = '".$this->db->idate($value)."'";
+				} elseif ($key == 'customsql') {
+					$sqlwhere[] = $value;
+				} elseif (strpos($value, '%') === false) {
+					$sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
+				} else {
+					$sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
+				}
+			}
+		}
+		if (count($sqlwhere) > 0) {
+			$sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
+		}
+
+		if (!empty($sortfield)) {
+			$sql .= $this->db->order($sortfield, $sortorder);
+		}
+		if (!empty($limit)) {
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$resql = $this->db->query($sql);
+		if ($resql) {
+			$num = $this->db->num_rows($resql);
+			$i = 0;
+			while ($i < ($limit ? min($limit, $num) : $num)) {
+				$obj = $this->db->fetch_object($resql);
+
+				$record = new self($this->db);
+				$record->setVarsFromFetchObj($obj);
+
+				$records[$record->id] = $record;
+
+				$i++;
+			}
+			$this->db->free($resql);
+
+			return $records;
+		} else {
+			$this->errors[] = 'Error '.$this->db->lasterror();
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+			return -1;
+		}
+	}
+
+	/**
+	 * Update object into database
+	 *
+	 * @param  User $user      User that modifies
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, >0 if OK
+	 */
+	public function update(User $user, $notrigger = false)
+	{
+		return $this->updateCommon($user, $notrigger);
+	}
+
+	/**
+	 * Delete object in database
+	 *
+	 * @param User $user       User that deletes
+	 * @param bool $notrigger  false=launch triggers, true=disable triggers
+	 * @return int             <0 if KO, >0 if OK
+	 */
+	public function delete(User $user, $notrigger = false)
+	{
+		return $this->deleteCommon($user, $notrigger);
+		//return $this->deleteCommon($user, $notrigger, 1);
+	}
+
+	/**
+	 *  Delete a line of object in database
+	 *
+	 *	@param  User	$user       User that delete
+	 *  @param	int		$idline		Id of line to delete
+	 *  @param 	bool 	$notrigger  false=launch triggers after, true=disable triggers
+	 *  @return int         		>0 if OK, <0 if KO
+	 */
+	public function deleteLine(User $user, $idline, $notrigger = false)
+	{
+		if ($this->status < 0) {
+			$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+			return -2;
+		}
+
+		return $this->deleteLineCommon($user, $idline, $notrigger);
+	}
+
+
+	/**
+	 *	Validate object
+	 *
+	 *	@param		User	$user     		User making status change
+	 *  @param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
+	 *	@return  	int						<=0 if OK, 0=Nothing done, >0 if KO
+	 */
+	public function validate($user, $notrigger = 0)
+	{
+		global $conf, $langs;
+
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+		$error = 0;
+
+		// Protection
+		if ($this->status == self::STATUS_VALIDATED) {
+			dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerrenthistory->write))
+		 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerrenthistory->rollerrenthistory_advance->validate))))
+		 {
+		 $this->error='NotEnoughPermissions';
+		 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
+		 return -1;
+		 }*/
+
+		$now = dol_now();
+
+		$this->db->begin();
+
+		// Define new ref
+		if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
+			$num = $this->getNextNumRef();
+		} else {
+			$num = $this->ref;
+		}
+		$this->newref = $num;
+
+		if (!empty($num)) {
+			// Validate
+			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+			$sql .= " SET ref = '".$this->db->escape($num)."',";
+			$sql .= " status = ".self::STATUS_VALIDATED;
+			if (!empty($this->fields['date_validation'])) {
+				$sql .= ", date_validation = '".$this->db->idate($now)."'";
+			}
+			if (!empty($this->fields['fk_user_valid'])) {
+				$sql .= ", fk_user_valid = ".((int) $user->id);
+			}
+			$sql .= " WHERE rowid = ".((int) $this->id);
+
+			dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
+			$resql = $this->db->query($sql);
+			if (!$resql) {
+				dol_print_error($this->db);
+				$this->error = $this->db->lasterror();
+				$error++;
+			}
+
+			if (!$error && !$notrigger) {
+				// Call trigger
+				$result = $this->call_trigger('ROLLERRENTHISTORY_VALIDATE', $user);
+				if ($result < 0) {
+					$error++;
+				}
+				// End call triggers
+			}
+		}
+
+		if (!$error) {
+			$this->oldref = $this->ref;
+
+			// Rename directory if dir was a temporary ref
+			if (preg_match('/^[\(]?PROV/i', $this->ref)) {
+				// Now we rename also files into index
+				$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'rollerrenthistory/".$this->db->escape($this->newref)."'";
+				$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'rollerrenthistory/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+				$resql = $this->db->query($sql);
+				if (!$resql) {
+					$error++; $this->error = $this->db->lasterror();
+				}
+
+				// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+				$oldref = dol_sanitizeFileName($this->ref);
+				$newref = dol_sanitizeFileName($num);
+				$dirsource = $conf->rollerstorage->dir_output.'/rollerrenthistory/'.$oldref;
+				$dirdest = $conf->rollerstorage->dir_output.'/rollerrenthistory/'.$newref;
+				if (!$error && file_exists($dirsource)) {
+					dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
+
+					if (@rename($dirsource, $dirdest)) {
+						dol_syslog("Rename ok");
+						// Rename docs starting with $oldref with $newref
+						$listoffiles = dol_dir_list($conf->rollerstorage->dir_output.'/rollerrenthistory/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+						foreach ($listoffiles as $fileentry) {
+							$dirsource = $fileentry['name'];
+							$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+							$dirsource = $fileentry['path'].'/'.$dirsource;
+							$dirdest = $fileentry['path'].'/'.$dirdest;
+							@rename($dirsource, $dirdest);
+						}
+					}
+				}
+			}
+		}
+
+		// Set new ref and current status
+		if (!$error) {
+			$this->ref = $num;
+			$this->status = self::STATUS_VALIDATED;
+		}
+
+		if (!$error) {
+			$this->db->commit();
+			return 1;
+		} else {
+			$this->db->rollback();
+			return -1;
+		}
+	}
+
+
+	/**
+	 *	Set draft status
+	 *
+	 *	@param	User	$user			Object user that modify
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
+	 *	@return	int						<0 if KO, >0 if OK
+	 */
+	public function setDraft($user, $notrigger = 0)
+	{
+		// Protection
+		if ($this->status <= self::STATUS_DRAFT) {
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->write))
+		 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerstorage_advance->validate))))
+		 {
+		 $this->error='Permission denied';
+		 return -1;
+		 }*/
+
+		return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'ROLLERRENTHISTORY_UNVALIDATE');
+	}
+
+	/**
+	 *	Set cancel status
+	 *
+	 *	@param	User	$user			Object user that modify
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
+	 *	@return	int						<0 if KO, 0=Nothing done, >0 if OK
+	 */
+	public function cancel($user, $notrigger = 0)
+	{
+		// Protection
+		if ($this->status != self::STATUS_VALIDATED) {
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->write))
+		 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerstorage_advance->validate))))
+		 {
+		 $this->error='Permission denied';
+		 return -1;
+		 }*/
+
+		return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'ROLLERRENTHISTORY_CANCEL');
+	}
+
+	/**
+	 *	Set back to validated status
+	 *
+	 *	@param	User	$user			Object user that modify
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
+	 *	@return	int						<0 if KO, 0=Nothing done, >0 if OK
+	 */
+	public function reopen($user, $notrigger = 0)
+	{
+		// Protection
+		if ($this->status == self::STATUS_VALIDATED) {
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->write))
+		 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerstorage_advance->validate))))
+		 {
+		 $this->error='Permission denied';
+		 return -1;
+		 }*/
+
+		return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'ROLLERRENTHISTORY_REOPEN');
+	}
+
+	/**
+	 *  Return a link to the object card (with optionaly the picto)
+	 *
+	 *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+	 *  @param  string  $option                     On what the link point to ('nolink', ...)
+	 *  @param  int     $notooltip                  1=Disable tooltip
+	 *  @param  string  $morecss                    Add more css on link
+	 *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+	 *  @return	string                              String with URL
+	 */
+	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+	{
+		global $conf, $langs, $hookmanager;
+
+		if (!empty($conf->dol_no_mouse_hover)) {
+			$notooltip = 1; // Force disable tooltips
+		}
+
+		$result = '';
+
+		$label = img_picto('', $this->picto).' <u>'.$langs->trans("RollerRentHistory").'</u>';
+		if (isset($this->status)) {
+			$label .= ' '.$this->getLibStatut(5);
+		}
+		$label .= '<br>';
+		$label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
+
+		$url = dol_buildpath('/rollerstorage/rollerrenthistory_card.php', 1).'?id='.$this->id;
+
+		if ($option != 'nolink') {
+			// Add param to save lastsearch_values or not
+			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+				$add_save_lastsearch_values = 1;
+			}
+			if ($url && $add_save_lastsearch_values) {
+				$url .= '&save_lastsearch_values=1';
+			}
+		}
+
+		$linkclose = '';
+		if (empty($notooltip)) {
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+				$label = $langs->trans("ShowRollerRentHistory");
+				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+			}
+			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+		} else {
+			$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+		}
+
+		if ($option == 'nolink' || empty($url)) {
+			$linkstart = '<span';
+		} else {
+			$linkstart = '<a href="'.$url.'"';
+		}
+		$linkstart .= $linkclose.'>';
+		if ($option == 'nolink' || empty($url)) {
+			$linkend = '</span>';
+		} else {
+			$linkend = '</a>';
+		}
+
+		$result .= $linkstart;
+
+		if (empty($this->showphoto_on_popup)) {
+			if ($withpicto) {
+				$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+			}
+		} else {
+			if ($withpicto) {
+				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+				list($class, $module) = explode('@', $this->picto);
+				$upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
+				$filearray = dol_dir_list($upload_dir, "files");
+				$filename = $filearray[0]['name'];
+				if (!empty($filename)) {
+					$pospoint = strpos($filearray[0]['name'], '.');
+
+					$pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
+					if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
+						$result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$module.'" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div></div>';
+					} else {
+						$result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div>';
+					}
+
+					$result .= '</div>';
+				} else {
+					$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+				}
+			}
+		}
+
+		if ($withpicto != 2) {
+			$result .= $this->ref;
+		}
+
+		$result .= $linkend;
+		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+		global $action, $hookmanager;
+		$hookmanager->initHooks(array($this->element.'dao'));
+		$parameters = array('id'=>$this->id, 'getnomurl' => &$result);
+		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+		if ($reshook > 0) {
+			$result = $hookmanager->resPrint;
+		} else {
+			$result .= $hookmanager->resPrint;
+		}
+
+		return $result;
+	}
+
+	/**
+	 *	Return a thumb for kanban views
+	 *
+	 *	@param      string	    $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
+	 *  @return		string								HTML Code for Kanban thumb.
+	 */
+	/*
+	public function getKanbanView($option = '')
+	{
+		$return = '<div class="box-flex-item box-flex-grow-zero">';
+		$return .= '<div class="info-box info-box-sm">';
+		$return .= '<span class="info-box-icon bg-infobox-action">';
+		$return .= img_picto('', $this->picto);
+		$return .= '</span>';
+		$return .= '<div class="info-box-content">';
+		$return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
+		if (property_exists($this, 'label')) {
+			$return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
+		}
+		if (method_exists($this, 'getLibStatut')) {
+			$return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
+		}
+		$return .= '</div>';
+		$return .= '</div>';
+		$return .= '</div>';
+
+		return $return;
+	}
+	*/
+
+	/**
+	 *  Return the label of the status
+	 *
+	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+	 *  @return	string 			       Label of status
+	 */
+	public function getLabelStatus($mode = 0)
+	{
+		return $this->LibStatut($this->status, $mode);
+	}
+
+	/**
+	 *  Return the label of the status
+	 *
+	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+	 *  @return	string 			       Label of status
+	 */
+	public function getLibStatut($mode = 0)
+	{
+		return $this->LibStatut($this->status, $mode);
+	}
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 *  Return the status
+	 *
+	 *  @param	int		$status        Id status
+	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+	 *  @return string 			       Label of status
+	 */
+	public function LibStatut($status, $mode = 0)
+	{
+		// phpcs:enable
+		if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
+			global $langs;
+			//$langs->load("rollerstorage@rollerstorage");
+			$this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
+			$this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
+			$this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
+			$this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
+			$this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
+			$this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
+		}
+
+		$statusType = 'status'.$status;
+		//if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+		if ($status == self::STATUS_CANCELED) {
+			$statusType = 'status6';
+		}
+
+		return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+	}
+
+	/**
+	 *	Load the info information in the object
+	 *
+	 *	@param  int		$id       Id of object
+	 *	@return	void
+	 */
+	public function info($id)
+	{
+		$sql = "SELECT rowid,";
+		$sql .= " date_creation as datec, tms as datem,";
+		$sql .= " fk_user_creat, fk_user_modif";
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
+		$sql .= " WHERE t.rowid = ".((int) $id);
+
+		$result = $this->db->query($sql);
+		if ($result) {
+			if ($this->db->num_rows($result)) {
+				$obj = $this->db->fetch_object($result);
+
+				$this->id = $obj->rowid;
+
+				$this->user_creation_id = $obj->fk_user_creat;
+				$this->user_modification_id = $obj->fk_user_modif;
+				if (!empty($obj->fk_user_valid)) {
+					$this->user_validation_id = $obj->fk_user_valid;
+				}
+				$this->date_creation     = $this->db->jdate($obj->datec);
+				$this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
+				if (!empty($obj->datev)) {
+					$this->date_validation   = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
+				}
+			}
+
+			$this->db->free($result);
+		} else {
+			dol_print_error($this->db);
+		}
+	}
+
+	/**
+	 * Initialise object with example values
+	 * Id must be 0 if object instance is a specimen
+	 *
+	 * @return void
+	 */
+	public function initAsSpecimen()
+	{
+		// Set here init that are not commonf fields
+		// $this->property1 = ...
+		// $this->property2 = ...
+
+		$this->initAsSpecimenCommon();
+	}
+
+	/**
+	 * 	Create an array of lines
+	 *
+	 * 	@return array|int		array of lines if OK, <0 if KO
+	 */
+	public function getLinesArray()
+	{
+		$this->lines = array();
+
+		$objectline = new RollerRentHistoryLine($this->db);
+		$result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_rollerrenthistory = '.((int) $this->id)));
+
+		if (is_numeric($result)) {
+			$this->error = $objectline->error;
+			$this->errors = $objectline->errors;
+			return $result;
+		} else {
+			$this->lines = $result;
+			return $this->lines;
+		}
+	}
+
+	/**
+	 *  Returns the reference to the following non used object depending on the active numbering module.
+	 *
+	 *  @return string      		Object free reference
+	 */
+	public function getNextNumRef()
+	{
+		global $langs, $conf;
+		$langs->load("rollerstorage@rollerstorage");
+
+		if (empty($conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON)) {
+			$conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON = 'mod_rollerrenthistory_standard';
+		}
+
+		if (!empty($conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON)) {
+			$mybool = false;
+
+			$file = $conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON.".php";
+			$classname = $conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON;
+
+			// Include file with class
+			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+			foreach ($dirmodels as $reldir) {
+				$dir = dol_buildpath($reldir."core/modules/rollerstorage/");
+
+				// Load file with numbering class (if found)
+				$mybool |= @include_once $dir.$file;
+			}
+
+			if ($mybool === false) {
+				dol_print_error('', "Failed to include file ".$file);
+				return '';
+			}
+
+			if (class_exists($classname)) {
+				$obj = new $classname();
+				$numref = $obj->getNextValue($this);
+
+				if ($numref != '' && $numref != '-1') {
+					return $numref;
+				} else {
+					$this->error = $obj->error;
+					//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+					return "";
+				}
+			} else {
+				print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
+				return "";
+			}
+		} else {
+			print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+			return "";
+		}
+	}
+
+	/**
+	 *  Create a document onto disk according to template module.
+	 *
+	 *  @param	    string		$modele			Force template to use ('' to not force)
+	 *  @param		Translate	$outputlangs	objet lang a utiliser pour traduction
+	 *  @param      int			$hidedetails    Hide details of lines
+	 *  @param      int			$hidedesc       Hide description
+	 *  @param      int			$hideref        Hide ref
+	 *  @param      null|array  $moreparams     Array to provide more information
+	 *  @return     int         				0 if KO, 1 if OK
+	 */
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+	{
+		global $conf, $langs;
+
+		$result = 0;
+		$includedocgeneration = 0;
+
+		$langs->load("rollerstorage@rollerstorage");
+
+		if (!dol_strlen($modele)) {
+			$modele = 'standard_rollerrenthistory';
+
+			if (!empty($this->model_pdf)) {
+				$modele = $this->model_pdf;
+			} elseif (!empty($conf->global->ROLLERRENTHISTORY_ADDON_PDF)) {
+				$modele = $conf->global->ROLLERRENTHISTORY_ADDON_PDF;
+			}
+		}
+
+		$modelpath = "core/modules/rollerstorage/doc/";
+
+		if ($includedocgeneration && !empty($modele)) {
+			$result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Action executed by scheduler
+	 * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+	 * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+	 *
+	 * @return	int			0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+	 */
+	public function doScheduledJob()
+	{
+		global $conf, $langs;
+
+		//$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+		$error = 0;
+		$this->output = '';
+		$this->error = '';
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$now = dol_now();
+
+		$this->db->begin();
+
+		// ...
+
+		$this->db->commit();
+
+		return $error;
+	}
+}
+
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
+
+/**
+ * Class RollerRentHistoryLine. You can also remove this and generate a CRUD class for lines objects.
+ */
+class RollerRentHistoryLine extends CommonObjectLine
+{
+	// To complete with content of an object RollerRentHistoryLine
+	// We should have a field rowid, fk_rollerrenthistory and position
+
+	/**
+	 * @var int  Does object support extrafields ? 0=No, 1=Yes
+	 */
+	public $isextrafieldmanaged = 0;
+
+	/**
+	 * Constructor
+	 *
+	 * @param DoliDb $db Database handler
+	 */
+	public function __construct(DoliDB $db)
+	{
+		$this->db = $db;
+	}
+}

+ 1118 - 0
custom/rollerstorage/class/rollerrenthistory.class.php.back

@@ -0,0 +1,1118 @@
+<?php
+/* Copyright (C) 2017  Laurent Destailleur <eldy@users.sourceforge.net>
+ * Copyright (C) 2024 László Szollősi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ * \file        class/rollerrenthistory.class.php
+ * \ingroup     rollerstorage
+ * \brief       This file is a CRUD class file for RollerRentHistory (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for RollerRentHistory
+ */
+class RollerRentHistory extends CommonObject
+{
+	/**
+	 * @var string ID of module.
+	 */
+	public $module = 'rollerstorage';
+
+	/**
+	 * @var string ID to identify managed object.
+	 */
+	public $element = 'rollerrenthistory';
+
+	/**
+	 * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+	 */
+	public $table_element = 'rollerstorage_rollerrenthistory';
+
+	/**
+	 * @var int  Does this object support multicompany module ?
+	 * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+	 */
+	public $ismultientitymanaged = 0;
+
+	/**
+	 * @var int  Does object support extrafields ? 0=No, 1=Yes
+	 */
+	public $isextrafieldmanaged = 1;
+
+	/**
+	 * @var string String with name of icon for rollerrenthistory. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'rollerrenthistory@rollerstorage' if picto is file 'img/object_rollerrenthistory.png'.
+	 */
+	public $picto = 'fa-file';
+
+
+	const STATUS_DRAFT = 0;
+	const STATUS_VALIDATED = 1;
+	const STATUS_CANCELED = 9;
+
+
+	/**
+	 *  'type' field format:
+	 *  	'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',
+	 *  	'select' (list of values are in 'options'),
+	 *  	'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]',
+	 *  	'chkbxlst:...',
+	 *  	'varchar(x)',
+	 *  	'text', 'text:none', 'html',
+	 *   	'double(24,8)', 'real', 'price',
+	 *  	'date', 'datetime', 'timestamp', 'duration',
+	 *  	'boolean', 'checkbox', 'radio', 'array',
+	 *  	'mail', 'phone', 'url', 'password', 'ip'
+	 *		Note: Filter must be a Dolibarr filter syntax string. Example: "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.status:!=:0) or (t.nature:is:NULL)"
+	 *  'label' the translation key.
+	 *  'picto' is code of a picto to show before value in forms
+	 *  'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM' or 'isModEnabled("multicurrency")' ...)
+	 *  'position' is the sort order of field.
+	 *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+	 *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+	 *  'noteditable' says if field is not editable (1 or 0)
+	 *  'alwayseditable' says if field can be modified also when status is not draft ('1' or '0')
+	 *  'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+	 *  'index' if we want an index in database.
+	 *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+	 *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+	 *  'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
+	 *  'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
+	 *  'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+	 *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+	 *  'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+	 *  'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
+	 *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+	 *  'comment' is not used. You can store here any text of your choice. It is not used by application.
+	 *	'validate' is 1 if need to validate with $this->validateField()
+	 *  'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
+	 *
+	 *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+	 */
+
+	// BEGIN MODULEBUILDER PROPERTIES
+	/**
+	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+	 */
+	public $fields=array(
+		'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+		'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>'1', 'position'=>10, 'notnull'=>1, 'visible'=>0, 'default'=>'1', 'index'=>1,),
+		'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'validate'=>'1', 'comment'=>"Reference of object"),
+		'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
+		'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
+		'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'picto'=>'user', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid', 'csslist'=>'tdoverflowmax150',),
+		'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'picto'=>'user', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2, 'csslist'=>'tdoverflowmax150',),
+		'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>'1', 'position'=>2000, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Piszkozat', '1'=>'Hiteles&iacute;tve', '9'=>'Megszak&iacute;tva'), 'validate'=>'1',),
+		'event_id' => array('type'=>'integer', 'label'=>'Event', 'enabled'=>'1', 'position'=>512, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
+		'inventory_id' => array('type'=>'integer', 'label'=>'Scooter', 'enabled'=>'1', 'position'=>513, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
+		'facture_id' => array('type'=>'integer', 'label'=>'Facture', 'enabled'=>'1', 'position'=>514, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
+		'ticket_id' => array('type'=>'integer', 'label'=>'Ticket', 'enabled'=>'1', 'position'=>515, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
+		'product_id' => array('type'=>'integer', 'label'=>'Product', 'enabled'=>'1', 'position'=>516, 'notnull'=>0, 'visible'=>1, 'noteditable'=>'1',),
+		'invoice_number' => array('type'=>'varchar(255)', 'label'=>'InvoiceNumber', 'enabled'=>'1', 'position'=>517, 'notnull'=>1, 'visible'=>1, 'noteditable'=>'1',),
+	);
+	public $rowid;
+	public $entity;
+	public $ref;
+	public $date_creation;
+	public $tms;
+	public $fk_user_creat;
+	public $fk_user_modif;
+	public $status;
+	public $event_id;
+	public $inventory_id;
+	public $facture_id;
+	public $ticket_id;
+	public $product_id;
+	public $invoice_number;
+	// END MODULEBUILDER PROPERTIES
+
+
+	// If this object has a subtable with lines
+
+	// /**
+	//  * @var string    Name of subtable line
+	//  */
+	// public $table_element_line = 'rollerstorage_rollerrenthistoryline';
+
+	// /**
+	//  * @var string    Field with ID of parent key if this object has a parent
+	//  */
+	// public $fk_element = 'fk_rollerrenthistory';
+
+	// /**
+	//  * @var string    Name of subtable class that manage subtable lines
+	//  */
+	// public $class_element_line = 'RollerRentHistoryline';
+
+	// /**
+	//  * @var array	List of child tables. To test if we can delete object.
+	//  */
+	// protected $childtables = array();
+
+	// /**
+	//  * @var array    List of child tables. To know object to delete on cascade.
+	//  *               If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+	//  *               call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+	//  */
+	// protected $childtablesoncascade = array('rollerstorage_rollerrenthistorydet');
+
+	// /**
+	//  * @var RollerRentHistoryLine[]     Array of subtable lines
+	//  */
+	// public $lines = array();
+
+
+
+	/**
+	 * Constructor
+	 *
+	 * @param DoliDb $db Database handler
+	 */
+	public function __construct(DoliDB $db)
+	{
+		global $conf, $langs;
+
+		$this->db = $db;
+
+		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
+			$this->fields['rowid']['visible'] = 0;
+		}
+		if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
+			$this->fields['entity']['enabled'] = 0;
+		}
+
+		// Example to show how to set values of fields definition dynamically
+		/*if ($user->rights->rollerstorage->rollerrenthistory->read) {
+			$this->fields['myfield']['visible'] = 1;
+			$this->fields['myfield']['noteditable'] = 0;
+		}*/
+
+		// Unset fields that are disabled
+		foreach ($this->fields as $key => $val) {
+			if (isset($val['enabled']) && empty($val['enabled'])) {
+				unset($this->fields[$key]);
+			}
+		}
+
+		// Translate some data of arrayofkeyval
+		if (is_object($langs)) {
+			foreach ($this->fields as $key => $val) {
+				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+					foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+						$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+					}
+				}
+			}
+		}
+	}
+
+	/**
+	 * Create object into database
+	 *
+	 * @param  User $user      User that creates
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, Id of created object if OK
+	 */
+	public function create(User $user, $notrigger = false)
+	{
+		$resultcreate = $this->createCommon($user, $notrigger);
+
+		//$resultvalidate = $this->validate($user, $notrigger);
+
+		return $resultcreate;
+	}
+
+	/**
+	 * Clone an object into another one
+	 *
+	 * @param  	User 	$user      	User that creates
+	 * @param  	int 	$fromid     Id of object to clone
+	 * @return 	mixed 				New object created, <0 if KO
+	 */
+	public function createFromClone(User $user, $fromid)
+	{
+		global $langs, $extrafields;
+		$error = 0;
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$object = new self($this->db);
+
+		$this->db->begin();
+
+		// Load source object
+		$result = $object->fetchCommon($fromid);
+		if ($result > 0 && !empty($object->table_element_line)) {
+			$object->fetchLines();
+		}
+
+		// get lines so they will be clone
+		//foreach($this->lines as $line)
+		//	$line->fetch_optionals();
+
+		// Reset some properties
+		unset($object->id);
+		unset($object->fk_user_creat);
+		unset($object->import_key);
+
+		// Clear fields
+		if (property_exists($object, 'ref')) {
+			$object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+		}
+		if (property_exists($object, 'label')) {
+			$object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+		}
+		if (property_exists($object, 'status')) {
+			$object->status = self::STATUS_DRAFT;
+		}
+		if (property_exists($object, 'date_creation')) {
+			$object->date_creation = dol_now();
+		}
+		if (property_exists($object, 'date_modification')) {
+			$object->date_modification = null;
+		}
+		// ...
+		// Clear extrafields that are unique
+		if (is_array($object->array_options) && count($object->array_options) > 0) {
+			$extrafields->fetch_name_optionals_label($this->table_element);
+			foreach ($object->array_options as $key => $option) {
+				$shortkey = preg_replace('/options_/', '', $key);
+				if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
+					//var_dump($key);
+					//var_dump($clonedObj->array_options[$key]); exit;
+					unset($object->array_options[$key]);
+				}
+			}
+		}
+
+		// Create clone
+		$object->context['createfromclone'] = 'createfromclone';
+		$result = $object->createCommon($user);
+		if ($result < 0) {
+			$error++;
+			$this->error = $object->error;
+			$this->errors = $object->errors;
+		}
+
+		if (!$error) {
+			// copy internal contacts
+			if ($this->copy_linked_contact($object, 'internal') < 0) {
+				$error++;
+			}
+		}
+
+		if (!$error) {
+			// copy external contacts if same company
+			if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
+				if ($this->copy_linked_contact($object, 'external') < 0) {
+					$error++;
+				}
+			}
+		}
+
+		unset($object->context['createfromclone']);
+
+		// End
+		if (!$error) {
+			$this->db->commit();
+			return $object;
+		} else {
+			$this->db->rollback();
+			return -1;
+		}
+	}
+
+	/**
+	 * Load object in memory from the database
+	 *
+	 * @param int    $id   Id object
+	 * @param string $ref  Ref
+	 * @return int         <0 if KO, 0 if not found, >0 if OK
+	 */
+	public function fetch($id, $ref = null)
+	{
+		$result = $this->fetchCommon($id, $ref);
+		if ($result > 0 && !empty($this->table_element_line)) {
+			$this->fetchLines();
+		}
+		return $result;
+	}
+
+	/**
+	 * Load object lines in memory from the database
+	 *
+	 * @return int         <0 if KO, 0 if not found, >0 if OK
+	 */
+	public function fetchLines()
+	{
+		$this->lines = array();
+
+		$result = $this->fetchLinesCommon();
+		return $result;
+	}
+
+
+	/**
+	 * Load list of objects in memory from the database.
+	 *
+	 * @param  string      $sortorder    Sort Order
+	 * @param  string      $sortfield    Sort field
+	 * @param  int         $limit        limit
+	 * @param  int         $offset       Offset
+	 * @param  array       $filter       Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+	 * @param  string      $filtermode   Filter mode (AND or OR)
+	 * @return array|int                 int <0 if KO, array of pages if OK
+	 */
+	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+	{
+		global $conf;
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$records = array();
+
+		$sql = "SELECT ";
+		$sql .= $this->getFieldList('t');
+		$sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+			$sql .= " WHERE t.entity IN (".getEntity($this->element).")";
+		} else {
+			$sql .= " WHERE 1 = 1";
+		}
+		// Manage filter
+		$sqlwhere = array();
+		if (count($filter) > 0) {
+			foreach ($filter as $key => $value) {
+				if ($key == 't.rowid') {
+					$sqlwhere[] = $key." = ".((int) $value);
+				} elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+					$sqlwhere[] = $key." = '".$this->db->idate($value)."'";
+				} elseif ($key == 'customsql') {
+					$sqlwhere[] = $value;
+				} elseif (strpos($value, '%') === false) {
+					$sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
+				} else {
+					$sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
+				}
+			}
+		}
+		if (count($sqlwhere) > 0) {
+			$sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
+		}
+
+		if (!empty($sortfield)) {
+			$sql .= $this->db->order($sortfield, $sortorder);
+		}
+		if (!empty($limit)) {
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$resql = $this->db->query($sql);
+		if ($resql) {
+			$num = $this->db->num_rows($resql);
+			$i = 0;
+			while ($i < ($limit ? min($limit, $num) : $num)) {
+				$obj = $this->db->fetch_object($resql);
+
+				$record = new self($this->db);
+				$record->setVarsFromFetchObj($obj);
+
+				$records[$record->id] = $record;
+
+				$i++;
+			}
+			$this->db->free($resql);
+
+			return $records;
+		} else {
+			$this->errors[] = 'Error '.$this->db->lasterror();
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+			return -1;
+		}
+	}
+
+	/**
+	 * Update object into database
+	 *
+	 * @param  User $user      User that modifies
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, >0 if OK
+	 */
+	public function update(User $user, $notrigger = false)
+	{
+		return $this->updateCommon($user, $notrigger);
+	}
+
+	/**
+	 * Delete object in database
+	 *
+	 * @param User $user       User that deletes
+	 * @param bool $notrigger  false=launch triggers, true=disable triggers
+	 * @return int             <0 if KO, >0 if OK
+	 */
+	public function delete(User $user, $notrigger = false)
+	{
+		return $this->deleteCommon($user, $notrigger);
+		//return $this->deleteCommon($user, $notrigger, 1);
+	}
+
+	/**
+	 *  Delete a line of object in database
+	 *
+	 *	@param  User	$user       User that delete
+	 *  @param	int		$idline		Id of line to delete
+	 *  @param 	bool 	$notrigger  false=launch triggers after, true=disable triggers
+	 *  @return int         		>0 if OK, <0 if KO
+	 */
+	public function deleteLine(User $user, $idline, $notrigger = false)
+	{
+		if ($this->status < 0) {
+			$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+			return -2;
+		}
+
+		return $this->deleteLineCommon($user, $idline, $notrigger);
+	}
+
+
+	/**
+	 *	Validate object
+	 *
+	 *	@param		User	$user     		User making status change
+	 *  @param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
+	 *	@return  	int						<=0 if OK, 0=Nothing done, >0 if KO
+	 */
+	public function validate($user, $notrigger = 0)
+	{
+		global $conf, $langs;
+
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+		$error = 0;
+
+		// Protection
+		if ($this->status == self::STATUS_VALIDATED) {
+			dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerrenthistory->write))
+		 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerrenthistory->rollerrenthistory_advance->validate))))
+		 {
+		 $this->error='NotEnoughPermissions';
+		 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
+		 return -1;
+		 }*/
+
+		$now = dol_now();
+
+		$this->db->begin();
+
+		// Define new ref
+		if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
+			$num = $this->getNextNumRef();
+		} else {
+			$num = $this->ref;
+		}
+		$this->newref = $num;
+
+		if (!empty($num)) {
+			// Validate
+			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+			$sql .= " SET ref = '".$this->db->escape($num)."',";
+			$sql .= " status = ".self::STATUS_VALIDATED;
+			if (!empty($this->fields['date_validation'])) {
+				$sql .= ", date_validation = '".$this->db->idate($now)."'";
+			}
+			if (!empty($this->fields['fk_user_valid'])) {
+				$sql .= ", fk_user_valid = ".((int) $user->id);
+			}
+			$sql .= " WHERE rowid = ".((int) $this->id);
+
+			dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
+			$resql = $this->db->query($sql);
+			if (!$resql) {
+				dol_print_error($this->db);
+				$this->error = $this->db->lasterror();
+				$error++;
+			}
+
+			if (!$error && !$notrigger) {
+				// Call trigger
+				$result = $this->call_trigger('ROLLERRENTHISTORY_VALIDATE', $user);
+				if ($result < 0) {
+					$error++;
+				}
+				// End call triggers
+			}
+		}
+
+		if (!$error) {
+			$this->oldref = $this->ref;
+
+			// Rename directory if dir was a temporary ref
+			if (preg_match('/^[\(]?PROV/i', $this->ref)) {
+				// Now we rename also files into index
+				$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'rollerrenthistory/".$this->db->escape($this->newref)."'";
+				$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'rollerrenthistory/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+				$resql = $this->db->query($sql);
+				if (!$resql) {
+					$error++; $this->error = $this->db->lasterror();
+				}
+
+				// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+				$oldref = dol_sanitizeFileName($this->ref);
+				$newref = dol_sanitizeFileName($num);
+				$dirsource = $conf->rollerstorage->dir_output.'/rollerrenthistory/'.$oldref;
+				$dirdest = $conf->rollerstorage->dir_output.'/rollerrenthistory/'.$newref;
+				if (!$error && file_exists($dirsource)) {
+					dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
+
+					if (@rename($dirsource, $dirdest)) {
+						dol_syslog("Rename ok");
+						// Rename docs starting with $oldref with $newref
+						$listoffiles = dol_dir_list($conf->rollerstorage->dir_output.'/rollerrenthistory/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+						foreach ($listoffiles as $fileentry) {
+							$dirsource = $fileentry['name'];
+							$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+							$dirsource = $fileentry['path'].'/'.$dirsource;
+							$dirdest = $fileentry['path'].'/'.$dirdest;
+							@rename($dirsource, $dirdest);
+						}
+					}
+				}
+			}
+		}
+
+		// Set new ref and current status
+		if (!$error) {
+			$this->ref = $num;
+			$this->status = self::STATUS_VALIDATED;
+		}
+
+		if (!$error) {
+			$this->db->commit();
+			return 1;
+		} else {
+			$this->db->rollback();
+			return -1;
+		}
+	}
+
+
+	/**
+	 *	Set draft status
+	 *
+	 *	@param	User	$user			Object user that modify
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
+	 *	@return	int						<0 if KO, >0 if OK
+	 */
+	public function setDraft($user, $notrigger = 0)
+	{
+		// Protection
+		if ($this->status <= self::STATUS_DRAFT) {
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->write))
+		 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerstorage_advance->validate))))
+		 {
+		 $this->error='Permission denied';
+		 return -1;
+		 }*/
+
+		return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'ROLLERRENTHISTORY_UNVALIDATE');
+	}
+
+	/**
+	 *	Set cancel status
+	 *
+	 *	@param	User	$user			Object user that modify
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
+	 *	@return	int						<0 if KO, 0=Nothing done, >0 if OK
+	 */
+	public function cancel($user, $notrigger = 0)
+	{
+		// Protection
+		if ($this->status != self::STATUS_VALIDATED) {
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->write))
+		 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerstorage_advance->validate))))
+		 {
+		 $this->error='Permission denied';
+		 return -1;
+		 }*/
+
+		return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'ROLLERRENTHISTORY_CANCEL');
+	}
+
+	/**
+	 *	Set back to validated status
+	 *
+	 *	@param	User	$user			Object user that modify
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
+	 *	@return	int						<0 if KO, 0=Nothing done, >0 if OK
+	 */
+	public function reopen($user, $notrigger = 0)
+	{
+		// Protection
+		if ($this->status == self::STATUS_VALIDATED) {
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->write))
+		 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->rollerstorage->rollerstorage_advance->validate))))
+		 {
+		 $this->error='Permission denied';
+		 return -1;
+		 }*/
+
+		return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'ROLLERRENTHISTORY_REOPEN');
+	}
+
+	/**
+	 *  Return a link to the object card (with optionaly the picto)
+	 *
+	 *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+	 *  @param  string  $option                     On what the link point to ('nolink', ...)
+	 *  @param  int     $notooltip                  1=Disable tooltip
+	 *  @param  string  $morecss                    Add more css on link
+	 *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+	 *  @return	string                              String with URL
+	 */
+	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+	{
+		global $conf, $langs, $hookmanager;
+
+		if (!empty($conf->dol_no_mouse_hover)) {
+			$notooltip = 1; // Force disable tooltips
+		}
+
+		$result = '';
+
+		$label = img_picto('', $this->picto).' <u>'.$langs->trans("RollerRentHistory").'</u>';
+		if (isset($this->status)) {
+			$label .= ' '.$this->getLibStatut(5);
+		}
+		$label .= '<br>';
+		$label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
+
+		$url = dol_buildpath('/rollerstorage/rollerrenthistory_card.php', 1).'?id='.$this->id;
+
+		if ($option != 'nolink') {
+			// Add param to save lastsearch_values or not
+			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+				$add_save_lastsearch_values = 1;
+			}
+			if ($url && $add_save_lastsearch_values) {
+				$url .= '&save_lastsearch_values=1';
+			}
+		}
+
+		$linkclose = '';
+		if (empty($notooltip)) {
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+				$label = $langs->trans("ShowRollerRentHistory");
+				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+			}
+			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+		} else {
+			$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+		}
+
+		if ($option == 'nolink' || empty($url)) {
+			$linkstart = '<span';
+		} else {
+			$linkstart = '<a href="'.$url.'"';
+		}
+		$linkstart .= $linkclose.'>';
+		if ($option == 'nolink' || empty($url)) {
+			$linkend = '</span>';
+		} else {
+			$linkend = '</a>';
+		}
+
+		$result .= $linkstart;
+
+		if (empty($this->showphoto_on_popup)) {
+			if ($withpicto) {
+				$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+			}
+		} else {
+			if ($withpicto) {
+				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+				list($class, $module) = explode('@', $this->picto);
+				$upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
+				$filearray = dol_dir_list($upload_dir, "files");
+				$filename = $filearray[0]['name'];
+				if (!empty($filename)) {
+					$pospoint = strpos($filearray[0]['name'], '.');
+
+					$pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
+					if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
+						$result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$module.'" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div></div>';
+					} else {
+						$result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div>';
+					}
+
+					$result .= '</div>';
+				} else {
+					$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+				}
+			}
+		}
+
+		if ($withpicto != 2) {
+			$result .= $this->ref;
+		}
+
+		$result .= $linkend;
+		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+		global $action, $hookmanager;
+		$hookmanager->initHooks(array($this->element.'dao'));
+		$parameters = array('id'=>$this->id, 'getnomurl' => &$result);
+		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+		if ($reshook > 0) {
+			$result = $hookmanager->resPrint;
+		} else {
+			$result .= $hookmanager->resPrint;
+		}
+
+		return $result;
+	}
+
+	/**
+	 *	Return a thumb for kanban views
+	 *
+	 *	@param      string	    $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
+	 *  @return		string								HTML Code for Kanban thumb.
+	 */
+	/*
+	public function getKanbanView($option = '')
+	{
+		$return = '<div class="box-flex-item box-flex-grow-zero">';
+		$return .= '<div class="info-box info-box-sm">';
+		$return .= '<span class="info-box-icon bg-infobox-action">';
+		$return .= img_picto('', $this->picto);
+		$return .= '</span>';
+		$return .= '<div class="info-box-content">';
+		$return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
+		if (property_exists($this, 'label')) {
+			$return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
+		}
+		if (method_exists($this, 'getLibStatut')) {
+			$return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
+		}
+		$return .= '</div>';
+		$return .= '</div>';
+		$return .= '</div>';
+
+		return $return;
+	}
+	*/
+
+	/**
+	 *  Return the label of the status
+	 *
+	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+	 *  @return	string 			       Label of status
+	 */
+	public function getLabelStatus($mode = 0)
+	{
+		return $this->LibStatut($this->status, $mode);
+	}
+
+	/**
+	 *  Return the label of the status
+	 *
+	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+	 *  @return	string 			       Label of status
+	 */
+	public function getLibStatut($mode = 0)
+	{
+		return $this->LibStatut($this->status, $mode);
+	}
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 *  Return the status
+	 *
+	 *  @param	int		$status        Id status
+	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+	 *  @return string 			       Label of status
+	 */
+	public function LibStatut($status, $mode = 0)
+	{
+		// phpcs:enable
+		if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
+			global $langs;
+			//$langs->load("rollerstorage@rollerstorage");
+			$this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
+			$this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
+			$this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
+			$this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
+			$this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
+			$this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
+		}
+
+		$statusType = 'status'.$status;
+		//if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+		if ($status == self::STATUS_CANCELED) {
+			$statusType = 'status6';
+		}
+
+		return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+	}
+
+	/**
+	 *	Load the info information in the object
+	 *
+	 *	@param  int		$id       Id of object
+	 *	@return	void
+	 */
+	public function info($id)
+	{
+		$sql = "SELECT rowid,";
+		$sql .= " date_creation as datec, tms as datem,";
+		$sql .= " fk_user_creat, fk_user_modif";
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
+		$sql .= " WHERE t.rowid = ".((int) $id);
+
+		$result = $this->db->query($sql);
+		if ($result) {
+			if ($this->db->num_rows($result)) {
+				$obj = $this->db->fetch_object($result);
+
+				$this->id = $obj->rowid;
+
+				$this->user_creation_id = $obj->fk_user_creat;
+				$this->user_modification_id = $obj->fk_user_modif;
+				if (!empty($obj->fk_user_valid)) {
+					$this->user_validation_id = $obj->fk_user_valid;
+				}
+				$this->date_creation     = $this->db->jdate($obj->datec);
+				$this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
+				if (!empty($obj->datev)) {
+					$this->date_validation   = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
+				}
+			}
+
+			$this->db->free($result);
+		} else {
+			dol_print_error($this->db);
+		}
+	}
+
+	/**
+	 * Initialise object with example values
+	 * Id must be 0 if object instance is a specimen
+	 *
+	 * @return void
+	 */
+	public function initAsSpecimen()
+	{
+		// Set here init that are not commonf fields
+		// $this->property1 = ...
+		// $this->property2 = ...
+
+		$this->initAsSpecimenCommon();
+	}
+
+	/**
+	 * 	Create an array of lines
+	 *
+	 * 	@return array|int		array of lines if OK, <0 if KO
+	 */
+	public function getLinesArray()
+	{
+		$this->lines = array();
+
+		$objectline = new RollerRentHistoryLine($this->db);
+		$result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_rollerrenthistory = '.((int) $this->id)));
+
+		if (is_numeric($result)) {
+			$this->error = $objectline->error;
+			$this->errors = $objectline->errors;
+			return $result;
+		} else {
+			$this->lines = $result;
+			return $this->lines;
+		}
+	}
+
+	/**
+	 *  Returns the reference to the following non used object depending on the active numbering module.
+	 *
+	 *  @return string      		Object free reference
+	 */
+	public function getNextNumRef()
+	{
+		global $langs, $conf;
+		$langs->load("rollerstorage@rollerstorage");
+
+		if (empty($conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON)) {
+			$conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON = 'mod_rollerrenthistory_standard';
+		}
+
+		if (!empty($conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON)) {
+			$mybool = false;
+
+			$file = $conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON.".php";
+			$classname = $conf->global->ROLLERSTORAGE_ROLLERRENTHISTORY_ADDON;
+
+			// Include file with class
+			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+			foreach ($dirmodels as $reldir) {
+				$dir = dol_buildpath($reldir."core/modules/rollerstorage/");
+
+				// Load file with numbering class (if found)
+				$mybool |= @include_once $dir.$file;
+			}
+
+			if ($mybool === false) {
+				dol_print_error('', "Failed to include file ".$file);
+				return '';
+			}
+
+			if (class_exists($classname)) {
+				$obj = new $classname();
+				$numref = $obj->getNextValue($this);
+
+				if ($numref != '' && $numref != '-1') {
+					return $numref;
+				} else {
+					$this->error = $obj->error;
+					//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+					return "";
+				}
+			} else {
+				print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
+				return "";
+			}
+		} else {
+			print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+			return "";
+		}
+	}
+
+	/**
+	 *  Create a document onto disk according to template module.
+	 *
+	 *  @param	    string		$modele			Force template to use ('' to not force)
+	 *  @param		Translate	$outputlangs	objet lang a utiliser pour traduction
+	 *  @param      int			$hidedetails    Hide details of lines
+	 *  @param      int			$hidedesc       Hide description
+	 *  @param      int			$hideref        Hide ref
+	 *  @param      null|array  $moreparams     Array to provide more information
+	 *  @return     int         				0 if KO, 1 if OK
+	 */
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+	{
+		global $conf, $langs;
+
+		$result = 0;
+		$includedocgeneration = 0;
+
+		$langs->load("rollerstorage@rollerstorage");
+
+		if (!dol_strlen($modele)) {
+			$modele = 'standard_rollerrenthistory';
+
+			if (!empty($this->model_pdf)) {
+				$modele = $this->model_pdf;
+			} elseif (!empty($conf->global->ROLLERRENTHISTORY_ADDON_PDF)) {
+				$modele = $conf->global->ROLLERRENTHISTORY_ADDON_PDF;
+			}
+		}
+
+		$modelpath = "core/modules/rollerstorage/doc/";
+
+		if ($includedocgeneration && !empty($modele)) {
+			$result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Action executed by scheduler
+	 * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+	 * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+	 *
+	 * @return	int			0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+	 */
+	public function doScheduledJob()
+	{
+		global $conf, $langs;
+
+		//$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+		$error = 0;
+		$this->output = '';
+		$this->error = '';
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$now = dol_now();
+
+		$this->db->begin();
+
+		// ...
+
+		$this->db->commit();
+
+		return $error;
+	}
+}
+
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
+
+/**
+ * Class RollerRentHistoryLine. You can also remove this and generate a CRUD class for lines objects.
+ */
+class RollerRentHistoryLine extends CommonObjectLine
+{
+	// To complete with content of an object RollerRentHistoryLine
+	// We should have a field rowid, fk_rollerrenthistory and position
+
+	/**
+	 * @var int  Does object support extrafields ? 0=No, 1=Yes
+	 */
+	public $isextrafieldmanaged = 0;
+
+	/**
+	 * Constructor
+	 *
+	 * @param DoliDb $db Database handler
+	 */
+	public function __construct(DoliDB $db)
+	{
+		$this->db = $db;
+	}
+}

+ 110 - 0
custom/rollerstorage/lib/rollerstorage_rollerrenthistory.lib.php

@@ -0,0 +1,110 @@
+<?php
+/* Copyright (C) 2024 László Szollősi
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ * \file    lib/rollerstorage_rollerrenthistory.lib.php
+ * \ingroup rollerstorage
+ * \brief   Library files with common functions for RollerRentHistory
+ */
+
+/**
+ * Prepare array of tabs for RollerRentHistory
+ *
+ * @param	RollerRentHistory	$object		RollerRentHistory
+ * @return 	array					Array of tabs
+ */
+function rollerrenthistoryPrepareHead($object)
+{
+	global $db, $langs, $conf;
+
+	$langs->load("rollerstorage@rollerstorage");
+
+	$showtabofpagecontact = 1;
+	$showtabofpagenote = 1;
+	$showtabofpagedocument = 1;
+	$showtabofpageagenda = 1;
+
+	$h = 0;
+	$head = array();
+
+	$head[$h][0] = dol_buildpath("/rollerstorage/rollerrenthistory_card.php", 1).'?id='.$object->id;
+	$head[$h][1] = $langs->trans("Card");
+	$head[$h][2] = 'card';
+	$h++;
+
+	if ($showtabofpagecontact) {
+		$head[$h][0] = dol_buildpath("/rollerstorage/rollerrenthistory_contact.php", 1).'?id='.$object->id;
+		$head[$h][1] = $langs->trans("Contacts");
+		$head[$h][2] = 'contact';
+		$h++;
+	}
+
+	if ($showtabofpagenote) {
+		if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) {
+			$nbNote = 0;
+			if (!empty($object->note_private)) {
+				$nbNote++;
+			}
+			if (!empty($object->note_public)) {
+				$nbNote++;
+			}
+			$head[$h][0] = dol_buildpath('/rollerstorage/rollerrenthistory_note.php', 1).'?id='.$object->id;
+			$head[$h][1] = $langs->trans('Notes');
+			if ($nbNote > 0) {
+				$head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : '');
+			}
+			$head[$h][2] = 'note';
+			$h++;
+		}
+	}
+
+	if ($showtabofpagedocument) {
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+		require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
+		$upload_dir = $conf->rollerstorage->dir_output."/rollerrenthistory/".dol_sanitizeFileName($object->ref);
+		$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
+		$nbLinks = Link::count($db, $object->element, $object->id);
+		$head[$h][0] = dol_buildpath("/rollerstorage/rollerrenthistory_document.php", 1).'?id='.$object->id;
+		$head[$h][1] = $langs->trans('Documents');
+		if (($nbFiles + $nbLinks) > 0) {
+			$head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';
+		}
+		$head[$h][2] = 'document';
+		$h++;
+	}
+
+	if ($showtabofpageagenda) {
+		$head[$h][0] = dol_buildpath("/rollerstorage/rollerrenthistory_agenda.php", 1).'?id='.$object->id;
+		$head[$h][1] = $langs->trans("Events");
+		$head[$h][2] = 'agenda';
+		$h++;
+	}
+
+	// Show more tabs from modules
+	// Entries must be declared in modules descriptor with line
+	//$this->tabs = array(
+	//	'entity:+tabname:Title:@rollerstorage:/rollerstorage/mypage.php?id=__ID__'
+	//); // to add new tab
+	//$this->tabs = array(
+	//	'entity:-tabname:Title:@rollerstorage:/rollerstorage/mypage.php?id=__ID__'
+	//); // to remove a tab
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'rollerrenthistory@rollerstorage');
+
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'rollerrenthistory@rollerstorage', 'remove');
+
+	return $head;
+}

+ 321 - 0
custom/rollerstorage/rollerrenthistory_agenda.php

@@ -0,0 +1,321 @@
+<?php
+/* Copyright (C) 2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2024 László Szollősi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *  \file       rollerrenthistory_agenda.php
+ *  \ingroup    rollerstorage
+ *  \brief      Tab of events on RollerRentHistory
+ */
+
+//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
+//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
+//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
+//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
+//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
+//if (! defined("MAIN_SECURITY_FORCECSP"))   define('MAIN_SECURITY_FORCECSP', 'none');	// Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+	$i--; $j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
+	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
+	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) {
+	$res = @include "../main.inc.php";
+}
+if (!$res && file_exists("../../main.inc.php")) {
+	$res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+	$res = @include "../../../main.inc.php";
+}
+if (!$res) {
+	die("Include of main fails");
+}
+
+require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+dol_include_once('/rollerstorage/class/rollerrenthistory.class.php');
+dol_include_once('/rollerstorage/lib/rollerstorage_rollerrenthistory.lib.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("rollerstorage@rollerstorage", "other"));
+
+// Get parameters
+$id = GETPOST('id', 'int');
+$ref = GETPOST('ref', 'alpha');
+$action = GETPOST('action', 'aZ09');
+$cancel = GETPOST('cancel', 'aZ09');
+$backtopage = GETPOST('backtopage', 'alpha');
+
+if (GETPOST('actioncode', 'array')) {
+	$actioncode = GETPOST('actioncode', 'array', 3);
+	if (!count($actioncode)) {
+		$actioncode = '0';
+	}
+} else {
+	$actioncode = GETPOST("actioncode", "alpha", 3) ? GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
+}
+$search_rowid = GETPOST('search_rowid');
+$search_agenda_label = GETPOST('search_agenda_label');
+
+$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
+$sortfield = GETPOST('sortfield', 'aZ09comma');
+$sortorder = GETPOST('sortorder', 'aZ09comma');
+$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
+$offset = $limit * $page;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+if (!$sortfield) {
+	$sortfield = 'a.datep,a.id';
+}
+if (!$sortorder) {
+	$sortorder = 'DESC,DESC';
+}
+
+// Initialize technical objects
+$object = new RollerRentHistory($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->rollerstorage->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('rollerrenthistoryagenda', 'globalcard')); // Note that conf->hooks_modules contains array
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->rollerstorage->multidir_output[!empty($object->entity) ? $object->entity : $conf->entity]."/".$object->id;
+}
+
+// There is several ways to check permission.
+// Set $enablepermissioncheck to 1 to enable a minimum low level of checks
+$enablepermissioncheck = 0;
+if ($enablepermissioncheck) {
+	$permissiontoread = $user->rights->rollerstorage->rollerrenthistory->read;
+	$permissiontoadd = $user->rights->rollerstorage->rollerrenthistory->write;
+} else {
+	$permissiontoread = 1;
+	$permissiontoadd = 1;
+}
+
+// Security check (enable the most restrictive one)
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
+//restrictedArea($user, $object->module, $object->id, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft);
+if (!isModEnabled("rollerstorage")) {
+	accessforbidden();
+}
+if (!$permissiontoread) accessforbidden();
+
+
+/*
+ *  Actions
+ */
+
+$parameters = array('id'=>$id);
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
+
+if (empty($reshook)) {
+	// Cancel
+	if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
+		header("Location: ".$backtopage);
+		exit;
+	}
+
+	// Purge search criteria
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
+		$actioncode = '';
+		$search_agenda_label = '';
+	}
+}
+
+
+
+/*
+ *	View
+ */
+
+$form = new Form($db);
+
+if ($object->id > 0) {
+	$title = $langs->trans("Agenda");
+	//if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title;
+	$help_url = 'EN:Module_Agenda_En';
+	llxHeader('', $title, $help_url);
+
+	if (isModEnabled('notification')) {
+		$langs->load("mails");
+	}
+	$head = rollerrenthistoryPrepareHead($object);
+
+
+	print dol_get_fiche_head($head, 'agenda', $langs->trans("RollerRentHistory"), -1, $object->picto);
+
+	// Object card
+	// ------------------------------------------------------------
+	$linkback = '<a href="'.dol_buildpath('/rollerstorage/rollerrenthistory_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	/*
+	// Ref customer
+	$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
+	$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
+	// Thirdparty
+	$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
+	// Project
+	if (!empty($conf->project->enabled)) {
+		$langs->load("projects");
+		$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+		if ($permissiontoadd) {
+			if ($action != 'classify') {
+				//$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token='.newToken().'&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+			}
+			$morehtmlref.=' : ';
+			if ($action == 'classify') {
+				//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+				$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+				$morehtmlref.='<input type="hidden" name="action" value="classin">';
+				$morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
+				$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+				$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+				$morehtmlref.='</form>';
+			} else {
+				$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+			}
+		} else {
+			if (!empty($object->fk_project)) {
+				$proj = new Project($db);
+				$proj->fetch($object->fk_project);
+				$morehtmlref .= ': '.$proj->getNomUrl();
+			} else {
+				$morehtmlref .= '';
+			}
+		}
+	}*/
+	$morehtmlref .= '</div>';
+
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+	print '<div class="fichecenter">';
+	print '<div class="underbanner clearboth"></div>';
+
+	$object->info($object->id);
+	dol_print_object_info($object, 1);
+
+	print '</div>';
+
+	print dol_get_fiche_end();
+
+
+
+	// Actions buttons
+
+	$objthirdparty = $object;
+	$objcon = new stdClass();
+
+	$out = '&origin='.urlencode($object->element.'@'.$object->module).'&originid='.urlencode($object->id);
+	$urlbacktopage = $_SERVER['PHP_SELF'].'?id='.$object->id;
+	$out .= '&backtopage='.urlencode($urlbacktopage);
+	$permok = $user->rights->agenda->myactions->create;
+	if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) {
+		//$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create';
+		if (get_class($objthirdparty) == 'Societe') {
+			$out .= '&socid='.urlencode($objthirdparty->id);
+		}
+		$out .= (!empty($objcon->id) ? '&contactid='.urlencode($objcon->id) : '').'&percentage=-1';
+		//$out.=$langs->trans("AddAnAction").' ';
+		//$out.=img_picto($langs->trans("AddAnAction"),'filenew');
+		//$out.="</a>";
+	}
+
+	$morehtmlright = '';
+
+	//$messagingUrl = DOL_URL_ROOT.'/societe/messaging.php?socid='.$object->id;
+	//$morehtmlright .= dolGetButtonTitle($langs->trans('ShowAsConversation'), '', 'fa fa-comments imgforviewmode', $messagingUrl, '', 1);
+	//$messagingUrl = DOL_URL_ROOT.'/societe/agenda.php?socid='.$object->id;
+	//$morehtmlright .= dolGetButtonTitle($langs->trans('MessageListViewType'), '', 'fa fa-bars imgforviewmode', $messagingUrl, '', 2);
+
+	if (isModEnabled('agenda')) {
+		if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) {
+			$morehtmlright .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out);
+		} else {
+			$morehtmlright .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out, '', 0);
+		}
+	}
+
+
+	if (isModEnabled('agenda') && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
+		print '<br>';
+
+		$param = '&id='.$object->id.(!empty($socid) ? '&socid='.$socid : '');
+		if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+			$param .= '&contextpage='.urlencode($contextpage);
+		}
+		if ($limit > 0 && $limit != $conf->liste_limit) {
+			$param .= '&limit='.urlencode($limit);
+		}
+
+		//print load_fiche_titre($langs->trans("ActionsOnRollerRentHistory"), '', '');
+		print_barre_liste($langs->trans("ActionsOnRollerRentHistory"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlright, '', 0, 1, 1);
+
+		// List of all actions
+		$filters = array();
+		$filters['search_agenda_label'] = $search_agenda_label;
+		$filters['search_rowid'] = $search_rowid;
+
+		// TODO Replace this with same code than into list.php
+		show_actions_done($conf, $langs, $db, $object, null, 0, $actioncode, '', $filters, $sortfield, $sortorder, $object->module);
+	}
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 621 - 0
custom/rollerstorage/rollerrenthistory_card.php

@@ -0,0 +1,621 @@
+<?php
+/* Copyright (C) 2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2024 László Szollősi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *   	\file       rollerrenthistory_card.php
+ *		\ingroup    rollerstorage
+ *		\brief      Page to create/edit/view rollerrenthistory
+ */
+
+//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
+//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
+//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
+//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
+//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
+//if (! defined("MAIN_SECURITY_FORCECSP"))   define('MAIN_SECURITY_FORCECSP', 'none');	// Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
+//if (! defined('NOSESSION'))     		     define('NOSESSION', '1');				    // Disable session
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+	$i--; $j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
+	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
+	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) {
+	$res = @include "../main.inc.php";
+}
+if (!$res && file_exists("../../main.inc.php")) {
+	$res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+	$res = @include "../../../main.inc.php";
+}
+if (!$res) {
+	die("Include of main fails");
+}
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
+dol_include_once('/rollerstorage/class/rollerrenthistory.class.php');
+dol_include_once('/rollerstorage/lib/rollerstorage_rollerrenthistory.lib.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("rollerstorage@rollerstorage", "other"));
+
+// Get parameters
+$id = GETPOST('id', 'int');
+$ref = GETPOST('ref', 'alpha');
+$lineid   = GETPOST('lineid', 'int');
+
+$action = GETPOST('action', 'aZ09');
+$confirm = GETPOST('confirm', 'alpha');
+$cancel = GETPOST('cancel', 'aZ09');
+$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)).basename(__FILE__, '.php')); // To manage different context of search
+$backtopage = GETPOST('backtopage', 'alpha');
+$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha');
+$dol_openinpopup = GETPOST('dol_openinpopup', 'aZ09');
+
+// Initialize technical objects
+$object = new RollerRentHistory($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->rollerstorage->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('rollerrenthistorycard', 'globalcard')); // Note that conf->hooks_modules contains array
+
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+
+// Initialize array of search criterias
+$search_all = GETPOST("search_all", 'alpha');
+$search = array();
+foreach ($object->fields as $key => $val) {
+	if (GETPOST('search_'.$key, 'alpha')) {
+		$search[$key] = GETPOST('search_'.$key, 'alpha');
+	}
+}
+
+if (empty($action) && empty($id) && empty($ref)) {
+	$action = 'view';
+}
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
+
+// There is several ways to check permission.
+// Set $enablepermissioncheck to 1 to enable a minimum low level of checks
+$enablepermissioncheck = 0;
+if ($enablepermissioncheck) {
+	$permissiontoread = $user->hasRight('rollerstorage', 'rollerrenthistory', 'read');
+	$permissiontoadd = $user->hasRight('rollerstorage', 'rollerrenthistory', 'write'); // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
+	$permissiontodelete = $user->hasRight('rollerstorage', 'rollerrenthistory', 'delete') || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT);
+	$permissionnote = $user->hasRight('rollerstorage', 'rollerrenthistory', 'write'); // Used by the include of actions_setnotes.inc.php
+	$permissiondellink = $user->hasRight('rollerstorage', 'rollerrenthistory', 'write'); // Used by the include of actions_dellink.inc.php
+} else {
+	$permissiontoread = 1;
+	$permissiontoadd = 1; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
+	$permissiontodelete = 1;
+	$permissionnote = 1;
+	$permissiondellink = 1;
+}
+
+$upload_dir = $conf->rollerstorage->multidir_output[isset($object->entity) ? $object->entity : 1].'/rollerrenthistory';
+
+// Security check (enable the most restrictive one)
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$isdraft = (isset($object->status) && ($object->status == $object::STATUS_DRAFT) ? 1 : 0);
+//restrictedArea($user, $object->module, $object->id, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft);
+if (!isModEnabled("rollerstorage")) {
+	accessforbidden();
+}
+if (!$permissiontoread) {
+	accessforbidden();
+}
+
+
+/*
+ * Actions
+ */
+
+$parameters = array();
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
+
+if (empty($reshook)) {
+	$error = 0;
+
+	$backurlforlist = dol_buildpath('/rollerstorage/rollerrenthistory_list.php', 1);
+
+	if (empty($backtopage) || ($cancel && empty($id))) {
+		if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
+			if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
+				$backtopage = $backurlforlist;
+			} else {
+				$backtopage = dol_buildpath('/rollerstorage/rollerrenthistory_card.php', 1).'?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
+			}
+		}
+	}
+
+	$triggermodname = 'ROLLERSTORAGE_ROLLERRENTHISTORY_MODIFY'; // Name of trigger action code to execute when we modify record
+
+	// Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen
+	include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
+
+	// Actions when linking object each other
+	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
+
+	// Actions when printing a doc from card
+	include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
+
+	// Action to move up and down lines of object
+	//include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php';
+
+	// Action to build doc
+	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
+
+	if ($action == 'set_thirdparty' && $permissiontoadd) {
+		$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, $triggermodname);
+	}
+	if ($action == 'classin' && $permissiontoadd) {
+		$object->setProject(GETPOST('projectid', 'int'));
+	}
+
+	// Actions to send emails
+	$triggersendname = 'ROLLERSTORAGE_ROLLERRENTHISTORY_SENTBYMAIL';
+	$autocopy = 'MAIN_MAIL_AUTOCOPY_ROLLERRENTHISTORY_TO';
+	$trackid = 'rollerrenthistory'.$object->id;
+	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
+}
+
+
+
+
+/*
+ * View
+ *
+ * Put here all code to build page
+ */
+
+$form = new Form($db);
+$formfile = new FormFile($db);
+$formproject = new FormProjets($db);
+
+$title = $langs->trans("RollerRentHistory");
+$help_url = '';
+llxHeader('', $title, $help_url);
+
+// Example : Adding jquery code
+// print '<script type="text/javascript">
+// jQuery(document).ready(function() {
+// 	function init_myfunc()
+// 	{
+// 		jQuery("#myid").removeAttr(\'disabled\');
+// 		jQuery("#myid").attr(\'disabled\',\'disabled\');
+// 	}
+// 	init_myfunc();
+// 	jQuery("#mybutton").click(function() {
+// 		init_myfunc();
+// 	});
+// });
+// </script>';
+
+
+// Part to create
+if ($action == 'create') {
+	if (empty($permissiontoadd)) {
+		accessforbidden('NotEnoughPermissions', 0, 1);
+	}
+
+	print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("RollerRentHistory")), '', 'object_'.$object->picto);
+
+	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="action" value="add">';
+	if ($backtopage) {
+		print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
+	}
+	if ($backtopageforcancel) {
+		print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	}
+
+	print dol_get_fiche_head(array(), '');
+
+	// Set some default values
+	//if (! GETPOSTISSET('fieldname')) $_POST['fieldname'] = 'myvalue';
+
+	print '<table class="border centpercent tableforfieldcreate">'."\n";
+
+	// Common attributes
+	include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php';
+
+	// Other attributes
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
+
+	print '</table>'."\n";
+
+	print dol_get_fiche_end();
+
+	print $form->buttonsSaveCancel("Create");
+
+	print '</form>';
+
+	//dol_set_focus('input[name="ref"]');
+}
+
+// Part to edit record
+if (($id || $ref) && $action == 'edit') {
+	print load_fiche_titre($langs->trans("RollerRentHistory"), '', 'object_'.$object->picto);
+
+	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="action" value="update">';
+	print '<input type="hidden" name="id" value="'.$object->id.'">';
+	if ($backtopage) {
+		print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
+	}
+	if ($backtopageforcancel) {
+		print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	}
+
+	print dol_get_fiche_head();
+
+	print '<table class="border centpercent tableforfieldedit">'."\n";
+
+	// Common attributes
+	include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php';
+
+	// Other attributes
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php';
+
+	print '</table>';
+
+	print dol_get_fiche_end();
+
+	print $form->buttonsSaveCancel();
+
+	print '</form>';
+}
+
+// Part to show record
+if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
+	$head = rollerrenthistoryPrepareHead($object);
+
+	print dol_get_fiche_head($head, 'card', $langs->trans("RollerRentHistory"), -1, $object->picto);
+
+	$formconfirm = '';
+
+	// Confirmation to delete
+	if ($action == 'delete') {
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteRollerRentHistory'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1);
+	}
+	// Confirmation to delete line
+	if ($action == 'deleteline') {
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
+	}
+
+	// Clone confirmation
+	if ($action == 'clone') {
+		// Create an array for form
+		$formquestion = array();
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
+	}
+
+	// Confirmation of action xxxx (You can use it for xxx = 'close', xxx = 'reopen', ...)
+	if ($action == 'xxx') {
+		$text = $langs->trans('ConfirmActionRollerRentHistory', $object->ref);
+		/*if (isModEnabled('notification'))
+		{
+			require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php';
+			$notify = new Notify($db);
+			$text .= '<br>';
+			$text .= $notify->confirmMessage('ROLLERRENTHISTORY_CLOSE', $object->socid, $object);
+		}*/
+
+		$formquestion = array();
+
+		/*
+		$forcecombo=0;
+		if ($conf->browser->name == 'ie') $forcecombo = 1;	// There is a bug in IE10 that make combo inside popup crazy
+		$formquestion = array(
+			// 'text' => $langs->trans("ConfirmClone"),
+			// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
+			// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
+			// array('type' => 'other',    'name' => 'idwarehouse',   'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
+		);
+		*/
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220);
+	}
+
+	// Call Hook formConfirm
+	$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
+	$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	if (empty($reshook)) {
+		$formconfirm .= $hookmanager->resPrint;
+	} elseif ($reshook > 0) {
+		$formconfirm = $hookmanager->resPrint;
+	}
+
+	// Print form confirm
+	print $formconfirm;
+
+
+	// Object card
+	// ------------------------------------------------------------
+	$linkback = '<a href="'.dol_buildpath('/rollerstorage/rollerrenthistory_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	/*
+		// Ref customer
+		$morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1);
+		$morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string'.(isset($conf->global->THIRDPARTY_REF_INPUT_SIZE) ? ':'.$conf->global->THIRDPARTY_REF_INPUT_SIZE : ''), '', null, null, '', 1);
+		// Thirdparty
+		$morehtmlref .= '<br>'.$object->thirdparty->getNomUrl(1, 'customer');
+		if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
+			$morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$object->thirdparty->id.'&search_societe='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)';
+		}
+		// Project
+		if (isModEnabled('project')) {
+			$langs->load("projects");
+			$morehtmlref .= '<br>';
+			if ($permissiontoadd) {
+				$morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
+				if ($action != 'classify') {
+					$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
+				}
+				$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
+			} else {
+				if (!empty($object->fk_project)) {
+					$proj = new Project($db);
+					$proj->fetch($object->fk_project);
+					$morehtmlref .= $proj->getNomUrl(1);
+					if ($proj->title) {
+						$morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
+					}
+				}
+			}
+		}
+	*/
+	$morehtmlref .= '</div>';
+
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+
+	print '<div class="fichecenter">';
+	print '<div class="fichehalfleft">';
+	print '<div class="underbanner clearboth"></div>';
+	print '<table class="border centpercent tableforfield">'."\n";
+
+	// Common attributes
+	//$keyforbreak='fieldkeytoswitchonsecondcolumn';	// We change column just before this field
+	//unset($object->fields['fk_project']);				// Hide field already shown in banner
+	//unset($object->fields['fk_soc']);					// Hide field already shown in banner
+	include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
+
+	// Other attributes. Fields from hook formObjectOptions and Extrafields.
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
+
+	print '</table>';
+	print '</div>';
+	print '</div>';
+
+	print '<div class="clearboth"></div>';
+
+	print dol_get_fiche_end();
+
+
+	/*
+	 * Lines
+	 */
+
+	if (!empty($object->table_element_line)) {
+		// Show object lines
+		$result = $object->getLinesArray();
+
+		print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">
+		<input type="hidden" name="token" value="' . newToken().'">
+		<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
+		<input type="hidden" name="mode" value="">
+		<input type="hidden" name="page_y" value="">
+		<input type="hidden" name="id" value="' . $object->id.'">
+		';
+
+		if (!empty($conf->use_javascript_ajax) && $object->status == 0) {
+			include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
+		}
+
+		print '<div class="div-table-responsive-no-min">';
+		if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) {
+			print '<table id="tablelines" class="noborder noshadow" width="100%">';
+		}
+
+		if (!empty($object->lines)) {
+			$object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1);
+		}
+
+		// Form to add new line
+		if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') {
+			if ($action != 'editline') {
+				// Add products/services form
+
+				$parameters = array();
+				$reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+				if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+				if (empty($reshook))
+					$object->formAddObjectLine(1, $mysoc, $soc);
+			}
+		}
+
+		if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) {
+			print '</table>';
+		}
+		print '</div>';
+
+		print "</form>\n";
+	}
+
+
+	// Buttons for actions
+
+	if ($action != 'presend' && $action != 'editline') {
+		print '<div class="tabsAction">'."\n";
+		$parameters = array();
+		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+		if ($reshook < 0) {
+			setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+		}
+
+		if (empty($reshook)) {
+			// Send
+			if (empty($user->socid)) {
+				print dolGetButtonAction('', $langs->trans('SendMail'), 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&token='.newToken().'&mode=init#formmailbeforetitle');
+			}
+
+			// Back to draft
+			if ($object->status == $object::STATUS_VALIDATED) {
+				print dolGetButtonAction('', $langs->trans('SetToDraft'), 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes&token='.newToken(), '', $permissiontoadd);
+			}
+
+			print dolGetButtonAction('', $langs->trans('Modify'), 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&token='.newToken(), '', $permissiontoadd);
+
+			// Validate
+			if ($object->status == $object::STATUS_DRAFT) {
+				if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) {
+					print dolGetButtonAction('', $langs->trans('Validate'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes&token='.newToken(), '', $permissiontoadd);
+				} else {
+					$langs->load("errors");
+					print dolGetButtonAction($langs->trans("ErrorAddAtLeastOneLineFirst"), $langs->trans("Validate"), 'default', '#', '', 0);
+				}
+			}
+
+			// Clone
+			if ($permissiontoadd) {
+				print dolGetButtonAction('', $langs->trans('ToClone'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.(!empty($object->socid)?'&socid='.$object->socid:'').'&action=clone&token='.newToken(), '', $permissiontoadd);
+			}
+
+			/*
+			if ($permissiontoadd) {
+				if ($object->status == $object::STATUS_ENABLED) {
+					print dolGetButtonAction('', $langs->trans('Disable'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=disable&token='.newToken(), '', $permissiontoadd);
+				} else {
+					print dolGetButtonAction('', $langs->trans('Enable'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=enable&token='.newToken(), '', $permissiontoadd);
+				}
+			}
+			if ($permissiontoadd) {
+				if ($object->status == $object::STATUS_VALIDATED) {
+					print dolGetButtonAction('', $langs->trans('Cancel'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=close&token='.newToken(), '', $permissiontoadd);
+				} else {
+					print dolGetButtonAction('', $langs->trans('Re-Open'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen&token='.newToken(), '', $permissiontoadd);
+				}
+			}
+			*/
+
+			// Delete
+			$params = array();
+			print dolGetButtonAction('', $langs->trans("Delete"), 'delete', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken(), 'delete', $permissiontodelete, $params);
+		}
+		print '</div>'."\n";
+	}
+
+
+	// Select mail models is same action as presend
+	if (GETPOST('modelselected')) {
+		$action = 'presend';
+	}
+
+	if ($action != 'presend') {
+		print '<div class="fichecenter"><div class="fichehalfleft">';
+		print '<a name="builddoc"></a>'; // ancre
+
+		$includedocgeneration = 0;
+
+		// Documents
+		if ($includedocgeneration) {
+			$objref = dol_sanitizeFileName($object->ref);
+			$relativepath = $objref.'/'.$objref.'.pdf';
+			$filedir = $conf->rollerstorage->dir_output.'/'.$object->element.'/'.$objref;
+			$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
+			$genallowed = $permissiontoread; // If you can read, you can build the PDF to read content
+			$delallowed = $permissiontoadd; // If you can create/edit, you can remove a file on card
+			print $formfile->showdocuments('rollerstorage:RollerRentHistory', $object->element.'/'.$objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang);
+		}
+
+		// Show links to link elements
+		$linktoelem = $form->showLinkToObjectBlock($object, null, array('rollerrenthistory'));
+		$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
+
+
+		print '</div><div class="fichehalfright">';
+
+		$MAXEVENT = 10;
+
+		$morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', dol_buildpath('/rollerstorage/rollerrenthistory_agenda.php', 1).'?id='.$object->id);
+
+		// List of actions on element
+		include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
+		$formactions = new FormActions($db);
+		$somethingshown = $formactions->showactions($object, $object->element.'@'.$object->module, (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlcenter);
+
+		print '</div></div>';
+	}
+
+	//Select mail models is same action as presend
+	if (GETPOST('modelselected')) {
+		$action = 'presend';
+	}
+
+	// Presend form
+	$modelmail = 'rollerrenthistory';
+	$defaulttopic = 'InformationMessage';
+	$diroutput = $conf->rollerstorage->dir_output;
+	$trackid = 'rollerrenthistory'.$object->id;
+
+	include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 228 - 0
custom/rollerstorage/rollerrenthistory_contact.php

@@ -0,0 +1,228 @@
+<?php
+/* Copyright (C) 2007-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2024 László Szollősi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *  \file       rollerrenthistory_contact.php
+ *  \ingroup    rollerstorage
+ *  \brief      Tab for contacts linked to RollerRentHistory
+ */
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+	$i--; $j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
+	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
+	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) {
+	$res = @include "../main.inc.php";
+}
+if (!$res && file_exists("../../main.inc.php")) {
+	$res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+	$res = @include "../../../main.inc.php";
+}
+if (!$res) {
+	die("Include of main fails");
+}
+
+require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
+dol_include_once('/rollerstorage/class/rollerrenthistory.class.php');
+dol_include_once('/rollerstorage/lib/rollerstorage_rollerrenthistory.lib.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("rollerstorage@rollerstorage", "companies", "other", "mails"));
+
+$id     = (GETPOST('id') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
+$ref    = GETPOST('ref', 'alpha');
+$lineid = GETPOST('lineid', 'int');
+$socid  = GETPOST('socid', 'int');
+$action = GETPOST('action', 'aZ09');
+
+// Initialize technical objects
+$object = new RollerRentHistory($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->rollerstorage->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('rollerrenthistorycontact', 'globalcard')); // Note that conf->hooks_modules contains array
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+
+// There is several ways to check permission.
+// Set $enablepermissioncheck to 1 to enable a minimum low level of checks
+$enablepermissioncheck = 0;
+if ($enablepermissioncheck) {
+	$permissiontoread = $user->rights->rollerstorage->rollerrenthistory->read;
+	$permission = $user->rights->rollerstorage->rollerrenthistory->write;
+} else {
+	$permissiontoread = 1;
+	$permission = 1;
+}
+
+// Security check (enable the most restrictive one)
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
+//restrictedArea($user, $object->module, $object->id, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft);
+if (!isModEnabled("rollerstorage")) {
+	accessforbidden();
+}
+if (!$permissiontoread) accessforbidden();
+
+
+/*
+ * Add a new contact
+ */
+
+if ($action == 'addcontact' && $permission) {
+	$contactid = (GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int'));
+	$typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
+	$result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
+
+	if ($result >= 0) {
+		header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
+		exit;
+	} else {
+		if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
+			$langs->load("errors");
+			setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
+		} else {
+			setEventMessages($object->error, $object->errors, 'errors');
+		}
+	}
+} elseif ($action == 'swapstatut' && $permission) {
+	// Toggle the status of a contact
+	$result = $object->swapContactStatus(GETPOST('ligne', 'int'));
+} elseif ($action == 'deletecontact' && $permission) {
+	// Deletes a contact
+	$result = $object->delete_contact($lineid);
+
+	if ($result >= 0) {
+		header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
+		exit;
+	} else {
+		dol_print_error($db);
+	}
+}
+
+
+/*
+ * View
+ */
+
+$title = $langs->trans('RollerRentHistory')." - ".$langs->trans('ContactsAddresses');
+$help_url = '';
+//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
+llxHeader('', $title, $help_url);
+
+$form = new Form($db);
+$formcompany = new FormCompany($db);
+$contactstatic = new Contact($db);
+$userstatic = new User($db);
+
+
+/* *************************************************************************** */
+/*                                                                             */
+/* View and edit mode                                                         */
+/*                                                                             */
+/* *************************************************************************** */
+
+if ($object->id) {
+	/*
+	 * Show tabs
+	 */
+	$head = rollerrenthistoryPrepareHead($object);
+
+	print dol_get_fiche_head($head, 'contact', $langs->trans("RollerRentHistory"), -1, $object->picto);
+
+	$linkback = '<a href="'.dol_buildpath('/rollerstorage/rollerrenthistory_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	/*
+	 // Ref customer
+	 $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
+	 $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
+	 // Thirdparty
+	 $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
+	 // Project
+	 if (!empty($conf->project->enabled))
+	 {
+	 $langs->load("projects");
+	 $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+	 if ($permissiontoadd)
+	 {
+	 if ($action != 'classify')
+	 //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token='.newToken().'&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+	 $morehtmlref.=' : ';
+	 if ($action == 'classify') {
+	 //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+	 $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+	 $morehtmlref.='<input type="hidden" name="action" value="classin">';
+	 $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
+	 $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+	 $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+	 $morehtmlref.='</form>';
+	 } else {
+	 $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+	 }
+	 } else {
+	 if (!empty($object->fk_project)) {
+	 $proj = new Project($db);
+	 $proj->fetch($object->fk_project);
+	 $morehtmlref .= ': '.$proj->getNomUrl();
+	 } else {
+	 $morehtmlref .= '';
+	 }
+	 }
+	 }*/
+	$morehtmlref .= '</div>';
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1);
+
+	print dol_get_fiche_end();
+
+	print '<br>';
+
+	// Contacts lines (modules that overwrite templates must declare this into descriptor)
+	$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
+	foreach ($dirtpls as $reldir) {
+		$res = @include dol_buildpath($reldir.'/contacts.tpl.php');
+		if ($res) {
+			break;
+		}
+	}
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 261 - 0
custom/rollerstorage/rollerrenthistory_document.php

@@ -0,0 +1,261 @@
+<?php
+/* Copyright (C) 2007-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2024 László Szollősi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *  \file       rollerrenthistory_document.php
+ *  \ingroup    rollerstorage
+ *  \brief      Tab for documents linked to RollerRentHistory
+ */
+
+//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
+//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
+//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
+//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
+//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
+//if (! defined("MAIN_SECURITY_FORCECSP"))   define('MAIN_SECURITY_FORCECSP', 'none');				// Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+	$i--; $j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
+	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
+	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) {
+	$res = @include "../main.inc.php";
+}
+if (!$res && file_exists("../../main.inc.php")) {
+	$res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+	$res = @include "../../../main.inc.php";
+}
+if (!$res) {
+	die("Include of main fails");
+}
+
+require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
+dol_include_once('/rollerstorage/class/rollerrenthistory.class.php');
+dol_include_once('/rollerstorage/lib/rollerstorage_rollerrenthistory.lib.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("rollerstorage@rollerstorage", "companies", "other", "mails"));
+
+
+$action = GETPOST('action', 'aZ09');
+$confirm = GETPOST('confirm');
+$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int'));
+$ref = GETPOST('ref', 'alpha');
+
+// Get parameters
+$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
+$sortfield = GETPOST('sortfield', 'aZ09comma');
+$sortorder = GETPOST('sortorder', 'aZ09comma');
+$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
+$offset = $limit * $page;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
+if (!$sortfield) {
+	$sortfield = "name";
+}
+//if (! $sortfield) $sortfield="position_name";
+
+// Initialize technical objects
+$object = new RollerRentHistory($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->rollerstorage->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('rollerrenthistorydocument', 'globalcard')); // Note that conf->hooks_modules contains array
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->rollerstorage->multidir_output[$object->entity ? $object->entity : $conf->entity]."/rollerrenthistory/".get_exdir(0, 0, 0, 1, $object);
+}
+
+// There is several ways to check permission.
+// Set $enablepermissioncheck to 1 to enable a minimum low level of checks
+$enablepermissioncheck = 0;
+if ($enablepermissioncheck) {
+	$permissiontoread = $user->rights->rollerstorage->rollerrenthistory->read;
+	$permissiontoadd = $user->rights->rollerstorage->rollerrenthistory->write; // Used by the include of actions_addupdatedelete.inc.php and actions_linkedfiles.inc.php
+} else {
+	$permissiontoread = 1;
+	$permissiontoadd = 1;
+}
+
+// Security check (enable the most restrictive one)
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
+//restrictedArea($user, $object->module, $object->id, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft);
+if (!isModEnabled("rollerstorage")) {
+	accessforbidden();
+}
+if (!$permissiontoread) {
+	accessforbidden();
+}
+if (empty($object->id)) {
+	accessforbidden();
+}
+
+
+
+/*
+ * Actions
+ */
+
+include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
+
+
+/*
+ * View
+ */
+
+$form = new Form($db);
+
+$title = $langs->trans("RollerRentHistory").' - '.$langs->trans("Files");
+$help_url = '';
+//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
+llxHeader('', $title, $help_url);
+
+// Show tabs
+$head = rollerrenthistoryPrepareHead($object);
+
+print dol_get_fiche_head($head, 'document', $langs->trans("RollerRentHistory"), -1, $object->picto);
+
+
+// Build file list
+$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
+$totalsize = 0;
+foreach ($filearray as $key => $file) {
+	$totalsize += $file['size'];
+}
+
+// Object card
+// ------------------------------------------------------------
+$linkback = '<a href="'.dol_buildpath('/rollerstorage/rollerrenthistory_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+$morehtmlref = '<div class="refidno">';
+/*
+ // Ref customer
+ $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
+ $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
+ // Thirdparty
+ $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
+ // Project
+ if (!empty($conf->project->enabled))
+ {
+ $langs->load("projects");
+ $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+ if ($permissiontoadd)
+ {
+ if ($action != 'classify')
+ //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token='.newToken().'&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+ $morehtmlref.=' : ';
+ if ($action == 'classify') {
+ //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+ $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+ $morehtmlref.='<input type="hidden" name="action" value="classin">';
+ $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
+ $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+ $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+ $morehtmlref.='</form>';
+ } else {
+ $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+ }
+ } else {
+ if (!empty($object->fk_project)) {
+ $proj = new Project($db);
+ $proj->fetch($object->fk_project);
+ $morehtmlref .= ': '.$proj->getNomUrl();
+ } else {
+ $morehtmlref .= '';
+ }
+ }
+ }*/
+$morehtmlref .= '</div>';
+
+dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+print '<div class="fichecenter">';
+
+print '<div class="underbanner clearboth"></div>';
+print '<table class="border centpercent tableforfield">';
+
+// Number of files
+print '<tr><td class="titlefield">'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>';
+
+// Total size
+print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.$totalsize.' '.$langs->trans("bytes").'</td></tr>';
+
+print '</table>';
+
+print '</div>';
+
+print dol_get_fiche_end();
+
+$modulepart = 'rollerstorage';
+//$permissiontoadd = $user->rights->rollerstorage->rollerrenthistory->write;
+$permissiontoadd = 1;
+//$permtoedit = $user->rights->rollerstorage->rollerrenthistory->write;
+$permtoedit = 1;
+$param = '&id='.$object->id;
+
+//$relativepathwithnofile='rollerrenthistory/' . dol_sanitizeFileName($object->id).'/';
+$relativepathwithnofile = 'rollerrenthistory/'.dol_sanitizeFileName($object->ref).'/';
+
+include DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
+
+// End of page
+llxFooter();
+$db->close();

+ 850 - 0
custom/rollerstorage/rollerrenthistory_list.php

@@ -0,0 +1,850 @@
+<?php
+/* Copyright (C) 2007-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2024 László Szollősi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *   	\file       rollerrenthistory_list.php
+ *		\ingroup    rollerstorage
+ *		\brief      List page for rollerrenthistory
+ */
+
+//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
+//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
+//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
+//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
+//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
+//if (! defined("MAIN_SECURITY_FORCECSP"))   define('MAIN_SECURITY_FORCECSP', 'none');	// Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
+//if (! defined('NOSESSION'))                define('NOSESSION', '1');					// On CLI mode, no need to use web sessions
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+	$i--;
+	$j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
+	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
+	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) {
+	$res = @include "../main.inc.php";
+}
+if (!$res && file_exists("../../main.inc.php")) {
+	$res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+	$res = @include "../../../main.inc.php";
+}
+if (!$res) {
+	die("Include of main fails");
+}
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
+
+// load rollerstorage libraries
+require_once __DIR__.'/class/rollerrenthistory.class.php';
+
+// for other modules
+//dol_include_once('/othermodule/class/otherobject.class.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("rollerstorage@rollerstorage", "other"));
+
+$action     = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'create'/'add', 'edit'/'update', 'view', ...
+$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
+$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
+$confirm    = GETPOST('confirm', 'alpha'); // Result of a confirmation
+$cancel     = GETPOST('cancel', 'alpha'); // We click on a Cancel button
+$toselect   = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
+$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)).basename(__FILE__, '.php')); // To manage different context of search
+$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
+$optioncss  = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
+$mode       = GETPOST('mode', 'aZ'); // The output mode ('list', 'kanban', 'hierarchy', 'calendar', ...)
+
+$id = GETPOST('id', 'int');
+$ref = GETPOST('ref', 'alpha');
+
+// Load variable for pagination
+$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
+$sortfield = GETPOST('sortfield', 'aZ09comma');
+$sortorder = GETPOST('sortorder', 'aZ09comma');
+$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
+if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
+	// If $page is not defined, or '' or -1 or if we click on clear filters
+	$page = 0;
+}
+$offset = $limit * $page;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+
+// Initialize technical objects
+$object = new RollerRentHistory($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->rollerstorage->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('rollerrenthistorylist')); // Note that conf->hooks_modules contains array
+
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+//$extrafields->fetch_name_optionals_label($object->table_element_line);
+
+$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+
+// Default sort order (if not yet defined by previous GETPOST)
+if (!$sortfield) {
+	reset($object->fields);					// Reset is required to avoid key() to return null.
+	$sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
+}
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
+
+// Initialize array of search criterias
+$search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml');
+$search = array();
+foreach ($object->fields as $key => $val) {
+	if (GETPOST('search_'.$key, 'alpha') !== '') {
+		$search[$key] = GETPOST('search_'.$key, 'alpha');
+	}
+	if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
+		$search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_'.$key.'_dtstartmonth', 'int'), GETPOST('search_'.$key.'_dtstartday', 'int'), GETPOST('search_'.$key.'_dtstartyear', 'int'));
+		$search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_'.$key.'_dtendmonth', 'int'), GETPOST('search_'.$key.'_dtendday', 'int'), GETPOST('search_'.$key.'_dtendyear', 'int'));
+	}
+}
+
+// List of fields to search into when doing a "search in all"
+$fieldstosearchall = array();
+foreach ($object->fields as $key => $val) {
+	if (!empty($val['searchall'])) {
+		$fieldstosearchall['t.'.$key] = $val['label'];
+	}
+}
+
+// Definition of array of fields for columns
+$arrayfields = array();
+foreach ($object->fields as $key => $val) {
+	// If $val['visible']==0, then we never show the field
+	if (!empty($val['visible'])) {
+		$visible = (int) dol_eval($val['visible'], 1);
+		$arrayfields['t.'.$key] = array(
+			'label'=>$val['label'],
+			'checked'=>(($visible < 0) ? 0 : 1),
+			'enabled'=>(abs($visible) != 3 && dol_eval($val['enabled'], 1)),
+			'position'=>$val['position'],
+			'help'=> isset($val['help']) ? $val['help'] : ''
+		);
+	}
+}
+// Extra fields
+include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
+
+$object->fields = dol_sort_array($object->fields, 'position');
+//$arrayfields['anotherfield'] = array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>1, 'enabled'=>1, 'position'=>90, 'csslist'=>'right');
+$arrayfields = dol_sort_array($arrayfields, 'position');
+
+// There is several ways to check permission.
+// Set $enablepermissioncheck to 1 to enable a minimum low level of checks
+$enablepermissioncheck = 0;
+if ($enablepermissioncheck) {
+	$permissiontoread = $user->hasRight('rollerstorage', 'rollerrenthistory', 'read');
+	$permissiontoadd = $user->hasRight('rollerstorage', 'rollerrenthistory', 'write');
+	$permissiontodelete = $user->hasRight('rollerstorage', 'rollerrenthistory', 'delete');
+} else {
+	$permissiontoread = 1;
+	$permissiontoadd = 1;
+	$permissiontodelete = 1;
+}
+
+// Security check (enable the most restrictive one)
+if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) accessforbidden();
+//$socid = 0; if ($user->socid > 0) $socid = $user->socid;
+//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
+//restrictedArea($user, $object->module, 0, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft);
+if (!isModEnabled("rollerstorage")) {
+	accessforbidden('Module rollerstorage not enabled');
+}
+if (!$permissiontoread) accessforbidden();
+
+
+/*
+ * Actions
+ */
+
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list';
+	$massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
+
+$parameters = array();
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
+
+if (empty($reshook)) {
+	// Selection of new fields
+	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+
+	// Purge search criteria
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
+		foreach ($object->fields as $key => $val) {
+			$search[$key] = '';
+			if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
+				$search[$key.'_dtstart'] = '';
+				$search[$key.'_dtend'] = '';
+			}
+		}
+		$toselect = array();
+		$search_array_options = array();
+	}
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
+		|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
+		$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
+	}
+
+	// Mass actions
+	$objectclass = 'RollerRentHistory';
+	$objectlabel = 'RollerRentHistory';
+	$uploaddir = $conf->rollerstorage->dir_output;
+	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
+
+	// You can add more action here
+	// if ($action == 'xxx' && $permissiontoxxx) ...
+}
+
+
+
+/*
+ * View
+ */
+
+$form = new Form($db);
+
+$now = dol_now();
+
+//$help_url = "EN:Module_RollerRentHistory|FR:Module_RollerRentHistory_FR|ES:Módulo_RollerRentHistory";
+$help_url = '';
+$title = $langs->trans("RollerRentHistorys");
+$morejs = array();
+$morecss = array();
+
+
+// Build and execute select
+// --------------------------------------------------------------------
+$sql = 'SELECT ';
+$sql .= $object->getFieldList('t');
+// Add fields from extrafields
+if (!empty($extrafields->attributes[$object->table_element]['label'])) {
+	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
+		$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : '');
+	}
+}
+// Add fields from hooks
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook
+$sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
+$sql = preg_replace('/,\s*$/', '', $sql);
+//$sql .= ", COUNT(rc.rowid) as anotherfield";
+
+$sqlfields = $sql; // $sql fields to remove for count total
+
+$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
+//$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."anothertable as rc ON rc.parent = t.rowid";
+if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
+	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
+}
+// Add table from hooks
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
+$sql .= $hookmanager->resPrint;
+if ($object->ismultientitymanaged == 1) {
+	$sql .= " WHERE t.entity IN (".getEntity($object->element).")";
+} else {
+	$sql .= " WHERE 1 = 1";
+}
+foreach ($search as $key => $val) {
+	if (array_key_exists($key, $object->fields)) {
+		if ($key == 'status' && $search[$key] == -1) {
+			continue;
+		}
+		$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
+		if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0) || !empty($object->fields[$key]['arrayofkeyval'])) {
+			if ($search[$key] == '-1' || ($search[$key] === '0' && (empty($object->fields[$key]['arrayofkeyval']) || !array_key_exists('0', $object->fields[$key]['arrayofkeyval'])))) {
+				$search[$key] = '';
+			}
+			$mode_search = 2;
+		}
+		if ($search[$key] != '') {
+			$sql .= natural_search("t.".$db->escape($key), $search[$key], (($key == 'status') ? 2 : $mode_search));
+		}
+	} else {
+		if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') {
+			$columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key);
+			if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) {
+				if (preg_match('/_dtstart$/', $key)) {
+					$sql .= " AND t.".$db->escape($columnName)." >= '".$db->idate($search[$key])."'";
+				}
+				if (preg_match('/_dtend$/', $key)) {
+					$sql .= " AND t.".$db->escape($columnName)." <= '".$db->idate($search[$key])."'";
+				}
+			}
+		}
+	}
+}
+if ($search_all) {
+	$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
+}
+//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
+// Add where from extra fields
+include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
+// Add where from hooks
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
+$sql .= $hookmanager->resPrint;
+
+/* If a group by is required
+$sql .= " GROUP BY ";
+foreach($object->fields as $key => $val) {
+	$sql .= "t.".$db->escape($key).", ";
+}
+// Add fields from extrafields
+if (!empty($extrafields->attributes[$object->table_element]['label'])) {
+	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
+		$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : '');
+	}
+}
+// Add where from hooks
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object);    // Note that $action and $object may have been modified by hook
+$sql .= $hookmanager->resPrint;
+$sql = preg_replace('/,\s*$/', '', $sql);
+*/
+
+// Add HAVING from hooks
+/*
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object); // Note that $action and $object may have been modified by hook
+$sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 ".$hookmanager->resPrint;
+*/
+
+// Count total nb of records
+$nbtotalofrecords = '';
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
+	/* The fast and low memory method to get and count full list converts the sql into a sql count */
+	$sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
+	$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
+	$resql = $db->query($sqlforcount);
+	if ($resql) {
+		$objforcount = $db->fetch_object($resql);
+		$nbtotalofrecords = $objforcount->nbtotalofrecords;
+	} else {
+		dol_print_error($db);
+	}
+
+	if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller then paging size (filtering), goto and load page 0
+		$page = 0;
+		$offset = 0;
+	}
+	$db->free($resql);
+}
+
+// Complete request and execute it with limit
+$sql .= $db->order($sortfield, $sortorder);
+if ($limit) {
+	$sql .= $db->plimit($limit + 1, $offset);
+}
+
+$resql = $db->query($sql);
+if (!$resql) {
+	dol_print_error($db);
+	exit;
+}
+
+$num = $db->num_rows($resql);
+
+
+// Direct jump if only one record found
+if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
+	$obj = $db->fetch_object($resql);
+	$id = $obj->rowid;
+	header("Location: ".dol_buildpath('/rollerstorage/rollerrenthistory_card.php', 1).'?id='.$id);
+	exit;
+}
+
+
+// Output page
+// --------------------------------------------------------------------
+
+llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'bodyforlist');	// Can use also classforhorizontalscrolloftabs instead of bodyforlist for no horizontal scroll
+
+// Example : Adding jquery code
+// print '<script type="text/javascript">
+// jQuery(document).ready(function() {
+// 	function init_myfunc()
+// 	{
+// 		jQuery("#myid").removeAttr(\'disabled\');
+// 		jQuery("#myid").attr(\'disabled\',\'disabled\');
+// 	}
+// 	init_myfunc();
+// 	jQuery("#mybutton").click(function() {
+// 		init_myfunc();
+// 	});
+// });
+// </script>';
+
+$arrayofselected = is_array($toselect) ? $toselect : array();
+
+$param = '';
+if (!empty($mode)) {
+	$param .= '&mode='.urlencode($mode);
+}
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+	$param .= '&contextpage='.urlencode($contextpage);
+}
+if ($limit > 0 && $limit != $conf->liste_limit) {
+	$param .= '&limit='.urlencode($limit);
+}
+foreach ($search as $key => $val) {
+	if (is_array($search[$key])) {
+		foreach ($search[$key] as $skey) {
+			if ($skey != '') {
+				$param .= '&search_'.$key.'[]='.urlencode($skey);
+			}
+		}
+	} elseif (preg_match('/(_dtstart|_dtend)$/', $key) && !empty($val)) {
+		$param .= '&search_'.$key.'month='.((int) GETPOST('search_'.$key.'month', 'int'));
+		$param .= '&search_'.$key.'day='.((int) GETPOST('search_'.$key.'day', 'int'));
+		$param .= '&search_'.$key.'year='.((int) GETPOST('search_'.$key.'year', 'int'));
+	} elseif ($search[$key] != '') {
+		$param .= '&search_'.$key.'='.urlencode($search[$key]);
+	}
+}
+if ($optioncss != '') {
+	$param .= '&optioncss='.urlencode($optioncss);
+}
+// Add $param from extra fields
+include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
+// Add $param from hooks
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object); // Note that $action and $object may have been modified by hook
+$param .= $hookmanager->resPrint;
+
+// List of mass actions available
+$arrayofmassactions = array(
+	//'validate'=>img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate"),
+	//'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
+	//'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
+	//'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"),
+);
+if (!empty($permissiontodelete)) {
+	$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
+}
+if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
+	$arrayofmassactions = array();
+}
+$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
+
+print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
+if ($optioncss != '') {
+	print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+}
+print '<input type="hidden" name="token" value="'.newToken().'">';
+print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
+print '<input type="hidden" name="action" value="list">';
+print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
+print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
+print '<input type="hidden" name="page" value="'.$page.'">';
+print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
+print '<input type="hidden" name="page_y" value="">';
+print '<input type="hidden" name="mode" value="'.$mode.'">';
+
+
+$newcardbutton = '';
+$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition'));
+$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition'));
+$newcardbutton .= dolGetButtonTitleSeparator();
+$newcardbutton .= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/rollerstorage/rollerrenthistory_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd);
+
+print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1);
+
+// Add code for pre mass action (confirmation or email presend form)
+$topicmail = "SendRollerRentHistoryRef";
+$modelmail = "rollerrenthistory";
+$objecttmp = new RollerRentHistory($db);
+$trackid = 'xxxx'.$object->id;
+include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
+
+if ($search_all) {
+	$setupstring = '';
+	foreach ($fieldstosearchall as $key => $val) {
+		$fieldstosearchall[$key] = $langs->trans($val);
+		$setupstring .= $key."=".$val.";";
+	}
+	print '<!-- Search done like if PRODUCT_QUICKSEARCH_ON_FIELDS = '.$setupstring.' -->'."\n";
+	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'."\n";
+}
+
+$moreforfilter = '';
+/*$moreforfilter.='<div class="divsearchfield">';
+$moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
+$moreforfilter.= '</div>';*/
+
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
+if (empty($reshook)) {
+	$moreforfilter .= $hookmanager->resPrint;
+} else {
+	$moreforfilter = $hookmanager->resPrint;
+}
+
+if (!empty($moreforfilter)) {
+	print '<div class="liste_titre liste_titre_bydiv centpercent">';
+	print $moreforfilter;
+	print '</div>';
+}
+
+$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
+$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN', '')); // This also change content of $arrayfields
+$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
+
+print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
+print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
+
+// Fields title search
+// --------------------------------------------------------------------
+print '<tr class="liste_titre">';
+// Action column
+if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+	print '<td class="liste_titre maxwidthsearch">';
+	$searchpicto = $form->showFilterButtons('left');
+	print $searchpicto;
+	print '</td>';
+}
+foreach ($object->fields as $key => $val) {
+	$searchkey = empty($search[$key]) ? '' : $search[$key];
+	$cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
+	if ($key == 'status') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+	} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'rowid' && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'right';
+	}
+	if (!empty($arrayfields['t.'.$key]['checked'])) {
+		print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
+		if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+			print $form->selectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100'.($key == 'status' ? ' search_status onrightofpage' : ''), 1);
+		} elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:') === 0)) {
+			print $object->showInputField($val, $key, (isset($search[$key]) ? $search[$key] : ''), '', '', 'search_', $cssforfield.' maxwidth250', 1);
+		} elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
+			print '<div class="nowrap">';
+			print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
+			print '</div>';
+			print '<div class="nowrap">';
+			print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
+			print '</div>';
+		} elseif ($key == 'lang') {
+			require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
+			$formadmin = new FormAdmin($db);
+			print $formadmin->select_language($search[$key], 'search_lang', 0, null, 1, 0, 0, 'minwidth150 maxwidth200', 2);
+		} else {
+			print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag(isset($search[$key]) ? $search[$key] : '').'">';
+		}
+		print '</td>';
+	}
+}
+// Extra fields
+include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
+
+// Fields from hook
+$parameters = array('arrayfields'=>$arrayfields);
+$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook
+print $hookmanager->resPrint;
+/*if (!empty($arrayfields['anotherfield']['checked'])) {
+	print '<td class="liste_titre"></td>';
+}*/
+// Action column
+if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+	print '<td class="liste_titre maxwidthsearch">';
+	$searchpicto = $form->showFilterButtons();
+	print $searchpicto;
+	print '</td>';
+}
+print '</tr>'."\n";
+
+$totalarray = array();
+$totalarray['nbfield'] = 0;
+
+// Fields title label
+// --------------------------------------------------------------------
+print '<tr class="liste_titre">';
+if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+	print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
+	$totalarray['nbfield']++;
+}
+foreach ($object->fields as $key => $val) {
+	$cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
+	if ($key == 'status') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+	} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'rowid' && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'right';
+	}
+	$cssforfield = preg_replace('/small\s*/', '', $cssforfield);	// the 'small' css must not be used for the title label
+	if (!empty($arrayfields['t.'.$key]['checked'])) {
+		print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
+		$totalarray['nbfield']++;
+	}
+}
+// Extra fields
+include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
+// Hook fields
+$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder, 'totalarray'=>&$totalarray);
+$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
+print $hookmanager->resPrint;
+/*if (!empty($arrayfields['anotherfield']['checked'])) {
+	print '<th class="liste_titre right">'.$langs->trans("AnotherField").'</th>';
+	$totalarray['nbfield']++;
+}*/
+// Action column
+if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+	print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
+	$totalarray['nbfield']++;
+}
+print '</tr>'."\n";
+
+$totalarray = array();
+$totalarray['nbfield'] = 0;
+
+// Detect if we need a fetch on each output line
+$needToFetchEachLine = 0;
+if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
+	foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
+		if (preg_match('/\$object/', $val)) {
+			$needToFetchEachLine++; // There is at least one compute field that use $object
+		}
+	}
+}
+
+
+// Loop on record
+// --------------------------------------------------------------------
+$i = 0;
+$savnbfield = $totalarray['nbfield'];
+$totalarray = array();
+$totalarray['nbfield'] = 0;
+$imaxinloop = ($limit ? min($num, $limit) : $num);
+while ($i < $imaxinloop) {
+	$obj = $db->fetch_object($resql);
+	if (empty($obj)) {
+		break; // Should not happen
+	}
+
+	// Store properties in $object
+	$object->setVarsFromFetchObj($obj);
+
+	if ($mode == 'kanban') {
+		if ($i == 0) {
+			print '<tr><td colspan="'.$savnbfield.'">';
+			print '<div class="box-flex-container">';
+		}
+		// Output Kanban
+		print $object->getKanbanView('');
+		if ($i == ($imaxinloop - 1)) {
+			print '</div>';
+			print '</td></tr>';
+		}
+	} else {
+		// Show here line of result
+		$j = 0;
+		print '<tr data-rowid="'.$object->id.'" class="oddeven">';
+		// Action column
+		if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+			print '<td class="nowrap center">';
+			if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
+				$selected = 0;
+				if (in_array($object->id, $arrayofselected)) {
+					$selected = 1;
+				}
+				print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
+			}
+			print '</td>';
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
+		}
+		foreach ($object->fields as $key => $val) {
+			$cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
+			if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+				$cssforfield .= ($cssforfield ? ' ' : '').'center';
+			} elseif ($key == 'status') {
+				$cssforfield .= ($cssforfield ? ' ' : '').'center';
+			}
+
+			if (in_array($val['type'], array('timestamp'))) {
+				$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+			} elseif ($key == 'ref') {
+				$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+			}
+
+			if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status')) && empty($val['arrayofkeyval'])) {
+				$cssforfield .= ($cssforfield ? ' ' : '').'right';
+			}
+			//if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100';
+
+			if (!empty($arrayfields['t.'.$key]['checked'])) {
+				print '<td'.($cssforfield ? ' class="'.$cssforfield.(preg_match('/tdoverflow/', $cssforfield) ? ' classfortooltip' : '').'"' : '');
+				if (preg_match('/tdoverflow/', $cssforfield)) {
+					print ' title="'.dol_escape_htmltag($object->$key).'"';
+				}
+				print '>';
+				if ($key == 'status') {
+					print $object->getLibStatut(5);
+				} elseif ($key == 'rowid') {
+					print $object->showOutputField($val, $key, $object->id, '');
+				} else {
+					print $object->showOutputField($val, $key, $object->$key, '');
+				}
+				print '</td>';
+				if (!$i) {
+					$totalarray['nbfield']++;
+				}
+				if (!empty($val['isameasure']) && $val['isameasure'] == 1) {
+					if (!$i) {
+						$totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
+					}
+					if (!isset($totalarray['val'])) {
+						$totalarray['val'] = array();
+					}
+					if (!isset($totalarray['val']['t.'.$key])) {
+						$totalarray['val']['t.'.$key] = 0;
+					}
+					$totalarray['val']['t.'.$key] += $object->$key;
+				}
+			}
+		}
+		// Extra fields
+		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
+		// Fields from hook
+		$parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
+		$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
+		print $hookmanager->resPrint;
+		/*if (!empty($arrayfields['anotherfield']['checked'])) {
+			print '<td class="right">'.$obj->anotherfield.'</td>';
+		}*/
+		// Action column
+		if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+			print '<td class="nowrap center">';
+			if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
+				$selected = 0;
+				if (in_array($object->id, $arrayofselected)) {
+					$selected = 1;
+				}
+				print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
+			}
+			print '</td>';
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
+		}
+
+		print '</tr>'."\n";
+	}
+
+	$i++;
+}
+
+// Show total line
+include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
+
+// If no record found
+if ($num == 0) {
+	$colspan = 1;
+	foreach ($arrayfields as $key => $val) {
+		if (!empty($val['checked'])) {
+			$colspan++;
+		}
+	}
+	print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
+}
+
+
+$db->free($resql);
+
+$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
+$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+print $hookmanager->resPrint;
+
+print '</table>'."\n";
+print '</div>'."\n";
+
+print '</form>'."\n";
+
+if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
+	$hidegeneratedfilelistifempty = 1;
+	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
+		$hidegeneratedfilelistifempty = 0;
+	}
+
+	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
+	$formfile = new FormFile($db);
+
+	// Show list of available documents
+	$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
+	$urlsource .= str_replace('&amp;', '&', $param);
+
+	$filedir = $diroutputmassaction;
+	$genallowed = $permissiontoread;
+	$delallowed = $permissiontoadd;
+
+	print $formfile->showdocuments('massfilesarea_rollerstorage', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 221 - 0
custom/rollerstorage/rollerrenthistory_note.php

@@ -0,0 +1,221 @@
+<?php
+/* Copyright (C) 2007-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2024 László Szollősi
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *  \file       rollerrenthistory_note.php
+ *  \ingroup    rollerstorage
+ *  \brief      Tab for notes on RollerRentHistory
+ */
+
+//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
+//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
+//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
+//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
+//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
+//if (! defined("MAIN_SECURITY_FORCECSP"))   define('MAIN_SECURITY_FORCECSP', 'none');				// Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+	$i--; $j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
+	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
+	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) {
+	$res = @include "../main.inc.php";
+}
+if (!$res && file_exists("../../main.inc.php")) {
+	$res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+	$res = @include "../../../main.inc.php";
+}
+if (!$res) {
+	die("Include of main fails");
+}
+
+dol_include_once('/rollerstorage/class/rollerrenthistory.class.php');
+dol_include_once('/rollerstorage/lib/rollerstorage_rollerrenthistory.lib.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("rollerstorage@rollerstorage", "companies"));
+
+// Get parameters
+$id = GETPOST('id', 'int');
+$ref        = GETPOST('ref', 'alpha');
+$action = GETPOST('action', 'aZ09');
+$cancel     = GETPOST('cancel', 'aZ09');
+$backtopage = GETPOST('backtopage', 'alpha');
+
+// Initialize technical objects
+$object = new RollerRentHistory($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->rollerstorage->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('rollerrenthistorynote', 'globalcard')); // Note that conf->hooks_modules contains array
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->rollerstorage->multidir_output[empty($object->entity) ? $conf->entity : $object->entity]."/".$object->id;
+}
+
+
+// There is several ways to check permission.
+// Set $enablepermissioncheck to 1 to enable a minimum low level of checks
+$enablepermissioncheck = 0;
+if ($enablepermissioncheck) {
+	$permissiontoread = $user->rights->rollerstorage->rollerrenthistory->read;
+	$permissiontoadd = $user->rights->rollerstorage->rollerrenthistory->write;
+	$permissionnote = $user->rights->rollerstorage->rollerrenthistory->write; // Used by the include of actions_setnotes.inc.php
+} else {
+	$permissiontoread = 1;
+	$permissiontoadd = 1;
+	$permissionnote = 1;
+}
+
+// Security check (enable the most restrictive one)
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
+//restrictedArea($user, $object->module, $object->id, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft);
+if (!isModEnabled("rollerstorage")) {
+	accessforbidden();
+}
+if (!$permissiontoread) accessforbidden();
+
+
+/*
+ * Actions
+ */
+
+$parameters = array();
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
+if (empty($reshook)) {
+	include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
+}
+
+
+/*
+ * View
+ */
+
+$form = new Form($db);
+
+//$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes';
+$help_url = '';
+$title = $langs->trans('RollerRentHistory').' - '.$langs->trans("Notes");
+llxHeader('', $title, $help_url);
+
+if ($id > 0 || !empty($ref)) {
+	$object->fetch_thirdparty();
+
+	$head = rollerrenthistoryPrepareHead($object);
+
+	print dol_get_fiche_head($head, 'note', $langs->trans("RollerRentHistory"), -1, $object->picto);
+
+	// Object card
+	// ------------------------------------------------------------
+	$linkback = '<a href="'.dol_buildpath('/rollerstorage/rollerrenthistory_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	/*
+	 // Ref customer
+	 $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
+	 $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
+	 // Thirdparty
+	 $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
+	 // Project
+	 if (!empty($conf->project->enabled))
+	 {
+	 $langs->load("projects");
+	 $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+	 if ($permissiontoadd)
+	 {
+	 if ($action != 'classify')
+	 //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token='.newToken().'&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+	 $morehtmlref.=' : ';
+	 if ($action == 'classify') {
+	 //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+	 $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+	 $morehtmlref.='<input type="hidden" name="action" value="classin">';
+	 $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
+	 $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+	 $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+	 $morehtmlref.='</form>';
+	 } else {
+	 $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+	 }
+	 } else {
+	 if (!empty($object->fk_project)) {
+	 $proj = new Project($db);
+	 $proj->fetch($object->fk_project);
+	 $morehtmlref .= ': '.$proj->getNomUrl();
+	 } else {
+	 $morehtmlref .= '';
+	 }
+	 }
+	 }*/
+	 $morehtmlref .= '</div>';
+
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+
+	print '<div class="fichecenter">';
+	print '<div class="underbanner clearboth"></div>';
+
+
+	$cssclass = "titlefield";
+	include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
+
+	print '</div>';
+
+	print dol_get_fiche_end();
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 28 - 0
custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory.key.sql

@@ -0,0 +1,28 @@
+-- Copyright (C) 2024 László Szollősi
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of the GNU General Public License as published by
+-- the Free Software Foundation, either version 3 of the License, or
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see https://www.gnu.org/licenses/.
+
+
+-- BEGIN MODULEBUILDER INDEXES
+ALTER TABLE llx_rollerstorage_rollerrenthistory ADD INDEX idx_rollerstorage_rollerrenthistory_rowid (rowid);
+ALTER TABLE llx_rollerstorage_rollerrenthistory ADD INDEX idx_rollerstorage_rollerrenthistory_entity (entity);
+ALTER TABLE llx_rollerstorage_rollerrenthistory ADD INDEX idx_rollerstorage_rollerrenthistory_ref (ref);
+ALTER TABLE llx_rollerstorage_rollerrenthistory ADD CONSTRAINT llx_rollerstorage_rollerrenthistory_fk_user_creat FOREIGN KEY (fk_user_creat) REFERENCES llx_user(rowid);
+ALTER TABLE llx_rollerstorage_rollerrenthistory ADD INDEX idx_rollerstorage_rollerrenthistory_status (status);
+-- END MODULEBUILDER INDEXES
+
+--ALTER TABLE llx_rollerstorage_rollerrenthistory ADD UNIQUE INDEX uk_rollerstorage_rollerrenthistory_fieldxy(fieldx, fieldy);
+
+--ALTER TABLE llx_rollerstorage_rollerrenthistory ADD CONSTRAINT llx_rollerstorage_rollerrenthistory_fk_field FOREIGN KEY (fk_field) REFERENCES llx_rollerstorage_myotherobject(rowid);
+

+ 34 - 0
custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory.sql

@@ -0,0 +1,34 @@
+-- Copyright (C) 2024 László Szollősi
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of the GNU General Public License as published by
+-- the Free Software Foundation, either version 3 of the License, or
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see https://www.gnu.org/licenses/.
+
+
+CREATE TABLE llx_rollerstorage_rollerrenthistory(
+	-- BEGIN MODULEBUILDER FIELDS
+	rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, 
+	entity integer DEFAULT 1 NOT NULL, 
+	ref varchar(128) NOT NULL, 
+	date_creation datetime NOT NULL, 
+	tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
+	fk_user_creat integer NOT NULL, 
+	fk_user_modif integer, 
+	status integer NOT NULL, 
+	event_id integer, 
+	inventory_id integer NOT NULL, 
+	facture_id integer, 
+	ticket_id integer, 
+	product_id integer, 
+	invoice_number varchar(255) NOT NULL
+	-- END MODULEBUILDER FIELDS
+) ENGINE=innodb;

+ 34 - 0
custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory.sql.back

@@ -0,0 +1,34 @@
+-- Copyright (C) 2024 László Szollősi
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of the GNU General Public License as published by
+-- the Free Software Foundation, either version 3 of the License, or
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see https://www.gnu.org/licenses/.
+
+
+CREATE TABLE llx_rollerstorage_rollerrenthistory(
+	-- BEGIN MODULEBUILDER FIELDS
+	rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, 
+	entity integer DEFAULT 1 NOT NULL, 
+	ref varchar(128) NOT NULL, 
+	date_creation datetime NOT NULL, 
+	tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
+	fk_user_creat integer NOT NULL, 
+	fk_user_modif integer, 
+	status integer NOT NULL, 
+	event_id integer, 
+	inventory_id integer, 
+	facture_id integer, 
+	ticket_id integer, 
+	product_id integer, 
+	invoice_number varchar(255) NOT NULL
+	-- END MODULEBUILDER FIELDS
+) ENGINE=innodb;

+ 19 - 0
custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory_extrafields.key.sql

@@ -0,0 +1,19 @@
+-- Copyright (C) 2024 László Szollősi
+--
+-- This program is free software; you can redistribute it and/or modify
+-- it under the terms of the GNU General Public License as published by
+-- the Free Software Foundation; either version 3 of the License, or
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program. If not, see https://www.gnu.org/licenses/.
+
+
+-- BEGIN MODULEBUILDER INDEXES
+ALTER TABLE llx_rollerstorage_rollerrenthistory_extrafields ADD INDEX idx_rollerrenthistory_fk_object(fk_object);
+-- END MODULEBUILDER INDEXES

+ 23 - 0
custom/rollerstorage/sql/llx_rollerstorage_rollerrenthistory_extrafields.sql

@@ -0,0 +1,23 @@
+-- Copyright (C) 2024 László Szollősi
+--
+-- This program is free software; you can redistribute it and/or modify
+-- it under the terms of the GNU General Public License as published by
+-- the Free Software Foundation; either version 3 of the License, or
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program. If not, see https://www.gnu.org/licenses/.
+
+create table llx_rollerstorage_rollerrenthistory_extrafields
+(
+  rowid                     integer AUTO_INCREMENT PRIMARY KEY,
+  tms                       timestamp,
+  fk_object                 integer NOT NULL,
+  import_key                varchar(14)                          		-- import key
+) ENGINE=innodb;
+

+ 50 - 13
custom/settlements/class/daily_closing.class.php

@@ -1,6 +1,10 @@
 <?php
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
+require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_log.class.php';
 class DailyClosing
 {
+    use CurlApi;
+
     public function getChecked($deviceArray, $device)
     {
         return $this->isChecked($deviceArray, $device) ? 'checked' : '';
@@ -245,14 +249,16 @@ class DailyClosing
     {
         global $db, $langs;
         $to = date("Y-m-d H:i:s", dol_now());
-        $sql = "SELECT f.rowid, f.ref, e.label, f.datec, f.total_ttc, f.multicurrency_code, f.fk_statut
+        $sql = "SELECT f.rowid, f.ref, e.label, f.datec, f.total_ttc, f.multicurrency_code, f.fk_statut, bbt.rowid as bbt_rowid, bbtip.rowid as bbtip_rowid
         FROM llx_facture AS f
         INNER JOIN llx_entity AS e ON e.rowid = f.entity
+        LEFT JOIN llx_bbus_bbticket as bbt ON bbt.fk_facture = f.rowid
+        LEFT JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.invoice_number = f.ref
         WHERE 
             f.fk_user_author = {$user_id} AND 
             f.datec >= (SELECT un.date_creation FROM public.llx_settlements_usernaplo AS un WHERE un.user_id = {$user_id} AND un.group_user_id = {$group_id} AND un.status = 1 
-            /*AND date_trunc('day', un.date_creation) = CURRENT_DATE*/ ORDER BY un.rowid LIMIT 1) AND f.datec BETWEEN '{$from}' AND '{$to}' 
-            AND NOT EXISTS (SELECT 1 FROM llx_bbus_bbticketinvoiceprinting AS b WHERE b.fk_facture = f.rowid) 
+             ORDER BY un.rowid LIMIT 1) AND f.datec BETWEEN '{$from}' AND '{$to}' 
+            /*AND NOT EXISTS (SELECT 1 FROM llx_bbus_bbticketinvoiceprinting AS b WHERE b.fk_facture = f.rowid)*/ 
         ORDER BY f.rowid DESC;";
         //print $sql;
         $data = $db->query($sql);
@@ -268,6 +274,8 @@ class DailyClosing
         </tr>';
         if (!empty($result)) {
             foreach ($result as $record) {
+                if (!is_null($record['bbt_rowid']) && is_null($record['bbtip_rowid'])) {
+                    print '<br>';
                 print '<tr class="center">
                 <td><a href="/compta/facture/card.php?facid=' . $record['rowid'] . '&save_lastsearch_values=1">' . $record['ref'] . '</a></td>
                 <td>' . $record['label'] . '</td>
@@ -277,30 +285,51 @@ class DailyClosing
                 <td>' . $this->setStatut($record['fk_statut']) . '</td>
                 </tr>';
             }
+            }
         } else {
             print '<tr><td style="color:red; text-align:center;" colspan="5">' . $langs->trans('Empty') . '</td></tr>';
         }
         print '</table>';
     }
 
-    function printedFactures($group_id, $user_id)
+    function printedFactures($user_id, $date_creation)
     {
         global $db, $langs;
+        $startdate = date("Y-m-d H:i:s", $date_creation);
         $now = date("Y-m-d H:i:s", dol_now());
         $array = [];
-        $sql = "SELECT f.rowid
+        $crossShoppingFacturesString = "";
+        $sql = "SELECT f.rowid, bbt.rowid as bbt_rowid, bbtip.rowid as bbtip_rowid, f.ref
         FROM llx_facture AS f
         INNER JOIN llx_entity AS e ON e.rowid = f.entity
+        LEFT JOIN llx_bbus_bbticket as bbt ON bbt.fk_facture = f.rowid
+        LEFT JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.invoice_number = f.ref
         WHERE 
             f.fk_user_author = {$user_id} AND 
-            f.datec >= (SELECT un.date_creation FROM public.llx_settlements_usernaplo AS un WHERE un.user_id = {$user_id} AND un.group_user_id = {$group_id} AND un.status = 1 
-            ORDER BY un.rowid LIMIT 1) AND f.datec <= '{$now}'
-            AND EXISTS (SELECT 1 FROM llx_bbus_bbticketinvoiceprinting AS b WHERE b.fk_facture = f.rowid) 
+            f.datec BETWEEN '{$startdate}' AND '{$now}'
         ORDER BY f.rowid DESC;";
-        //print $sql;
+
         $data = $db->query($sql);
         while ($row = pg_fetch_assoc($data)) {
+            if (!is_null($row['bbt_rowid']) && !is_null($row['bbtip_rowid'])) {
             $array[] = $row['rowid'];
+            } else {
+                if ($crossShoppingFacturesString == "") {
+                    $crossShoppingFacturesString .= "'" . $row['ref'] . "'";
+                } else {
+                    $crossShoppingFacturesString .= ",'" . $row['ref'] . "'";
+                }
+            }
+        }
+        $params = ["from" => $startdate, "to" => $now, "factures" => $crossShoppingFacturesString];
+        $postFields = json_encode($params);
+        $crossShoppingFactures = $this->curlRunner('bookingapi/getPrintedFacturesRefsArray', $postFields, 'POST', true);
+
+        $data = $db->query($sql);
+        while ($row2 = pg_fetch_assoc($data)) {
+            if (in_array($row2['ref'], $crossShoppingFactures)) {
+                $array[] = $row2['rowid'];
+            }
         }
         return $array;
     }
@@ -327,17 +356,25 @@ class DailyClosing
         global $db;
         $array = [];
         $number = 0;
-        $sql = "SELECT tip.fk_facture, tip.product_id, count(tip.product_id)  FROM llx_bbus_bbticketinvoiceprinting as tip
+        $sql = "SELECT tip.fk_facture, tip.product_id, count(tip.product_id), invoice_number  FROM llx_bbus_bbticketinvoiceprinting as tip
         WHERE tip.fk_facture = {$facture_id}
-        GROUP BY tip.fk_facture, tip.product_id";
+        GROUP BY tip.fk_facture, tip.product_id, invoice_number";
         $data = $db->query($sql);
+        if ($db->num_rows($data) > 0) {
         while ($row = $db->fetch_object($data)) {
             $array[$row->fk_facture][$row->product_id] = $row->count;
         }
         $firstKey = array_key_first($array);
         $firstValue = $array[$firstKey];
         $number = reset($firstValue);
+        } else {
+            $factureObj = new Facture($db);
+            $result = $factureObj->fetch($facture_id);
+            $invoice_number = $factureObj->ref;
+            $params = ["invoice_number" => $invoice_number];
+            $postFields = json_encode($params);
+            $number = $this->curlRunner('bookingapi/getFacturesNumberOfPrints', $postFields, 'POST', true);
+        }
         return $number > 1 ? '<div style="color:red;">' . $number . '</div>' : '<div>' . $number . '</div>';
     }
-
-}
+}

+ 343 - 0
custom/settlements/class/daily_closing.class.php.bak

@@ -0,0 +1,343 @@
+<?php
+class DailyClosing
+{
+    public function getChecked($deviceArray, $device)
+    {
+        return $this->isChecked($deviceArray, $device) ? 'checked' : '';
+    }
+
+    public function getDeviceWHChk($deviceArray, $device)
+    {
+        return $this->isChecked($deviceArray, $device) ? 'display:none' : 'display:inline-block';
+    }
+
+    public function getDeviceAmount($amountArray, $device)
+    {
+        return $this->isValidAmountArray($amountArray, $device) ? $amountArray['d' . $device['device_id'] . '_amount'] : '';
+    }
+
+    private function isChecked($deviceArray, $device)
+    {
+        return isset($deviceArray) && $deviceArray['d' . $device['device_id']] != 'x';
+    }
+
+    private function isValidAmountArray($amountArray, $device)
+    {
+        return isset($amountArray) && $amountArray['d' . $device['device_id'] . '_amount'] != '';
+    }
+
+    private function isCheckedForDailyIncomeHUF($deviceArray)
+    {
+        return isset($deviceArray) && $deviceArray['_daily_HUF'] != 'x';
+    }
+
+    private function isCheckedForDailyIncomeEUR($deviceArray)
+    {
+        return isset($deviceArray) && $deviceArray['_daily_EUR'] != 'x';
+    }
+
+    public function getCheckedDailyIncomeHUF($deviceArray)
+    {
+        return $this->isCheckedForDailyIncomeHUF($deviceArray) ? 'checked' : '';
+    }
+
+    public function getDailyAmountHUFChk($deviceArray)
+    {
+        return $this->isCheckedForDailyIncomeHUF($deviceArray) ? 'display:none' : 'display:inline-block';
+    }
+
+    public function getCheckedDailyIncomeEUR($deviceArray)
+    {
+        return $this->isCheckedForDailyIncomeEUR($deviceArray) ? 'checked' : '';
+    }
+
+    public function getDailyAmountEURChk($deviceArray)
+    {
+        return $this->isCheckedForDailyIncomeEUR($deviceArray) ? 'display:none' : 'display:inline-block';
+    }
+
+    public function getJSONArray($array)
+    {
+        $jsonArray = [];
+        foreach ($_REQUEST['withholding'] as $whgroup) {
+            foreach ($whgroup as $dkey => $dvalue) {
+                if (stripos($dkey, '_amount') == false) {
+                    $OK = $dvalue == '1' ? 'OK' : '';
+                    $jsonArray[$dkey] = $OK;
+                } else {
+                    $value = $dvalue != '' ? $dvalue : '';
+                    $jsonArray[$dkey] = $value;
+                }
+            }
+        }
+        return $jsonArray;
+    }
+
+    public function getDeviceArray($PackageHistoryClosed)
+    {
+        $deviceArray = [];
+        $dataArray = json_decode($PackageHistoryClosed->note_public);
+        foreach ($dataArray as $key => $value) {
+            if (strpos($key, '_amount') == false) {
+                $deviceArray[$key] = $value == 'OK' ? 1 : 'x';
+            }
+        }
+        return $deviceArray;
+    }
+
+    public function getAmountArray($PackageHistoryClosed)
+    {
+        $amountArray = [];
+        $dataArray = json_decode($PackageHistoryClosed->note_public);
+        foreach ($dataArray as $key => $value) {
+            if (strpos($key, '_amount') == true) {
+                $amountArray[$key] = $value != '' ? $value : '';
+            }
+        }
+        return $amountArray;
+    }
+
+    public function getHeader($object, $user_id, $idmenu)
+    {
+        global $db, $langs, $conf;
+
+        $langs->load("settlements@settlements");
+
+        $h = 0;
+        $head = array();
+
+        $head[$h][0] = dol_buildpath("/settlements/dailyclosing_card.php", 1) . '?user_id=' . $user_id . '&idmenu=' . $idmenu . '&mainmenu=settlements&leftmenu=';
+        $head[$h][1] = $langs->trans("DailyClosing");
+        $head[$h][2] = 'card';
+        $h++;
+        $head[$h][0] = dol_buildpath("/settlements/dailyclosing_list.php", 1) . '?user_id=' . $user_id . '&idmenu=' . $idmenu . '&mainmenu=settlements&leftmenu=';
+        $head[$h][1] = $langs->trans("DailyClosingHistory");
+        $head[$h][2] = 'list';
+        $h++;
+        complete_head_from_modules($conf, $langs, $object, $head, $h, 'group@settlements');
+        return $head;
+    }
+
+    public function getAllHistoryRecords($sql)
+    {
+        global $db;
+        $historyRecords = [];
+        $result = $db->query($sql);
+        while ($row = pg_fetch_assoc($result)) {
+            $historyRecords[] = $row;
+        }
+        return $historyRecords;
+    }
+
+    function setRowColor($rownum)
+    {
+        return $rownum % 2 == 0 ? '#b0c4de' : 'white';
+    }
+
+    private function setStatus($status)
+    {
+        return $status ? '<font color="red">Closed</font>' : '<font color="green">Open</font>';
+    }
+
+    function tableDrawerForDailyClosing($allHistoryRecords, $idmenu)
+    {
+        $rownum = 0;
+        foreach ($allHistoryRecords as $record) {
+            $url = '/custom/settlements/dailyclosinghistory_card.php?id=' . $record['rowid'] . '&user_id=' . $record['user_id'] . '&idmenu=' . $idmenu . '&mainmenu=settlements&leftmenu=';
+            $bgcolor = $this->setRowColor($rownum);
+            print '<tr style="height:30px; background-color: ' . $bgcolor . '">
+            <td><a style="display: block; width: 100%; height: 100%;" href="' . $url . '">' . $record['rowid'] . '</a></td>';
+            print '<td style="text-align: center;">' . $record['date_creation'] . '</td>';
+            print '<td style="text-align: center;">' . $record['lastname'] . ' ' . $record['firstname'] . '</td>';
+            print '<td style="text-align: center;">' . $this->setStatus($record['status']) . '</td>';
+            print '</tr>';
+            $rownum++;
+        }
+    }
+
+    function get1stBlocHistorykDataOpen($id)
+    {
+        global $db;
+        $packageHistoryRecordObj = new PackageHistory($db);
+        $packageHistoryRecordObj->fetch($id);
+        /* $sql = "SELECT pack.label as packetlabel, gt.label as grouptool,  ph.fk_group_id, ph.user_id, ph.package_id, ph.rowid, gu.fk_settlements_group, gr.ref as usergroup, ph.date_creation FROM public.llx_rollerstorage_packagehistory AS ph
+        INNER JOIN llx_settlements_package as pack ON pack.rowid=ph.package_id
+        INNER JOIN llx_settlements_grouptools as gt ON gt.rowid = ph.fk_group_id
+        INNER JOIN llx_settlements_groupusers as gu ON gu.fk_user = ph.user_id
+        INNER JOIN llx_settlements_group as gr ON gr.rowid=gu.fk_settlements_group
+        WHERE ph.rowid = {$id}";
+        $data = $db->query($sql);
+        $packageHistoryObj = pg_fetch_object($data);
+        return $packageHistoryObj;*/
+        return $packageHistoryRecordObj;
+    }
+
+    function get1stBlocHistorykData($id)
+    {
+        global $db;
+        $packageHistoryObj = new PackageHistory($db);
+        $packageHistoryObj->fetch($id);
+        return $packageHistoryObj;
+    }
+
+
+    function get1stBlocHistorykDataClosed($id)
+    {
+        global $db;
+        $packageHistoryObj = new PackageHistory($db);
+        $packageHistoryObj->fetch($id);
+        return $packageHistoryObj;
+    }
+
+    function getStatus($rowid)
+    {
+        global $db;
+        $packageHistoryObj = new PackageHistory($db);
+        $result = $packageHistoryObj->fetch($rowid);
+        return $packageHistoryObj->status;
+    }
+
+    function closeRecord($id)
+    {
+        global $db, $user;
+        $packageHistoryObj = new PackageHistory($db);
+        $packageHistoryObj->fetch($id);
+        $packageHistoryObj->status = 1;
+        return $packageHistoryObj->update($user);
+    }
+
+    function getWithholdingRecords($withholdingArray)
+    {
+        foreach ($withholdingArray as $key => $value) {
+            $device_id = $this->getDeviceIdFromString($key);
+            $withholdingRecords[$device_id] = $value;
+        }
+        return $withholdingRecords;
+    }
+
+    function getDevicesList($devicesArray, $withholdingRecords)
+    {
+        foreach ($devicesArray as $devicevalue) {
+            $withholding = isset($withholdingRecords[$devicevalue['device_id']]) ? $withholdingRecords[$devicevalue['device_id']] : '';
+            $block2ndArray[] = ["rowid" => $devicevalue['rowid'], "device_id" => $devicevalue['device_id'], "title" => $devicevalue['title'], "ref" => $devicevalue["ref"], "status" => $devicevalue['status'], "withholding" => $withholding];
+        }
+        return $block2ndArray;
+    }
+
+    function getDailyIncomes($changes)
+    {
+        $block3rdArray = [];
+        if ($changes) {
+            foreach ($changes as $change) {
+                $tmpArray = explode('_', $change['ref']);
+                $block3rdArray[$tmpArray[1]] = $change['title'];
+            }
+        }
+        return $block3rdArray;
+    }
+
+    private function getDeviceIdFromString($key)
+    {
+        return substr($key, 1);
+    }
+
+    function unprintedFActures($group_id, $user_id, $from)
+    {
+        global $db, $langs;
+        $to = date("Y-m-d H:i:s", dol_now());
+        $sql = "SELECT f.rowid, f.ref, e.label, f.datec, f.total_ttc, f.multicurrency_code, f.fk_statut
+        FROM llx_facture AS f
+        INNER JOIN llx_entity AS e ON e.rowid = f.entity
+        WHERE 
+            f.fk_user_author = {$user_id} AND 
+            f.datec >= (SELECT un.date_creation FROM public.llx_settlements_usernaplo AS un WHERE un.user_id = {$user_id} AND un.group_user_id = {$group_id} AND un.status = 1 
+            /*AND date_trunc('day', un.date_creation) = CURRENT_DATE*/ ORDER BY un.rowid LIMIT 1) AND f.datec BETWEEN '{$from}' AND '{$to}' 
+            AND NOT EXISTS (SELECT 1 FROM llx_bbus_bbticketinvoiceprinting AS b WHERE b.fk_facture = f.rowid) 
+        ORDER BY f.rowid DESC;";
+        //print $sql;
+        $data = $db->query($sql);
+        $result = pg_fetch_all($data);
+        print '<table id="unprintedfactureslist" style="display:none; width:100%;">';
+        print '<tr class="center unprintedfacturetr">
+        <td style="width:15%;">' . $langs->trans('Invoice') . '</td>
+        <td style="width:20%;">' . $langs->trans('Company') . '</td>
+        <td style="width:20%;">' . $langs->trans('Date creation') . '</td>
+        <td style="width:20%;">' . $langs->trans('Amount') . '</td>
+        <td style="width:10%;">' . $langs->trans('Currency') . '</td>
+        <td>' . $langs->trans('Status') . '</td>
+        </tr>';
+        if (!empty($result)) {
+            foreach ($result as $record) {
+                print '<tr class="center">
+                <td><a href="/compta/facture/card.php?facid=' . $record['rowid'] . '&save_lastsearch_values=1">' . $record['ref'] . '</a></td>
+                <td>' . $record['label'] . '</td>
+                <td>' . $record['datec'] . '</td>
+                <td>' . $record['total_ttc'] . '</td>
+                <td>' . $record['multicurrency_code'] . '</td>
+                <td>' . $this->setStatut($record['fk_statut']) . '</td>
+                </tr>';
+            }
+        } else {
+            print '<tr><td style="color:red; text-align:center;" colspan="5">' . $langs->trans('Empty') . '</td></tr>';
+        }
+        print '</table>';
+    }
+
+    function printedFactures($group_id, $user_id)
+    {
+        global $db, $langs;
+        $now = date("Y-m-d H:i:s", dol_now());
+        $array = [];
+        $sql = "SELECT f.rowid
+        FROM llx_facture AS f
+        INNER JOIN llx_entity AS e ON e.rowid = f.entity
+        WHERE 
+            f.fk_user_author = {$user_id} AND 
+            f.datec >= (SELECT un.date_creation FROM public.llx_settlements_usernaplo AS un WHERE un.user_id = {$user_id} AND un.group_user_id = {$group_id} AND un.status = 1 
+            ORDER BY un.rowid LIMIT 1) AND f.datec <= '{$now}'
+            AND EXISTS (SELECT 1 FROM llx_bbus_bbticketinvoiceprinting AS b WHERE b.fk_facture = f.rowid) 
+        ORDER BY f.rowid DESC;";
+        //print $sql;
+        $data = $db->query($sql);
+        while ($row = pg_fetch_assoc($data)) {
+            $array[] = $row['rowid'];
+        }
+        return $array;
+    }
+
+    function setStatut($statut)
+    {
+        switch ($statut) {
+            case '0':
+                return '<span class="badge  badge-status0 badge-status">Tervezet</span>';
+                break;
+
+            case '2':
+                return '<span class="badge  badge-status6 badge-status">Fizetve</span>';
+                break;
+
+            case '1':
+                return '<span class="badge  badge-status1 badge-status">Nem fizetett</span>';
+                break;
+        }
+    }
+
+    function getTheNumberOfPrints($facture_id)
+    {
+        global $db;
+        $array = [];
+        $number = 0;
+        $sql = "SELECT tip.fk_facture, tip.product_id, count(tip.product_id)  FROM llx_bbus_bbticketinvoiceprinting as tip
+        WHERE tip.fk_facture = {$facture_id}
+        GROUP BY tip.fk_facture, tip.product_id";
+        $data = $db->query($sql);
+        while ($row = $db->fetch_object($data)) {
+            $array[$row->fk_facture][$row->product_id] = $row->count;
+        }
+        $firstKey = array_key_first($array);
+        $firstValue = $array[$firstKey];
+        $number = reset($firstValue);
+        return $number > 1 ? '<div style="color:red;">' . $number . '</div>' : '<div>' . $number . '</div>';
+    }
+
+}

+ 1 - 1
custom/settlements/core/tpl/dailyclosing_open.tpl.php

@@ -207,7 +207,7 @@ if (!empty($packageHistoryRecordObj) && $packageHistoryRecordObj->status == 0) {
                 </tr>';
     print '<tr><td>';
     print '<table>';
-    $printedFactures = $dailyClosing->printedFactures($packageHistoryRecordObj->fk_group_id, $user_id);
+    $printedFactures = $dailyClosing->printedFactures($user_id, $packageHistoryRecordObj->date_creation);
     $rownum = 0;
     print '<tr>
     <td colspan="2">&nbsp;<span class="fa fa-arrow-down"></span> <b>Mark for storno</b></td>

+ 255 - 0
custom/settlements/core/tpl/dailyclosing_open.tpl.php.bak

@@ -0,0 +1,255 @@
+<?php
+if (!empty($packageHistoryRecordObj) && $packageHistoryRecordObj->status == 0) {
+    print '<form method="POST" id="dailyclosingform" action="' . $url . '">' . "\n";
+    print '<input type="hidden" name="token" value="' . newToken() . '">';
+    print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
+    print '<input type="hidden" name="action" value="list">';
+    print '<input id="stornochange" type="hidden" name="stornochange" value="' . $stornochange . '">';
+    print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
+    print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
+    print '<input type="hidden" name="page" value="' . $page . '">';
+
+    $from = date('Y-m-d H:i:s', $packageHistoryRecordObj->date_creation);
+    $to = date('Y-m-d H:i:s', dol_now());
+
+    print '<div id="DCuserData" style="width: 50%; float:left;">';
+    print '<table style="width:100%;">';
+    print '<tr><td colspan="4" class="dailyClosingHeader">' . $name . '</td></tr>';
+    print '<tr><td colspan="4" class="center" style="height:50px;">' . $from . ' - ' . $to . '</td></tr>';
+    print '<tr><td colspan="4">' . $langs->trans('UserGroupName') . ':  <b>' . $helper->getUserGroupRefById($packageHistoryRecordObj->fk_groupuser_id) . '</b></td></tr>
+    <tr><td colspan="4">' . $langs->trans('ToolGroupName') . ':  <b> ' . $helper->getGroupLabelById($packageHistoryRecordObj->fk_group_id) . '</b></td></tr>
+    <tr><td colspan="4">' . $langs->trans('PackageName') . ': <b>' . $helper->getPackageLabelById($packageHistoryRecordObj->package_id) . '</b></td></tr>
+    &nbsp;';
+
+    #
+    #   Jutalék Lezárt
+    #
+    $commissionClosed = $commmissionhandler->getTotalCommissionFromThisPeriod($user_id, $from, $to);
+    print '<tr><td colspan="4">
+                <table class="dailyclosingTableLeftSide">
+                <tr><td style="text-align: center; background-color: lightgrey;" colspan="4">' . $langs->trans('CommissionClosed') . '</td></tr>';
+    if (count($commissionClosed) > 0) {
+        foreach ($commissionClosed as $commission) {
+            print '<tr style="height: 35px; text-align: center;"><td>' . $commission['date_creation'] . '</td><td>' . $commission['label'] . '</td><td style="width:350px;"><b>' . $helper->correctNumber(intval($commission['amount'])) . ' HUF</b></td></tr>';
+        }
+    } else {
+        print '<tr style="height: 35px; text-align: center;"><td colspan="3" style="color: red;">' . $langs->trans('NoCommission') . '</td></tr>';
+    }
+    print '</table>
+                &nbsp;
+    </td></tr>';
+    #
+    #   Jutalék (kalkulált)
+    #
+    $commission = $commmissionhandler->getTotalCommission($user_id, $from, $to);
+    print '<tr><td colspan="4">
+    <table class="dailyclosingTableLeftSide">
+                <tr><td style="text-align: center; background-color: lightgrey;" colspan="4">' . $langs->trans('ExpectedCommission') . '</td></tr>
+                <tr style="height: 35px; text-align: center;"><td style="width:350px;"><b>' . $helper->correctNumber(intval($commission)) . ' HUF</b></td></tr>
+                </table>
+                &nbsp;
+    </td></tr>';
+
+    $withholdingTD = '<td style="text-align: center; background-color: rgb(163, 0, 51); color:white;" colspan="2">' . $langs->trans('Withhold') . '</td>';
+
+    print '<tr><td style="text-align: center; background-color: lightgrey;" colspan="2">' . $langs->trans('DevicesList') . '</td>' . $withholdingTD . '</tr>';
+    #
+    # Eszközök listája
+    #
+
+    $counter = 1;
+
+    //print_r($withholdingsArray); exit;
+    //print_r($withholdingsChkArray);
+
+    if ($BLock2ndData) {
+        foreach ($BLock2ndData as $device) {
+            $displayConfirmButton = 'display:inline-block';
+            $displayPrinterButton = 'display:none';
+
+            # checkboxes
+
+            $checkedDevice = $dailyClosing->getChecked($deviceArray, $device);
+            $deviceWHChk = $dailyClosing->getDeviceWHChk($deviceArray, $device);
+            $deviceAmount = $dailyClosing->getDeviceAmount($amountArray, $device);
+            //print_r($checkedDevice);
+            $checkedDailyIncomeHUF = $dailyClosing->getCheckedDailyIncomeHUF($deviceArray);
+            $dailyAmountHUFChk = $dailyClosing->getDailyAmountHUFChk($deviceArray);
+            $checkedDailyIncomeEUR = $dailyClosing->getCheckedDailyIncomeEUR($deviceArray);
+            $dailyAmountEURChk = $dailyClosing->getDailyAmountEURChk($deviceArray);
+            $witholdingIdentifier = 'd' . $device['device_id'] . '_amount';
+            $witholdingChkIdentifier = 'd' . $device['device_id'];
+            if (isset($withholdingsArray[$witholdingIdentifier]) && $withholdingsArray[$witholdingIdentifier] !== '') {
+                $deviceAmount = $withholdingsArray[$witholdingIdentifier];
+            }
+            if ($withholdingsChkArray[$witholdingChkIdentifier] == '1') {
+                $checkedDevice = 'checked';
+                $deviceWHChk = "display:none;";
+            }
+            //print_r($checkedDevice);
+
+            print '<input type="hidden" name="withholding[withholdingchk][d' . $device['device_id'] . ']" value="x">';
+            print '<tr style="height: 35px;"><td style="width:200px;">' . $device['ref'] . '</td><td style="width:350px;">' . $device['title'] . '</td><td class="withholding"><input class="DCcheckbox" type="checkbox" name="withholding[withholdingchk][d' . $device['device_id'] . ']" data-chk="wh_' . $counter . '" data-input="wh_input_' . $counter . '" onclick="checkboxClick(event)" value="1" ' . $checkedDevice . ' ' . $disabled . '/></td><td class="fields withholding" id="wh_' . $counter . '" style="' . $deviceWHChk . '"><input class="inputfield" id="wh_input_' . $counter . '" name="withholding[withholdingAmount][d' . $device['device_id'] . '_amount]" style="display:inline-block;" type="field" value="' . $deviceAmount . '"' . $disabled . '/> HUF</td></tr>';
+            $counter++;
+        }
+    }
+    if (!empty($addititonalDevices)) {
+        foreach ($addititonalDevices as $key => $value) {
+            $device['device_id'] = $key;
+            $checkedAdditional = $dailyClosing->getChecked($deviceArray, $device);
+            $deviceWHChk = $dailyClosing->getDeviceWHChk($deviceArray, $device);
+            $deviceAmount = $dailyClosing->getDeviceAmount($amountArray, $device);
+            $witholdingIdentifier = 'd' . $key . '_amount';
+            $witholdingChkIdentifier = 'd' . $key;
+            if (isset($withholdingsArray[$witholdingIdentifier]) && $withholdingsArray[$witholdingIdentifier] !== '') {
+                $deviceAmount = $withholdingsArray[$witholdingIdentifier];
+            }
+            if ($withholdingsChkArray[$witholdingChkIdentifier] == '1') {   
+                $checkedAdditional = 'checked';
+                $deviceWHChk = "display:none;";
+            }
+            print '<input type="hidden" name="withholding[withholdingchk][d' . $key . ']" value="x">';
+            print '<tr style="height: 35px;"><td style="width:200px;">' . $helper->getAdditionalTitle($key) . '</td><td style="width:350px;">' . $value . '</td><td class="withholding" id="checkboxtdwh_' . $counter . '"><input class="DCcheckbox" type="checkbox" name="withholding[withholdingchk][d' . $key . ']" data-chk="wh_' . $counter . '" data-input="wh_input_' . $counter . '" onclick="checkboxClick(event)" value="1" ' . $checkedAdditional . ' ' . $disabled . '/></td><td class="fields withholding" id="wh_' . $counter . '" style="' . $deviceWHChk . '"><input class="inputfield" id="wh_input_' . $counter . '" name="withholding[withholdingAmount][d' . $key . '_amount]" style="display:inline-block;" type="field" value="' . $deviceAmount . '"' . $disabled . '/> HUF</td></tr>';
+            $counter++;
+        }
+    }
+    print '</table>&nbsp;';
+    #
+    # Napi bevétel KP
+    #
+
+    if (isset($withholdingsArray['_daily_HUFcash_amount']) && $withholdingsArray['_daily_HUFcash_amount'] !== '') {
+        $_daily_HUFcash_amount = $withholdingsArray['_daily_HUFcash_amount'];
+    }else{
+        $_daily_HUFcash_amount = $amountArray['_daily_HUFcash_amount'];
+    }
+    
+    if($withholdingsChkArray['_daily_HUFcash'] == 1){
+        $checkedDailyIncomeHUF = 'checked';
+        $dailyAmountHUFChk = "display:none";
+    }
+
+
+    if (isset($withholdingsArray['_daily_EURcash_amount']) && $withholdingsArray['_daily_EURcash_amount'] !== '') {
+        $_daily_EURcash_amount = $withholdingsArray['_daily_EURcash_amount'];
+    }else{
+        $_daily_EURcash_amount = $amountArray['_daily_EURcash_amount'];
+    }
+
+    if($withholdingsChkArray['_daily_EURcash'] == 1){
+        $checkedDailyIncomeEUR = 'checked';
+        $dailyAmountEURChk = "display:none";
+    }
+
+    print '<table class="dailyclosingTableLeftSide">
+                <tr><td style="text-align: center; background-color: lightgrey;" colspan="2">' . $langs->trans('DailyIncomeCash') . '</td>' . $withholdingTD . '</tr>
+                <input type="hidden" name="withholding[withholdingchk][_daily_HUFcash]" value="x">
+                <tr style="height: 35px;"><td style="width:200px;">' . $langs->trans('DailyIncomeCash') . ' HUF:</td><td style="width:350px; color:green; font-weight: bold;">' . $helper->correctNumber($BLock3rdData['HUFcash']) . ' HUF</td><td class="withholding"><input class="DCcheckbox" type="checkbox" name="withholding[withholdingchk][_daily_HUFcash]" data-chk="wh_' . $counter . '" data-input="wh_input_' . $counter . '" onclick="checkboxClick(event)" value="1"' . $checkedDailyIncomeHUF . ' ' . $disabled . '/></td><td class="fields withholding" id="wh_' . $counter . '" style="' . $dailyAmountHUFChk . '"><input class="inputfield" id="wh_input_' . $counter . '" name="withholding[withholdingAmount][_daily_HUFcash_amount]" style="display:inline-block;" type="field" value="' . $_daily_HUFcash_amount . '" ' . $disabled . '/> HUF</td></tr>';
+    $counter++;
+    print '<input type="hidden" name="withholding[withholdingchk][_daily_EURcash]" value="x">
+                <tr style="height: 35px;"><td style="width:200px;">' . $langs->trans('DailyIncomeCash') . ' EUR:</td><td style="width:350px; color:green; font-weight: bold;">' . $helper->correctNumber($BLock3rdData['EURcash']) . ' EUR</td><td class="withholding"><input class="DCcheckbox" type="checkbox"  name="withholding[withholdingchk][_daily_EURcash]" data-chk="wh_' . $counter . '" data-input="wh_input_' . $counter . '" onclick="checkboxClick(event)" value="1"' . $checkedDailyIncomeEUR . ' ' . $disabled . '/></td><td class="fields withholding" id="wh_' . $counter . '" style="' . $dailyAmountEURChk . '"><input class="inputfield" id="wh_input_' . $counter . '" name="withholding[withholdingAmount][_daily_EURcash_amount]" style="display:inline-block;" type="field" value="' . $_daily_EURcash_amount . '" ' . $disabled . '/> HUF</td></tr>
+                </table>';
+
+    #
+    # Napi bevétel kártya
+    #                
+    print '<table class="dailyclosingTableLeftSide">
+                <tr><td style="text-align: center; background-color: lightgrey;" colspan="4">' . $langs->trans('DailyIncomeCard') . '</td></tr>
+                <tr style="height: 35px;"><td style="width:200px;"> HUF:</td><td style="width:350px;"><b>' . $helper->correctNumber(intval($BLock3rdData['HUFcard'])) . ' HUF</b></td><td style="width:10px;"></td><td></td></tr>
+                <tr style="height: 35px;"><td style="width:200px;"> EUR:</td><td style=""><b>' . $helper->correctNumber((intval($BLock3rdData['EURcard']))) . ' EUR </b></td><td></td><td></td></tr>
+                </table>
+                &nbsp;';
+    #
+    # Teljes összeg KP + váltó
+    #
+    print '<table class="dailyclosingTableLeftSide">
+                <tr><td style="text-align: center; background-color: lightgrey;" colspan="4">' . $langs->trans('TotalAmountCash') . '</td></tr>
+                <tr style="text-align: center;"><td style="width:200px;">&nbsp;</td><td>' . $langs->trans('DailyIncomeCash') . '</td><td>' . $langs->trans('Change') . '</td><td>' . $langs->trans('TotalAmountCash') . '</td></tr>
+                <tr style="height: 35px;"><td style="width:200px;"> HUF:</td><td style="text-align: center;">' . $helper->correctNumber($BLock3rdData['HUFcash']) . ' HUF </td><td style="text-align: center;">' . $helper->correctNumber(intval($addititonalChangesDevices['change_huf'])) . ' HUF </td><td style="text-align: center;"><b>' . $helper->correctNumber(intval($BLock3rdData['HUFcash'] + intval($addititonalChangesDevices['change_huf']))) . ' HUF</b></td><td style="width:10px;"></td></tr>
+                <tr style="height: 35px;"><td style="width:200px;"> EUR:</td><td style="text-align: center;">' . $helper->correctNumber($BLock3rdData['EURcash']) . ' EUR </td><td style="text-align: center;">' . $helper->correctNumber(intval($addititonalChangesDevices['change_eur'])) . ' EUR </td><td style="text-align: center;"><b>' . $helper->correctNumber((intval($BLock3rdData['EURcash']) + intval($addititonalChangesDevices['change_eur']))) . ' EUR</b></td></tr>
+                </table>
+                &nbsp;';
+    #
+    # Teljes összeg KP + kartya
+    #
+    print '<table class="dailyclosingTableLeftSide">
+                <tr><td style="text-align: center; background-color: lightgrey;" colspan="4">' . $langs->trans('TotalAmount') . '</td></tr>
+                <tr style="text-align: center;"><td style="width:200px;">&nbsp;</td><td>' . $langs->trans('DailyIncomeCash') . '</td><td>' . $langs->trans('DailyIncomeCard') . '</td><td>' . $langs->trans('TotalAmount') . '</td></tr>
+                <tr style="height: 35px;"><td style="width:200px;"> HUF:</td><td style="text-align: center;">' . $helper->correctNumber($BLock3rdData['HUFcash']) . ' HUF </td><td style="text-align: center;">' . $helper->correctNumber($BLock3rdData['HUFcard']) . ' HUF </td><td style="text-align: center;"><b>' . $helper->correctNumber(intval($BLock3rdData['HUFcash'] + intval($BLock3rdData['HUFcard']))) . ' HUF</b></td></tr>
+                <tr style="height: 35px;"><td style="width:200px;"> EUR:</td><td style="text-align: center;">' . $helper->correctNumber($BLock3rdData['EURcash']) . ' EUR </td><td style="text-align: center;">' . $helper->correctNumber($BLock3rdData['EURcard']) . ' EUR </td><td style="text-align: center;"><b>' . $helper->correctNumber(intval($BLock3rdData['EURcash']) + intval($BLock3rdData['EURcard'])) . ' EUR</b></td></tr>
+                </table>
+                &nbsp;';
+
+    #
+    #   Unprinted factures
+    #                
+    print '<table class="dailyclosingTableLeftSide">';
+    print '<tr onclick="showFactures(event)"><td colspan="4" class="unprintedfactures">Unprinted factures<span id="unprintedFactureSpan" class="fa fa-chevron-down" style="float:right; padding-right: 10px; padding-top:3px;"></span></td></tr>';
+    print '</table>';
+    print $dailyClosing->unprintedFactures($packageHistoryRecordObj->fk_group_id, $user_id, $from);
+    #
+    # Checkbox
+    #
+    print '<div>&nbsp;</div>';
+    print '<div style="' . $displayConfirmButton . '">
+            <div><input type="checkbox" onclick="checkall(event)" />' . $langs->trans('EverythingOK') . '</div>&nbsp;';
+
+    #
+    # Confirm buttons
+    #
+    print '<div><button type="submit" name"confirmdailyclosing" value="1">' . $langs->trans('DailyClosing') . '</button></div>';
+    print '</div></div>';
+    print '&nbsp;';
+    print '<div id="DCFactureData" style="width: 50%; float:left;">
+        <table style="width:100%;">
+            <tr>
+                <td colspan="4" class="dailyClosingHeader">' . $langs->trans('FactureList') . '</td>
+                </tr>';
+    print '<tr><td>';
+    print '<table>';
+    $printedFactures = $dailyClosing->printedFactures($packageHistoryRecordObj->fk_group_id, $user_id);
+    $rownum = 0;
+    print '<tr>
+    <td colspan="2">&nbsp;<span class="fa fa-arrow-down"></span> <b>Mark for storno</b></td>
+    <td colspan="2">&nbsp;<span class="fa fa-arrow-down"></span> <b>No commission</b></td>
+    <td></td>
+    <td></td>
+    <td colspan="3" style="text-align:right;"><b>Number of prints </b><span style="margin-right: 10px;" class="fa fa-arrow-down"></span></td>
+    </tr>';
+    foreach ($factures as $facture) {
+        $checked = $facture['marked_for_storno'] ? 'checked' : '';
+        $checkedCommission = $facture['commission_deduction'] ? 'checked' : '';
+        $bgcolor = $dailyClosing->setRowColor($rownum);
+        $printed = '';
+        $numberOfPrints = 0;
+        //$disabled = $facture['marked_for_storno'] ? 'disabled' : '';
+
+        if (in_array($facture['rowid'], $printedFactures)) {
+            $printed = '<div style="color:green;">Printed</div>';
+            $numberOfPrints = $dailyClosing->getTheNumberOfPrints($facture['rowid']);
+        }
+        print '<tr style="background-color: ' . $bgcolor . '">
+        <td style="width: 5%"><input type="checkbox" name="storno" value="' . $facture['rowid'] . '" ' . $checked . ' ' . $disabled . ' onclick="setStorno(event)"></input></td>
+        <td style="width: 25%"><a href="/compta/facture/card.php?facid=' . $facture['rowid'] . '&save_lastsearch_values=1">' . $facture['ref'] . ' <span class="fa fa-link"></span></a></td>
+        <td style="width: 5%"><input type="checkbox" name="commission" value="' . $facture['rowid'] . '" ' . $checkedCommission . ' ' . $disabled . ' onclick="setCommission(event)"></input></td>
+        <td style="width: 20%">' . $facture['date_closing'] . '</td>
+        <td style="width: 15%" class="center">' . $facture['libelle'] . '</td>
+        <td style="width: 10%" class="center">' . $helper->correctNumber(intval($facture['multicurrency_total_ttc'])) . '</td>
+        <td style="width: 10%" class="center">' . $facture['multicurrency_code'] . '</td>
+        <td style="width: 5%" class="center">' . $printed . '</td>
+        <td style="width: 5%" class="center">' . $numberOfPrints . '</td>
+        </tr>';
+        $rownum++;
+    }
+
+    print '</table></td></tr>';
+    print '</table>
+    </div>';
+    print '</form>';
+} else {
+    print '<div id="DCuserData" style="width:50%;">';
+    print '<table style="width:100%;"><tr><td colspan="4" class="dailyClosingHeader">' . $name . '</td></tr></table>';
+    print '<div style="color: red; margin-top: 50px;">' . $langs->trans('NoDailyClosing') . '</div>';
+    print '<div style="margin-top: 20px;"><a href="settlementtoolssettingsindex.php?idmenu=1594&mainmenu=settlements&leftmenu=&id=' . $packageHistoryRecordObj->fk_group_id . '&nopackageuser=1">' . $langs->trans('BackToGroup') . '</a></div>';
+    print '</div>';
+}

+ 4 - 1
includes/restler/framework/Luracast/Restler/RestException.php

@@ -67,7 +67,10 @@ class RestException extends Exception
         503 => 'Service Unavailable',
         504 => 'Gateway Timeout',
         505 => 'HTTP Version Not Supported',
-        506 => 'No available spaces'
+        506 => 'No available spaces',
+        507 => 'Too many RentHistory',
+        508 => 'No RentHistory',
+        509 => 'DB error'
     );
     private $details;
     private $stage;