Jelajahi Sumber

added Storage table actions

Piotr Labudda 9 tahun lalu
induk
melakukan
8f6cfb58bb
2 mengubah file dengan 319 tambahan dan 47 penghapusan
  1. 197 47
      SE/se-lib/Route/Storage.php
  2. 122 0
      SE/se-lib/Route/Storage.php.tableActions.js

+ 197 - 47
SE/se-lib/Route/Storage.php

@@ -518,7 +518,7 @@ jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', fun
 		$this->navView();
 		try {
 			$idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
-			if (empty($idStorage)) throw new Exception("No id storage");
+			if (empty($idStorage)) throw new Exception("Missing id storage");
 			$storageList = $this->getStorageList();
 			if (empty($storageList)) throw new Exception("No storage defined");
 			if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage id='{$idStorage}' not exists");
@@ -631,10 +631,10 @@ jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(
 		$this->navView();
 		try {
 			$idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
-			if (empty($idStorage)) throw new Exception("No id storage");
+			if (empty($idStorage)) throw new Exception("Missing id storage");
 			$storageList = $this->getStorageList();
 			if (empty($storageList)) throw new Exception("No storage defined");
-			if (!array_key_exists($idStorage, $storageList)) throw new Exception("No id storage not exists");
+			if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
 
 			$storagePdo = DB::getStorage($idStorage);
 			$rawInfo = $storagePdo->getTableListWithInfo();
@@ -651,10 +651,10 @@ jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(
 		$this->navView();
 		try {
 			$idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
-			if (empty($idStorage)) throw new Exception("No id storage");
+			if (empty($idStorage)) throw new Exception("Missing id storage");
 			$storageList = $this->getStorageList();
 			if (empty($storageList)) throw new Exception("No storage defined");
-			if (!array_key_exists($idStorage, $storageList)) throw new Exception("No id storage not exists");
+			if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
 			$tblName = V::get('table', '', $_REQUEST, 'word');
 			if (empty($tblName)) throw new Exception("No table name");
 
@@ -670,7 +670,7 @@ jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(
 
 			$cellZasobList = array();
 			foreach (DB::getPDO()->fetchAllByKey("
-					select z.ID, z.`DESC`, z.A_STATUS
+					select z.ID, z.`DESC`, z.`TYPE` as ZASOB_TYPE, z.A_STATUS
 					from CRM_LISTA_ZASOBOW z
 					where z.PARENT_ID = '{$idTable}'
 				", $key = 'DESC') as $ind => $row) {
@@ -680,6 +680,7 @@ jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(
 			$emptyItem = array();
 			$emptyItem['name'] = '';
 			$emptyItem['id_zasob'] = '';
+			$emptyItem['zasob_type'] = '';
 			$emptyItem['uwagi'] = '';
 
 			$emptyItem['type'] = '';
@@ -708,6 +709,7 @@ jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(
 				if ($tblZasob) {
 					$cellZasobList[$lowerCellName]['_checked'] = true;
 					$tblItem['id_zasob'] = $tblZasob['ID'];
+					$tblItem['zasob_type'] = $tblZasob['ZASOB_TYPE'];
 				} else {
 					$tblItem['uwagi'] .= '!Zasob';//'TODO: ADD ZASOB';
 					$ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addCellToZasoby&idStorage={$idStorage}&tblName={$tblName}&cellName={$cellName}";
@@ -717,10 +719,12 @@ jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(
 				$tableList[] = $tblItem;
 			}
 			foreach ($cellZasobList as $cellName => $row) {
+				if ('URL_ACTION' == $row['ZASOB_TYPE']) continue;
 				if (!$row['_checked']) {
 					$tblItem = V::cloneArray($emptyItem);
 					$tblItem['name'] = $cellName;
 					$tblItem['id_zasob'] = $row['ID'];
+					$tblItem['zasob_type'] = $row['ZASOB_TYPE'];
 					$tblItem['uwagi'] = '!DB';//'TODO: nie istnieje w bazie danych';
 					$tableList[] = $tblItem;
 				}
@@ -736,61 +740,207 @@ jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(
 				}
 				return ($a < $b) ? -1 : 1;
 			});
-			DBG::table("tableList", $tableList, __CLASS__, __FUNCTION__, __LINE__);
-?>
-<script>
-jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:click', function(e, n, payload) {
-	console.log('event p5UIBtnAjax:Storage:addCellToZasoby:click', n, payload);
-});
-jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', function(e, n, payload) {
-	console.log('event p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', n, payload);
-	if ('success' == payload.type && payload.body && payload.body.id > 0) {
-		var cellUwagi$Node = jQuery(n).parents('td').next('td');
-		cellUwagi$Node.text(cellUwagi$Node.text().replace('!Zasob', ''))
-		jQuery(n).parents('td').text(payload.body.id);
-		jQuery(n).remove();
-	}
-	jQuery.notify(payload.msg, payload.type);
-});
-</script>
-<?php
-
+			UI::table([
+				'caption' => "tableList",
+				'cols' => array_keys($emptyItem),
+				'rows' => $tableList
+			]);
+			echo UI::h('script', [], "
+				jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:click', function(e, n, payload) {
+					console.log('event p5UIBtnAjax:Storage:addCellToZasoby:click', n, payload);
+				});
+				jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', function(e, n, payload) {
+					console.log('event p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', n, payload);
+					if ('success' == payload.type && payload.body && payload.body.id > 0) {
+						var cellUwagiJQNode = jQuery(n).parents('td').next('td');
+						cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
+						jQuery(n).parents('td').text(payload.body.id);
+						jQuery(n).remove();
+					}
+					jQuery.notify(payload.msg, payload.type);
+				});
+			");
 			$ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addGeomEtykietaCells&idStorage={$idStorage}&tblName={$tblName}";
 			$onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addGeomEtykietaCells', { href: '{$ajaxAddZasobLink}' })";
 			UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj komórki etykiet", true);
 			echo "<i>(<code>`etykieta_x`</code>, <code>`etykieta_y`</code>, <code>`etykieta_obrot`</code>)</i>";
-?>
-<script>
-jQuery(document).on('p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', function(e, n, payload) {
-	console.log('event p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', n, payload);
-	if ('success' == payload.type && payload.body && payload.body.id > 0) {
-		var cellUwagi$Node = jQuery(n).parents('td').next('td');
-		cellUwagi$Node.text(cellUwagi$Node.text().replace('!Zasob', ''))
-		jQuery(n).parents('td').text(payload.body.id);
-		jQuery(n).remove();
-	}
-	jQuery.notify(payload.msg, payload.type);
-});
-</script>
-<?php
+			echo UI::h('script', [], "
+				jQuery(document).on('p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', function(e, n, payload) {
+					console.log('event p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', n, payload);
+					if ('success' == payload.type && payload.body && payload.body.id > 0) {
+						var cellUwagiJQNode = jQuery(n).parents('td').next('td');
+						cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
+						jQuery(n).parents('td').text(payload.body.id);
+						jQuery(n).remove();
+					}
+					jQuery.notify(payload.msg, payload.type);
+				});
+			");
 
+
+			$tableActions = array_filter($cellZasobList, function ($row) {
+				return ('URL_ACTION' == $row['ZASOB_TYPE']);
+			});
+			UI::table([
+				'caption' => "tableActions",
+				// 'cols' => array_keys($emptyItem),
+				'rows' => array_map(function ($item) {
+					$sqlIdAction = DB::getPDO()->quote($item['ID'], PDO::PARAM_INT);
+					$args = DB::getPDO()->fetchAll("
+						select z.`DESC`
+								, a.ID as ALIAS_ID, a.`DESC` as ALIAS_DESC, a.OPIS as ALIAS_OPIS
+						from CRM_LISTA_ZASOBOW z
+							left join CRM_LISTA_ZASOBOW a on(a.ID = z.ALIAS_ID)
+						where z.PARENT_ID = {$sqlIdAction}
+							and z.`TYPE` = 'PARAM_IN'
+					");
+					$definitionArgs = DB::getPDO()->fetchAll("
+						select p.ID, p.`DESC`
+						from CRM_LISTA_ZASOBOW z
+							join CRM_LISTA_ZASOBOW d on(d.ID = z.ALIAS_ID)
+							left join CRM_LISTA_ZASOBOW p on(p.PARENT_ID = d.ID)
+						where z.ID = {$sqlIdAction}
+							and p.`TYPE` = 'PARAM_IN'
+					");
+					$flatDefinitionArgs = implode(";", array_map(function ($arg) {
+						return "{$arg['ID']}={$arg['DESC']}";
+					}, $definitionArgs));
+					return [
+						'label' => DB::getPDO()->fetchValue(" select z.OPIS from CRM_LISTA_ZASOBOW z where z.ID = {$sqlIdAction} ") . " " .
+							UI::h('i', [
+								'class' => "glyphicon glyphicon-pencil",
+								'style' => "cursor:pointer",
+								'onClick' => "return Storage__tableStruct__editActionLabel(this, {$sqlIdAction})"], ''),
+						'args' => implode("<br>&", array_map(function ($item) {
+							return (NULL === $item['ALIAS_ID'])
+								? $item['DESC']
+								: "{$item['DESC']}=" . '{$row["' . $item['ALIAS_DESC'] . '"]}';// TODO: add rmParam btn
+						}, $args)) . " " .
+							UI::h('i', [
+								'class' => "glyphicon glyphicon-plus-sign",
+								'style' => "cursor:pointer",
+								'title' => "Dodaj PARAM_IN",
+								'onClick' => "return Storage__tableStruct__addParamAction(this, {$sqlIdAction}, '{$flatDefinitionArgs}')"], ''),
+						// 'args_info' => '<pre>' . var_export($args, true) . '</pre>',
+						'ID' => $item['ID'],
+						'DESC' => $item['DESC'],
+						'A_STATUS' => $item['A_STATUS'],
+						'definition args' => implode("", array_map(function ($item) {
+							return '<div style="white-space:nowrap">' . "[{$item['ID']}] {$item['DESC']}" . '</div>';
+						}, $definitionArgs)),
+					];
+				}, $tableActions)
+			]);
+			echo UI::h('button', [
+				'onClick'=>"Storage__tableStruct__addAction()",
+				'class'=>"btn btn-xs btn-default"
+			], "Dodaj Akcję");
+			echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
+			echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
+			echo UI::h('style', [], "
+				.swal2-radio.p5-swal-radio-as-list { text-align:left }
+				.swal2-radio.p5-swal-radio-as-list > label { display:block; margin-left:20px }
+			");
+			UI::inlineJS(__FILE__ . '.tableActions.js', [
+				'ID_STORAGE' => $idStorage,
+				'TABLE_NAME' => $tblName,
+				'FETCH_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=fetchActionListAjax',
+				'ADD_ACTION_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=addActionAjax'
+			]);
 			echo '<hr>';
+
 			$ajaxAddBaseProcesLink = Request::getPathUri() . "index.php?_route=Storage&_task=addBaseProces&idStorage={$idStorage}&tblName={$tblName}";
 			$onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addBaseProces', { href: '{$ajaxAddBaseProcesLink}' })";
 			UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj podstawowy proces dla tabeli '{$tblName}' - read only", true);
-			?>
-<script>
-jQuery(document).on('p5UIBtnAjax:Storage:addBaseProces:ajaxLoaded', function(e, n, payload) {
-	jQuery.notify(payload.msg, payload.type);
-});
-</script>
-			<?php
+			echo UI::h('script', [], "
+				jQuery(document).on('p5UIBtnAjax:Storage:addBaseProces:ajaxLoaded', function(e, n, payload) {
+					jQuery.notify(payload.msg, payload.type);
+				});
+			");
 		} catch (Exception $e) {
 			UI::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
 		}
 		UI::dol();
 	}
 
+	public function fetchActionListAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchActionListAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function fetchActionListAjax($args) {
+		return [
+			'type' => 'success',
+			'__args' => $args,
+			'options' => DB::getPDO()->fetchAll("
+				select z.ID, z.`DESC`, z.OPIS
+				from CRM_LISTA_ZASOBOW z
+				where z.`TYPE` = 'URL_ACTION'
+					and z.A_STATUS != 'DELETED'
+					and z.ALIAS_ID = 0
+			")
+		];
+	}
+
+	public function addActionAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'addActionAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function addActionAjax($args) {
+		$idStorage = V::get('idStorage', 0, $args, 'int');
+		if ($idStorage <= 0) throw new Exception("Missing id storage");
+		$idAction = V::get('idAction', 0, $args, 'int');
+		if ($idAction <= 0) throw new Exception("Missing id action");
+		$storageList = $this->getStorageList();
+		if (empty($storageList)) throw new Exception("No storage defined");
+		if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
+		$tblName = V::get('table', '', $args, 'word');
+		if (empty($tblName)) throw new Exception("No table name");
+
+		$storagePdo = DB::getStorage($idStorage);
+		// $tblStruct = $storagePdo->getTableStruct($tblName);
+		$idTable = $this->fetchTableId($idStorage, $tblName);
+		if ($idTable <= 0) throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
+
+		$action = DB::getPDO()->fetchFirst("
+			select z.ID, z.`DESC`, z.OPIS
+			from CRM_LISTA_ZASOBOW z
+			where z.ID = {$idAction}
+		");
+		if (empty($action)) throw new Exception("Action '{$idAction}' not exists");
+
+		$idInsertedAction = DB::getPDO()->insert('CRM_LISTA_ZASOBOW', [
+			'PARENT_ID' => $idTable,
+			'ALIAS_ID' => $idAction,
+			'TYPE' => 'URL_ACTION',
+			'DESC' => $action['DESC'],
+			'OPIS' => V::get('OPIS', $action['DESC'], $action),
+		]);
+		if (!$idInsertedAction) throw new Exception("Nie udało się dodać akcji");
+		try {
+			DB::getPDO()->insert('CRM_LISTA_ZASOBOW_HIST', [
+				'ID_USERS2' => $idInsertedAction,
+				'PARENT_ID' => $idTable,
+				'ALIAS_ID' => $idAction,
+				'TYPE' => 'URL_ACTION',
+				'DESC' => $action['DESC'],
+				'OPIS' => V::get('OPIS', $action['DESC'], $action),
+			]);
+		} catch (Exception $e) {
+			DBG::log($e);
+		}
+
+		return [
+			'type' => 'success',
+			'msg' => "Dodano akcję - rekord nr {$idInsertedAction}",
+			'__DBG__' => [
+				'$args' => $args,
+				'$idStorage' => $idStorage,
+				'$tblName' => $tblName,
+				// '$tblStruct' => $tblStruct,
+				'$idTable' => $idTable,
+				'$action' => $action,
+			]
+		];
+	}
+
 	public function addBaseProcesAction() {
 		Response::sendTryCatchJson(array($this, 'addBaseProces'), $_REQUEST);
 	}
@@ -1369,7 +1519,7 @@ jQuery(document).on('p5UIBtnAjax:Storage:addBaseProces:ajaxLoaded', function(e,
 				and z.`DESC`='{$tblName}'
 				and z.`A_STATUS` in('NORMAL','WAITING')
 		");
-		if (!empty($rows)) return $rows[0]['ID'];
+		if (!empty($rows)) return (int)$rows[0]['ID'];
 		return null;
 	}
 

+ 122 - 0
SE/se-lib/Route/Storage.php.tableActions.js

@@ -0,0 +1,122 @@
+// @require var ID_STORAGE
+// @require var TABLE_NAME
+// @require var FETCH_URL
+// @require var ADD_ACTION_URL
+
+function Storage__tableStruct__addAction() {
+  fetch(FETCH_URL, {
+    method: 'POST',
+    credentials: 'same-origin',// add cookies
+    headers: { 'Content-Type': 'application/json' },
+    body: JSON.stringify({
+      idStorage: ID_STORAGE,
+      table: TABLE_NAME
+    })
+  }).then(function (response) {
+    if ('application/json' !== response.headers.get('Content-Type').substr(0, 16)) {
+      throw 'Wrong response type: ' + response.headers.get('Content-Type')
+    }
+    return response.json()
+  }).then(function (data) {
+    if (!data) throw 'Empty response';
+    console.log('loadDataAjax:fetch: request finished data:', data);
+    if ('error' === data.type) {
+      p5UI__notifyAjaxCallback(data);
+      console.log('loadDataAjax:fetch: ERR data:', data);
+    } else if ('success' === data.type) {
+      if (!data.options) throw 'Missing options'
+      if (!data.options.length) throw 'Brak akcji do wyboru'
+      Storage__tableStruct__fetchedAddAction(data.options);
+    } else {
+      p5UI__notifyAjaxCallback(data);
+      console.log('loadDataAjax:fetch: ERR data:', data);
+    }
+  }).catch(function (e) {
+    p5UI__notifyAjaxCallback({
+      type: 'error',
+      msg: 'Request error: ' + e
+    });
+    console.log('fetchActionList: ERR:', e);
+  });
+}
+
+function Storage__tableStruct__fetchedAddAction(options) {
+  var optionsList = {};
+  options.forEach(function (option) {
+    optionsList[option.ID] = '[' + option.ID + '] ' + option.DESC
+  })
+  swal({
+    title: 'Dodaj Akcję',
+    input: 'radio',
+    inputOptions: optionsList,
+    showCancelButton: true,
+    showCloseButton: true,
+    inputClass: 'p5-swal-radio-as-list',
+    inputValidator: function (result) {
+      return new Promise(function (resolve, reject) {
+        if (result) {
+          resolve()
+        } else {
+          reject('Wybierz akcję')
+        }
+      })
+    }
+  }).then(function (result) {
+    fetch(ADD_ACTION_URL, {
+      method: 'POST',
+      credentials: 'same-origin',// add cookies
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({
+        idStorage: ID_STORAGE,
+        table: TABLE_NAME,
+        idAction: result
+      })
+    }).then(function (response) {
+      if ('application/json' !== response.headers.get('Content-Type').substr(0, 16)) {
+        throw 'Wrong response type: ' + response.headers.get('Content-Type')
+      }
+      return response.json()
+    }).then(function (data) {
+      if (!data) throw 'Empty response';
+      console.log('ADD_ACTION_URL:fetch: request finished data:', data);
+      if ('error' === data.type) {
+        p5UI__notifyAjaxCallback(data);
+        console.log('ADD_ACTION_URL:fetch: ERR data:', data);
+      } else if ('success' === data.type) {
+        p5UI__notifyAjaxCallback(data);
+      } else {
+        p5UI__notifyAjaxCallback(data);
+        console.log('ADD_ACTION_URL:fetch: ERR data:', data);
+      }
+    }).catch(function (e) {
+      p5UI__notifyAjaxCallback({
+        type: 'error',
+        msg: 'Request error: ' + e
+      });
+      console.log('fetchActionList: ERR:', e);
+    });
+    console.log('TODO: result', result);
+  }).catch(function (e) {
+    if ('close' === e || 'cancel' === e || 'overlay' === e) {
+
+    } else throw e
+  })
+}
+
+function Storage__tableStruct__editActionLabel(n, idAction) {
+  console.log('F.Storage__tableStruct__editActionLabel idAction('+idAction+')', n)
+  swal('TODO', 'Edytuj nazwę akcji', 'warning')
+}
+function Storage__tableStruct__addParamAction(n, idAction, flatDefArgs) {
+  var defArgs = (flatDefArgs || '').split(';').map(function (flatArg) {
+    var arg = flatArg.split('=')
+    return { ID: arg[0], DESC: arg[1]}
+  })
+  console.log('F.Storage__tableStruct__addParamAction idAction('+idAction+')', defArgs, n)
+  swal('TODO', '<div style=\"text-align:left\">Add PARAM_IN:<br> - ' + JSON.stringify(defArgs) + '<br> - or custom param' + '</div>', 'warning')
+}
+
+global.Storage__tableStruct__addAction = Storage__tableStruct__addAction
+global.Storage__tableStruct__fetchedAddAction = Storage__tableStruct__fetchedAddAction
+global.Storage__tableStruct__editActionLabel = Storage__tableStruct__editActionLabel
+global.Storage__tableStruct__addParamAction = Storage__tableStruct__addParamAction