Browse Source

select OD/DO done

Piotr Labudda 4 years ago
parent
commit
4ef0b0315e
1 changed files with 131 additions and 204 deletions
  1. 131 204
      theme/assets/js/createTableSelectedStateObject.js

+ 131 - 204
theme/assets/js/createTableSelectedStateObject.js

@@ -9,65 +9,125 @@ if (!URL_BAZA_NONE) throw "Missing URL_BAZA_NONE";
 
 var BAZA_OD_DO = BAZA_OD_DO || false;
 BAZA_OD_DO = (BAZA_OD_DO === 'OD' || BAZA_OD_DO === 'DO') ? BAZA_OD_DO : '';
-// - `Bocian.biAuditForm.odFeatureKeys`: `["CEIDG.879134","KRS/p.4398202"]`
-// - `Bocian.biAuditForm.doFeatureKeys`: `["KRS.1533062","KRS/p.4616336"]`
-var LOCAL_STORAGE_KEY = (BAZA_OD_DO) ? 'Bocian.biAuditForm.' + BAZA_OD_DO.toLowerCase() + 'FeatureKeys' : null;
-DBG1 && console.log('DBG:', { BAZA_OD_DO, LOCAL_STORAGE_KEY, KEY_PREFIX })
+
+
+{ // make fixed panel to select checkbox context OD, DO or default
+	function _px(px) { return (!px) ? '0px' : '' + px + 'px'; }
+
+	var panelNode = document.createElement('div')
+	var panelWidth = 600;
+	panelNode.style.position = 'fixed';
+	panelNode.style.top = _px(0);
+	panelNode.style.width = _px(panelWidth);
+	panelNode.style.left = _px(window.innerWidth > panelWidth ? Math.floor(window.innerWidth / 2 - panelWidth / 2) : 0);
+	panelNode.style.padding = '8px 15px'
+	panelNode.style.textAlign = 'center'
+	panelNode.className = 'alert alert-info'
+	panelNode.style.boxShadow = '6px 6px 20px 0px #31708f'
+	// panelNode.style.border = '1px solid red'
+	// panelNode.style.padding = '6px'
+	// panelNode.style.backgroundColor = 'lightRed'
+	// panelNode.style.color = 'black'
+
+	panelNode.innerHTML = 'Wybierz elementy do raportu: ' +
+		'<div class="tblAjax__footer__toolbar__pagination" style="display:inline-block">' +
+			'<a class="btn btn-xs btn-default' + (BAZA_OD_DO === 'OD' ? ' active' : '') + '" href="' + URL_BAZA_OD + '">' + 'OD' + '</a>' +
+			' ' +
+			'<i class="glyphicon glyphicon-random" style="vertical-align:middle"></i>' +
+			' ' +
+			'<a class="btn btn-xs btn-default' + (BAZA_OD_DO === 'DO' ? ' active' : '') + '" href="' + URL_BAZA_DO + '">' + 'DO' + '</a>' +
+			' ' +
+			(!BAZA_OD_DO ? '' : '<a class="btn btn-xs btn-default" href="' + URL_BAZA_NONE + '">' + 'Anuluj' + '</a>') +
+		'</div>' +
+	'';
+	
+	document.body.appendChild(panelNode)
+}
+
+if (!BAZA_OD_DO) return;
 
 if (!global.p5VendorJs) throw "Missing p5 Vendor js libs";
 if (!global.p5VendorJs.Redux) throw "Missing p5 Vendor js lib: Redux";
-if (!global.swal) throw "Missing swal";
 if (!localStorage) throw "Missing localStorage!";
-var swal = global.swal;
 var Redux = global.p5VendorJs.Redux;
 var ReduxThunk = global.p5VendorJs.ReduxThunk;
 var createStoreWithThunkMiddleware = Redux.applyMiddleware(ReduxThunk)(Redux.createStore); // TODO: to vendor.js
 
-{ // from `tools/Bocian.php.addItemToRaport.js`
-	function getSelectedListLocalStorageKey(from) { // from: ( OD | DO )
-		switch (from) {
-			case 'OD': return 'Bocian.biAuditForm.odFeatureKeys';
-			case 'DO': return 'Bocian.biAuditForm.doFeatureKeys';
-			default: throw "Not implemented from selected list '" + from + "' - expected 'OD' or 'DO'";
+{
+	// - `Bocian.biAuditForm.odFeatureKeys`: `["CEIDG.879134","KRS/p.4398202"]`
+	// - `Bocian.biAuditForm.doFeatureKeys`: `["KRS.1533062","KRS/p.4616336"]`
+	var bazaSelected = (function (from, prefix) { // from: OD | DO, prefix: KRS | KRS/p | MSIG | MSIG/p | CEIDG
+		function _getSelectedListLocalStorageKey(from) {
+			switch (from) {
+				case 'OD': return 'Bocian.biAuditForm.odFeatureKeys';
+				case 'DO': return 'Bocian.biAuditForm.doFeatureKeys';
+				default: throw "Not implemented from selected list '" + from + "' - expected 'OD' or 'DO'";
+			}
 		}
-	}
-	function getSelectedListFromLocalStorage(from) {
-		var key = getSelectedListLocalStorageKey(from);
-		return JSON.parse( localStorage.getItem(key) || '[]' );
-	}
-	function saveToSelectedListInLocalStorage(from, featureKey) {
-		DBG && console.log("DBG::saveToSelectedListInLocalStorage(from, featureKey)", {from, featureKey}, {added: getSelectedListFromLocalStorage(from).concat(featureKey)});
-		var key = getSelectedListLocalStorageKey(from);
-		var newValue = getSelectedListFromLocalStorage(from).concat(featureKey)
-		newValue = Array.from(new Set(newValue))
-		localStorage.setItem(key, JSON.stringify(newValue))
-	}
-	function saveSelectedListInLocalStorage(from, listFeatureKey) {
-		DBG && console.log("DBG::saveSelectedListInLocalStorage(from, listFeatureKey)", {from, listFeatureKey}, {added: getSelectedListFromLocalStorage(from).concat(listFeatureKey)});
-		var key = getSelectedListLocalStorageKey(from);
-		// var newValue = getSelectedListFromLocalStorage(from).concat(listFeatureKey)
-		var newValue = listFeatureKey
-		localStorage.setItem(key, JSON.stringify(newValue))
-	}
-	function removeFromSelectedListInLocalStorage(from, featureKey) {
-		DBG && console.log("DBG::removeFromSelectedListInLocalStorage(from, featureKey)", {from, featureKey});
-		localStorage.setItem(getSelectedListLocalStorageKey(from), JSON.stringify(
-			getSelectedListFromLocalStorage(from).filter(function (item) {
-				return ( item !== featureKey );
+
+		var _dbKey = _getSelectedListLocalStorageKey(from)
+
+		function _fetchAll() {
+			return JSON.parse( localStorage.getItem(_dbKey) || '[]' );
+		}
+		function _fetchList() {
+			return _fetchAll().filter(function (key) {
+				return (key.substr(0, prefix.length + 1) === prefix + '.');
 			})
-		))
-	}
-}
-function getCurrentBazaSelectedList(listPrimaryKeys, selected, prefix) {
-	// selected: (3) ["KRS/p.5872624", "KRS/p.4616336", "KRS.1533062"]
-	return listPrimaryKeys.filter(function (pk) {
-		return -1 !== selected.indexOf(prefix + '.' + pk);
-	})
+		}
+		function _toKey(pk) { return prefix + '.' + pk; }
+		function _isBaza(key) { return (key.substr(0, prefix.length + 1) === prefix + '.'); }
+		function _isNotBaza(key) { return !_isBaza(key); }
+		// function _toPk(key) { return key.substr(prefix.length + 1); }
+
+		return {
+			getTotal: function () { return _fetchList().length; },
+			add: function (pk) {
+				var all = new Set(_fetchAll())
+				all.add(_toKey(pk))
+				var newValue = Array.from(all)
+				localStorage.setItem(_dbKey, JSON.stringify(newValue))
+			},
+			delete: function (pk) {
+				var all = new Set(_fetchAll())
+				all.delete(_toKey(pk))
+				var newValue = Array.from(all)
+				localStorage.setItem(_dbKey, JSON.stringify(newValue))
+			},
+			addList: function (pks) {
+				var all = new Set(_fetchAll())
+				pks.forEach(function (pk) {
+					all.add(_toKey(pk))
+				})
+				var newValue = Array.from(all)
+				localStorage.setItem(_dbKey, JSON.stringify(newValue))
+			},
+			deleteList: function (pks) {
+				var all = new Set(_fetchAll())
+				pks.forEach(function (pk) {
+					all.delete(_toKey(pk))
+				})
+				var newValue = Array.from(all)
+				localStorage.setItem(_dbKey, JSON.stringify(newValue))
+			},
+			deleteAll: function () {
+				var newValue = _fetchAll().filter(_isNotBaza)
+				localStorage.setItem(_dbKey, JSON.stringify(newValue))
+			},
+			getOnlySelectedPks: function (listPrimaryKeys) {
+				var all = new Set(_fetchAll())
+
+				return listPrimaryKeys.filter(function (pk) {
+					return all.has(_toKey(pk))
+				})
+			},
+		}
+	})(BAZA_OD_DO, KEY_PREFIX);
 }
 
 function selectedStore(state, action) {
 	var prevState = state || { isLoading: false, selected: [], loading: [], listPrimaryKeys: [], totalSelected: 0 };
-	DBG1 && console.log('DBG::selectedStore', { prevState, action });
+	DBG && console.log('DBG::selectedStore', { prevState, action });
 	switch (action.type) {
 		case 'SET_CHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
 			loading: p5Utils__arrayRemove(prevState.loading, action.primaryKey),
@@ -116,7 +176,6 @@ function fixSelectAllInSelectedState(state) {
 			break;
 		}
 	}
-	// DBG1 && console.log('fixSelectAllInSelectedState', { isAllSelected, state });
 	var isSelectedSelectAll = ( -1 !== state.selected.indexOf('select-all') );
 	if (isAllSelected && !isSelectedSelectAll) return Object.assign(state, {
 		selected: ['select-all'].concat(state.selected)
@@ -132,40 +191,6 @@ function p5Utils__arrayRemove(array, toRemoveItem) {
 	});
 }
 
-var p5WPSUtils__createConvertToWpsDataInputFunction = function (identifier) {
-	return function (value) {
-		if (!value) return null; // WPS function require value, but for eg. featureQuery mey be empty
-		return { // "wps:Input"
-			identifier: identifier, // "ows:Identifier"
-			// title: "...", // "ows:Title"
-			data: { literalData: { value: value } }, // "wps:Data"
-			// reference: "???", // "wps:Reference"
-			// boundingBoxData: "???", // "wps:BoundingBoxData"
-		};
-	}
-};
-var p5WPSHelper_generateProcessSelectFeatureWithArgs = function (identifier, args) {
-	var dataInputs = Object.keys(args).reduce(function (ret, argName) {
-		var value = args[argName];
-		var convertValueToWpsDataInput = p5WPSUtils__createConvertToWpsDataInputFunction(argName);
-		return (p5Utils__isArray(value))
-			? ret.concat( value.map( convertValueToWpsDataInput ) )
-			: ret.concat([ convertValueToWpsDataInput(value) ])
-		;
-	}, []).filter(function (wpsTag) {
-		return !! wpsTag;
-	})
-	return {
-		identifier: identifier, // "ows:Identifier"
-		dataInputs: dataInputs,
-		responseForm: { // "wps:ResponseForm"
-			// rawDataOutput: "???", // "wps:RawDataOutput"
-			// responseDocument: "???", // "wps:ResponseDocument"
-		}
-	}
-}
-
-
 function selectedActions(idContext) {
 	var idContext = idContext || null;
 	function setChecked(primaryKey, totalSelected) {
@@ -190,44 +215,38 @@ function selectedActions(idContext) {
 		return { type: 'SET_ERROR_MSG', errorMsg: errorMsg }
 	}
 	function toggle(namespace, primaryKey, checked) {
-		DBG1 && console.log('DBG::toggle action: (pks:['+primaryKey+'])...');
+		DBG && console.log('DBG::toggle action: (pks:['+primaryKey+'])...');
 		if ('select-all' === primaryKey) return toggleAll(namespace, checked);
 
 		return function(dispatch, getState) {
 			dispatch(setLoading(primaryKey));
 
 			return new Promise(function (resolve, reject) {
-				DBG1 && console.log('DBG::toggle action: (pks:['+primaryKey+'])...');
+				DBG && console.log('DBG::toggle action: (pks:['+primaryKey+'])...');
 
 				if (checked) {
-					saveToSelectedListInLocalStorage(BAZA_OD_DO, KEY_PREFIX + '.' + primaryKey)
+					bazaSelected.add(primaryKey)
+					dispatch( setChecked(primaryKey, bazaSelected.getTotal()) );
 				} else {
-					removeFromSelectedListInLocalStorage(BAZA_OD_DO, KEY_PREFIX + '.' + primaryKey)
+					bazaSelected.delete(primaryKey)
+					dispatch( setUnchecked(primaryKey, bazaSelected.getTotal()) );
 				}
-
-				var selected = getSelectedListFromLocalStorage(BAZA_OD_DO)
-				DBG1 && console.log('DBG:setPrimaryKeys TODO read localStorage and setListChecked:', { selected, BAZA_OD_DO, LOCAL_STORAGE_KEY, KEY_PREFIX })
-
-				dispatch( checked ? setChecked(primaryKey, selected.length) : setUnchecked(primaryKey, selected.length) );
 			});
 		}
 	}
 	function setPrimaryKeys(namespace, listPrimaryKeys) { // TODO: should set list primaryKeys, change checkboxes to loading and fetch its state, then update gui
-		DBG1 && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+'])...');
+		DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+'])...');
 		return function(dispatch, getState) {
 			dispatch({ type: 'SET_PRIMARY_KEYS', listPrimaryKeys: listPrimaryKeys });
 			// dispatch( setListLoading(listPrimaryKeys) );
 			if (!listPrimaryKeys.length) return;
 
 			return new Promise(function (resolve, reject) {
-				DBG1 && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+'])...');
+				DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+'])...');
 
-				var selected = getSelectedListFromLocalStorage(BAZA_OD_DO)
-				// selected: (3) ["KRS/p.5872624", "KRS/p.4616336", "KRS.1533062"]
-				var curSelectedPK = getCurrentBazaSelectedList(listPrimaryKeys, selected, KEY_PREFIX)
-				DBG1 && console.log('DBG:setPrimaryKeys TODO read localStorage and setListChecked:', { selected, curSelectedPK, BAZA_OD_DO, LOCAL_STORAGE_KEY, KEY_PREFIX })
+				var curSelectedPK = bazaSelected.getOnlySelectedPks(listPrimaryKeys)
 
-				dispatch( setListChecked(curSelectedPK, selected.length) );
+				dispatch( setListChecked(curSelectedPK, bazaSelected.getTotal()) );
 			});
 		}
 	}
@@ -239,79 +258,50 @@ function selectedActions(idContext) {
 			var listPrimaryKeys = state.listPrimaryKeys;
 
 			return new Promise(function (resolve, reject) {
-				DBG1 && console.log('DBG::toggleAll action: (pks:['+listPrimaryKeys.join(',')+'])...');
+				DBG && console.log('DBG::toggleAll action: (pks:['+listPrimaryKeys.join(',')+'])...');
 
-				var selected = getSelectedListFromLocalStorage(BAZA_OD_DO)
-				// selected: (3) ["KRS/p.5872624", "KRS/p.4616336", "KRS.1533062"]
-				var toAdd = listPrimaryKeys.map(function (pk) {
-					return KEY_PREFIX + '.' + pk;
-				}).filter(function (key) {
-					return (-1 === selected.indexOf(key));
-				})
-				DBG1 && console.log('DBG:setPrimaryKeys TODO read localStorage and setListChecked:', { selected, toAdd, BAZA_OD_DO, LOCAL_STORAGE_KEY, KEY_PREFIX })
-				var newSelected = new Set(selected)
-				listPrimaryKeys.map(function (pk) { return KEY_PREFIX + '.' + pk; }).forEach(function (key) {
-					(checked) ? newSelected.add(key) : newSelected.delete(key)
-				})
-				saveSelectedListInLocalStorage(BAZA_OD_DO, Array.from(newSelected))
-
-				selected = getSelectedListFromLocalStorage(BAZA_OD_DO)
-
-				dispatch( checked ? setListChecked(listPrimaryKeys, selected.length) : setListUnchecked(listPrimaryKeys, selected.length) );
+				if (checked) {
+					bazaSelected.addList(listPrimaryKeys)
+					dispatch( setListChecked(listPrimaryKeys, bazaSelected.getTotal()) );
+				} else {
+					bazaSelected.deleteList(listPrimaryKeys)
+					dispatch( setListUnchecked(listPrimaryKeys, bazaSelected.getTotal()) );
+				}
 			});
 		}
 	}
 	function unselectAll(namespace) {
-		// dispatch(setLoading());
 		return function(dispatch, getState) {
-			// var reqArgs = { typeName: namespace };
-			// if (idContext) reqArgs.idContext = idContext;
-			// var reqPromise = p5WPS__unselecAllFeatures(reqArgs);
-			// return reqPromise.then(function (response) {
-			// 	DBG1 && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) dispatch success');
-			// 	// dispatch( setListChecked(response.selected, response.totalSelected) );
-			// 	dispatch( setListChecked([], 0) );
-			// }).catch(function (e) {
-			// 	p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA4: ' + e});
-			// 	DBG1 && console.warn('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) ERROR dispatch error');
-			// 	// var fullListPks = ['select-all'].concat(listPrimaryKeys)
-			// 	// dispatch( checked ? setListUnchecked(fullListPks) : setListChecked(fullListPks) );
-			// 	// dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
-			// 	// dispatch( setListLoading([]) );
-			// });
 			return new Promise(function (resolve, reject) {
-				DBG1 && console.log('DBG::unselectAll action: (pks:['+listPrimaryKeys.join(',')+'])...');
-				{
-					reject('TODO: unselectAll');
-					return;
-				}
+				DBG && console.log('DBG::unselectAll action ...');
 
-				// resolve();
+				bazaSelected.deleteAll()
+				dispatch( setListChecked([], 0) );
 			});
 		};
 	}
 	function selectAllMatchingFilter(namespace, filterQuery) {
-		DBG1 && console.log('DBG::selectAllMatchingFilter', { filterQuery });
+		DBG && console.log('DBG::selectAllMatchingFilter', { filterQuery });
 		return function(dispatch, getState) {
-			DBG1 && console.log('DBG::selectAllMatchingFilter state', state);
+			DBG && console.log('DBG::selectAllMatchingFilter state', state);
 			var state = getState();
 			var listPrimaryKeys = state.listPrimaryKeys;
 
 			// var reqArgs = { typeName: namespace, primaryKey: listPrimaryKeys, filterQuery: filterQuery };
 			// if (idContext) reqArgs.idContext = idContext;
 			// return p5WPS__selectAllFeaturesMatchingFilter(reqArgs).then(function (listSelected) {
-			// 	DBG1 && console.log('DBG::selectAllMatchingFilter dispatch success');
+			// 	DBG && console.log('DBG::selectAllMatchingFilter dispatch success');
 			// 	dispatch( setListChecked(listSelected.selected, listSelected.totalSelected) );
 			// }).catch(function (e) {
 			// 	p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA5: ' + e});
-			// 	DBG1 && console.warn('DBG::selectAllMatchingFilter ERROR dispatch error');
+			// 	DBG && console.warn('DBG::selectAllMatchingFilter ERROR dispatch error');
 			// 	// var fullListPks = ['select-all'].concat(listPrimaryKeys);
 			// 	// dispatch( setListUnchecked(fullListPks) );
 			// 	// dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
 			// 	dispatch( setListLoading([]) );
 			// });
 			return new Promise(function (resolve, reject) {
-				DBG1 && console.log('DBG::selectAllMatchingFilter action: (pks:['+listPrimaryKeys.join(',')+'])...');
+				DBG && console.log('DBG::selectAllMatchingFilter action: (pks:['+listPrimaryKeys.join(',')+'])...');
 				{
 					reject('TODO: selectAllMatchingFilter');
 					return;
@@ -339,70 +329,7 @@ function bocian_createTableSelectedStateObject(idContext) {
 	}
 }
 
-// TOOD: select OD/DO or default
-// swal({
-// 	title: 'Are you sure?',
-// 	text: "You won't be able to revert this!",
-// 	type: 'warning',
-// 	showCancelButton: true,
-// 	confirmButtonText: 'Yes, delete it!',
-// 	cancelButtonText: 'No, cancel!',
-// 	reverseButtons: true,
-// 	confirmButtonClass: 'btn btn-success',
-// 	cancelButtonClass: 'btn btn-danger',
-// 	buttonsStyling: false,
-// }).then((result) => {
-// 	if (result.value) {
-// 		DBG1 && console.log('DBG::setPrimaryKeys swal(value:'+result.value+') action: (pks:['+listPrimaryKeys.join(',')+'])');
-// 		// swalWithBootstrapButtons(
-// 		// 	'Deleted!',
-// 		// 	'Your file has been deleted.',
-// 		// 	'success'
-// 		// )
-// 	} else if (result.dismiss === swal.DismissReason.cancel) {
-// 		DBG1 && console.log('DBG::setPrimaryKeys swal(cancel) action: (pks:['+listPrimaryKeys.join(',')+'])');
-// 		// swalWithBootstrapButtons(
-// 		// 	'Cancelled',
-// 		// 	'Your imaginary file is safe :)',
-// 		// 	'error'
-// 		// )
-// 	} else {
-// 		DBG1 && console.log('DBG::setPrimaryKeys swal(else?) action: (pks:['+listPrimaryKeys.join(',')+'])');
-// 	}
-// })
-
-function _px(px) { return (!px) ? '0px' : '' + px + 'px'; }
-
 // var original_global__createTableSelectedStateObject = global.createTableSelectedStateObject; // to revert back to original
-{ // make fixed panel to select checkbox context OD, DO or default
-	var panelNode = document.createElement('div')
-	var panelWidth = 600;
-	panelNode.style.position = 'fixed';
-	panelNode.style.top = _px(0);
-	panelNode.style.width = _px(panelWidth);
-	panelNode.style.left = _px(window.innerWidth > panelWidth ? Math.floor(window.innerWidth / 2 - panelWidth / 2) : 0);
-	panelNode.style.padding = '8px 15px'
-	panelNode.style.textAlign = 'center'
-	panelNode.className = 'alert alert-info'
-	panelNode.style.boxShadow = '6px 6px 20px 0px #31708f'
-	// panelNode.style.border = '1px solid red'
-	// panelNode.style.padding = '6px'
-	// panelNode.style.backgroundColor = 'lightRed'
-	// panelNode.style.color = 'black'
-
-	panelNode.innerHTML = 'Wybierz elementy do raportu: ' +
-		'<div class="tblAjax__footer__toolbar__pagination" style="display:inline-block">' +
-			'<a class="btn btn-xs btn-default' + (BAZA_OD_DO === 'OD' ? ' active' : '') + '" href="' + URL_BAZA_OD + '">' + 'OD' + '</a>' +
-			' ' +
-			'<a class="btn btn-xs btn-default' + (BAZA_OD_DO === 'DO' ? ' active' : '') + '" href="' + URL_BAZA_DO + '">' + 'DO' + '</a>' +
-			' ' +
-			(!BAZA_OD_DO ? '' : '<a class="btn btn-xs btn-default" href="' + URL_BAZA_NONE + '">' + 'Anuluj' + '</a>') +
-		'</div>' +
-	'';
-	
-	document.body.appendChild(panelNode)
-}
-
 if (BAZA_OD_DO) {
 	global.createTableSelectedStateObject = bocian_createTableSelectedStateObject;
 }