Browse Source

added Raport generate progress bar

Piotr Labudda 7 years ago
parent
commit
3b192f621a
3 changed files with 262 additions and 3 deletions
  1. 137 0
      theme/assets/js/updateRaportProgress.js
  2. 10 0
      theme/bocian.php
  3. 115 3
      tools/Bocian.php

+ 137 - 0
theme/assets/js/updateRaportProgress.js

@@ -0,0 +1,137 @@
+var DBG = DBG || false
+var DBG_FAKE_ANIM = DBG_FAKE_ANIM || false
+if (!URL_FETCH_BI_AUDIT_PROGRESS) throw "Missing URL_FETCH_BI_AUDIT_PROGRESS"
+
+if (!jQuery('#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA').length) return;
+
+var IS_STARTED = false
+var DBG_COUNTER = 0;
+
+function getTableAjaxStruct() {
+	var tblNode = jQuery('#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA > table.AjaxTable')
+	var fieldCells = tblNode.find('> thead > tr.tblAjax__head__sort > th > span')
+	var idCells = tblNode.find('> tbody > tr > td:nth-child(2)')
+	// if(DBG)console.log('updateRaportProgress ('+DBG_COUNTER+') idCells: ', idCells);
+	if (!idCells.length || !fieldCells.length) {
+		return null;
+	}
+	// FILE_STATUS -> 'IN_PROGRESS'
+	// FILE_STATUS_info -> 'W trakcie generowania powiązań'
+	var fields = fieldCells.toArray().map(function (el) {
+		// if(DBG)console.log('updateRaportProgress ('+DBG_COUNTER+') fields loop ('+idx+'): el', el.title);
+		if (!el.title) return '';
+		var title = el.title
+		var fieldName = ''
+		if (')' === title.substr(-1)) {
+			var pos = title.lastIndexOf('(')
+			if (-1 !== pos) {
+				fieldName = title.substring(pos + 1, title.length - 1)
+			}
+		}
+		return fieldName;
+	})
+	if(DBG)console.log('getTableAjaxStruct ('+DBG_COUNTER+') fields: ', fields);
+	var fieldStatusIdx = fields.indexOf('FILE_STATUS');
+	var fieldStatusInfoIdx = fields.indexOf('FILE_STATUS_info');
+	if(DBG)console.log('getTableAjaxStruct ('+DBG_COUNTER+') idx('+fieldStatusIdx+','+fieldStatusInfoIdx+')');
+
+	var ids = idCells.toArray().map(function (el) {
+		return parseInt(jQuery(el).text());
+	})
+	if(DBG)console.log('getTableAjaxStruct ('+DBG_COUNTER+') ids: ', ids);
+
+	var statusNodes = (fieldStatusIdx > 0) ? tblNode.find('> tbody > tr > td:nth-child(' + (2 + fieldStatusIdx) + ')').toArray() : []
+	var statusInfoNodes = (fieldStatusInfoIdx > 0) ? tblNode.find('> tbody > tr > td:nth-child(' + (2 + fieldStatusInfoIdx) + ')').toArray() : []
+	var statuses = statusNodes.map(function (el) {
+		return jQuery(el).text()
+	})
+
+	return {
+		fields: fields,
+		fieldStatusIdx: fieldStatusIdx,
+		fieldStatusInfoIdx: fieldStatusInfoIdx,
+		ids: ids,
+		statusNodes: statusNodes,
+		statusInfoNodes: statusInfoNodes,
+		statuses: statuses,
+	}
+}
+
+function updateTableAjaxView(respJson) {
+	if (!respJson.body || !respJson.body.ids || !respJson.body.progress) return;
+	var tblStruct = getTableAjaxStruct()
+	if (!tblStruct) return;
+
+	if(DBG)console.log('DBG:updateTableAjaxView', {respJson: respJson, tblStruct: tblStruct});
+
+	tblStruct.statusNodes.forEach(function (el, idx) {
+		var id = tblStruct.ids[idx]
+		var respId = respJson.body.ids[idx]
+		if (id !== respId) return; // view updated before response
+		var progress = respJson.body.progress[idx]
+		var percent = Math.round(100 * progress)
+		if (DBG_FAKE_ANIM && percent > 0 && percent < 100) percent += (DBG_COUNTER * 10)
+		if(DBG)console.log('DBG:updateTableAjaxView loop ('+idx+', el)', {el: el, id: id, progress: progress, pr: percent });
+		var status = (respJson.body.statuses[idx]) ? respJson.body.statuses[idx] : null
+		if (DBG_FAKE_ANIM) status = (percent < 100) ? 'IN_PROGRES' : 'DONE'
+		updatePercentView(el, {
+			percent: percent,
+			status: status,
+		})
+		var statusInfo = (respJson.body.statusesInfo[idx]) ? respJson.body.statusesInfo[idx] : null
+		if (statusInfo && tblStruct.statusInfoNodes && tblStruct.statusInfoNodes[idx]) updateStatusInfoView(tblStruct.statusInfoNodes[idx], statusInfo)
+	})
+}
+
+function updateStatusInfoView(el, statusInfo) {
+	if (statusInfo) jQuery(el).find('span').text(statusInfo)
+}
+
+function updatePercentView(el, props) {
+	var hrNode = jQuery(el).find('hr')
+	if (!hrNode.length) hrNode = jQuery('<hr>').appendTo(el)
+	if (props.percent > 100) props.percent = 100
+	hrNode.attr('style', "margin:0; padding:0; border-bottom:3px solid #f00; width:" + props.percent + "%")
+	if (props.status) jQuery(el).find('span').text(props.status)
+}
+
+function updateRaportProgress() {
+	DBG_COUNTER += 1
+	if(DBG)console.log('updateRaportProgress ('+DBG_COUNTER+')');
+
+	var tblStruct = getTableAjaxStruct()
+	if(DBG)console.log('updateRaportProgress ('+DBG_COUNTER+') tblStruct', tblStruct);
+	if (!tblStruct) {
+		global.setTimeout(updateRaportProgress, 3000)
+		return;
+	}
+
+	global.fetch(URL_FETCH_BI_AUDIT_PROGRESS, {
+	  method: 'POST',
+		credentials: 	'same-origin',
+	  body: JSON.stringify({
+	    ids: tblStruct.ids,
+	  })
+	}).then(function (response) {
+		return response.json()
+	}).then(function (respJson) {
+		updateTableAjaxView(respJson)
+		IS_STARTED = false;
+		startUpdateRaportProgress()
+	}).catch(function (e) {
+		if(DBG)console.warn('e:', e)
+		IS_STARTED = false
+	})
+
+	IS_STARTED = false
+}
+
+function startUpdateRaportProgress() {
+	if (IS_STARTED) return;
+	IS_STARTED = true
+	if(DBG)console.log('START updateRaportProgress ...');
+	global.setTimeout(updateRaportProgress, 1000)
+}
+
+
+jQuery('#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA').on('TableAjax:render', startUpdateRaportProgress)

+ 10 - 0
theme/bocian.php

@@ -25,6 +25,16 @@ class Theme_bocian extends ThemeDefault {
 		include dirname(__FILE__) . '/view/footer.php';
 		//todo: ujednolicic wczytanie themy widoków i css w jednym katalogu(obecnie css w katalogu static a widoki w katalogu tmp )
 		UI::inlineRawJS(dirname(__FILE__) . '/assets/js/scripts.js');
+
+		if ('ViewTableAjax' === V::get('_route', '', $_GET)
+			&& 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA' === V::get('namespace', '', $_GET)
+		) {
+			UI::inlineJS(dirname(__FILE__) . '/assets/js/updateRaportProgress.js', [
+				'DBG' => (V::get('DBG', '', $_GET)),
+				'DBG_FAKE_ANIM' => (V::get('DBG_FAKE_ANIM', '', $_GET)),
+				'URL_FETCH_BI_AUDIT_PROGRESS' => Router::getRoute('UrlAction_Bocian')->getLink('fetchProgressAjax')
+			]);
+		}
 	}
 
 	function login($data) {

+ 115 - 3
tools/Bocian.php

@@ -5,7 +5,7 @@ Lib::loadClass('UI');
 Lib::loadClass('Response');
 Lib::loadClass('Request');
 
-// index.php?_route=UrlAction_BiAuditRaport  - uruchamia defaultAction
+// index.php?_route=UrlAction_Bocian  - uruchamia defaultAction
 class RouteTool_Bocian extends RouteToolBase {
 
 public static $helpEmailTo = 'biuro@bialnet.com.pl'; // email na który zostanie wysłane zapytanie z formularza POMOCY
@@ -1795,9 +1795,121 @@ public function showPowiazaniaEnergaRumKontrahenciPowiazania($items) {
 			}
 	}
 
+	function fetchProgressAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchProgressAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	function fetchProgressAjax($args) {
+		$DBG_FAKE_ANIM = false;
+		if (empty($args['ids'])) return [ 'msg' => "empty ids", 'type' => "success" ];
+		$ids = $args['ids'];
+
+		// private static function getDirectory($table, $id) {
+		$firstId = reset($ids);
+		{
+			Lib::loadClass('FoldersConfig');
+			$folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
+			if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
+			$rootPath = $folderConf['mount_point'];
+		}
 
+		$statuses = array_map(function ($id) {
+			return DB::getPDO()->fetchValue(" select FILE_STATUS from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = :id ", [ ':id' => $id ]);
+		}, $ids);
+		$statusesInfo = array_map(function ($id) {
+			return DB::getPDO()->fetchValue(" select FILE_STATUS_info from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = :id ", [ ':id' => $id ]);
+		}, $ids);
+		$progress = array_map(function ($id, $idx) use ($rootPath, $statuses, $DBG_FAKE_ANIM) {
+			DBG::log("Loop id({$id}) is-eq-82(".(82 == $id).") is-eq-'82'(".("82"==$id).")");
+			DBG::log("Loop id({$id}) is-eq-80(".(80 == $id).") is-eq-'80'(".("80"==$id).")");
+			$status = $statuses[$idx];
+			if ($DBG_FAKE_ANIM && 82 == $id) $status = 'IN_PROGRESS'; // TODO: DBG
+			if ($DBG_FAKE_ANIM && 80 == $id) $status = 'IN_PROGRESS'; // TODO: DBG
+			if ($DBG_FAKE_ANIM && 77 == $id) $status = 'IN_PROGRESS'; // TODO: DBG
+			DBG::log("Loop id({$id}) status({$status})...");
+
+			if ('GENERATED' === $status) return 1;
+			if ('IN_PROGRESS' !== $status) return 0;
+
+			if (!file_exists("{$rootPath}/.tasks/generatePowiazania-{$id}.progress")) return 0;
+			DBG::log("Loop id({$id}) status({$status}) progress file exists");
+			try {
+				$cnt = file_get_contents("{$rootPath}/.tasks/generatePowiazania-{$id}.progress");
+				$json = @json_decode($cnt, $assoc = true);
+				if (null === $json && 0 !== json_last_error()) {
+					throw new Exception("Parse json error for restrictions: " . json_last_error());
+				}
+				// $json['summary']['step']: 'initialize', 'relations', 'reports'
+				// $json['summary']['step'] = 'initialize' - recache - skip
+				// $json['summary']['step'] = 'relations' - szuka powiązań (@see AVG(details.progress / summary.count))
+				// $json['summary']['step'] = 'reports' - generuje pliki (@see summary.created)
+				if ($DBG_FAKE_ANIM && 82 == $id) { // TODO: DBG
+					$json = [
+						'summary' => [
+							'count' => 4,
+							'step' => 'relations',
+						],
+						'details' => [
+							'9'  => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+							'19' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+							'22' => [ 'progress' => 0, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+							'25' => [ 'progress' => 0, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+					] ];
+				}
+				if ($DBG_FAKE_ANIM && 80 == $id) { // TODO: DBG
+					$json = [
+						'summary' => [
+							'count' => 4,
+							'created' => 2,
+							'step' => 'reports',
+						],
+						'details' => [
+							'9'  => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+							'19' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+							'22' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+							'25' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+					] ];
+				}
+				if ($DBG_FAKE_ANIM && 77 == $id) { // TODO: DBG
+					$json = [
+						'summary' => [
+							'count' => 4,
+							'created' => 2,
+							'step' => 'relations',
+						],
+						'details' => [
+							'9'  => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+							'19' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+							'22' => [ 'progress' => 0.25, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+							'25' => [ 'progress' => 0, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
+					] ];
+				}
+				DBG::log($json, 'array', "Loop id({$id}) status({$status}) progress json");
+
+				if (empty($json['summary'])) return 0;
+				if (empty($json['summary']['count'])) return 0;
+				if (empty($json['summary']['step'])) return 0;
+				if (empty($json['details'])) return 0;
+				if ('relations' === $json['summary']['step']
+					|| 'reports' === $json['summary']['step']
+				) {
+					$listDetailsProgress = array_map(function ($detail) {
+						return floatval($detail['progress']);
+					}, $json['details']);
+					return (array_sum($listDetailsProgress) + V::get('created', 0, $json['summary'], 'int')) / ($json['summary']['count'] * 2);
+				}
 
-
-
+				return 0;
+			} catch (Exception $e) {
+				DBG::log($e);
+			}
+			return 0;
+		}, $ids, array_keys($ids));
+		return [ 'msg' => "DBG ids set", 'type' => "success", 'body' => [
+			'ids' => $ids,
+			'progress' => $progress,
+			'statuses' => $statuses,
+			'statusesInfo' => $statusesInfo,
+		] ];
+	}
 
 }