createTableSelectedStateObject.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. var DBG = DBG || false;
  2. var DBG1 = true;
  3. // if (!URI_WPS) throw "Missing URI_WPS";
  4. if (!KEY_PREFIX) return; // KEY_PREFIX = KRS | KRS/p | MSIG | MSIG/p | CEIDG
  5. if (!URL_BAZA_OD) throw "Missing URL_BAZA_OD";
  6. if (!URL_BAZA_DO) throw "Missing URL_BAZA_DO";
  7. if (!URL_BAZA_NONE) throw "Missing URL_BAZA_NONE";
  8. var BAZA_OD_DO = BAZA_OD_DO || false;
  9. BAZA_OD_DO = (BAZA_OD_DO === 'OD' || BAZA_OD_DO === 'DO') ? BAZA_OD_DO : '';
  10. // - `Bocian.biAuditForm.odFeatureKeys`: `["CEIDG.879134","KRS/p.4398202"]`
  11. // - `Bocian.biAuditForm.doFeatureKeys`: `["KRS.1533062","KRS/p.4616336"]`
  12. var LOCAL_STORAGE_KEY = (BAZA_OD_DO) ? 'Bocian.biAuditForm.' + BAZA_OD_DO.toLowerCase() + 'FeatureKeys' : null;
  13. DBG1 && console.log('DBG:', { BAZA_OD_DO, LOCAL_STORAGE_KEY, KEY_PREFIX })
  14. if (!global.p5VendorJs) throw "Missing p5 Vendor js libs";
  15. if (!global.p5VendorJs.Redux) throw "Missing p5 Vendor js lib: Redux";
  16. if (!global.swal) throw "Missing swal";
  17. if (!localStorage) throw "Missing localStorage!";
  18. var swal = global.swal;
  19. var Redux = global.p5VendorJs.Redux;
  20. var ReduxThunk = global.p5VendorJs.ReduxThunk;
  21. var createStoreWithThunkMiddleware = Redux.applyMiddleware(ReduxThunk)(Redux.createStore); // TODO: to vendor.js
  22. { // from `tools/Bocian.php.addItemToRaport.js`
  23. function getSelectedListLocalStorageKey(from) { // from: ( OD | DO )
  24. switch (from) {
  25. case 'OD': return 'Bocian.biAuditForm.odFeatureKeys';
  26. case 'DO': return 'Bocian.biAuditForm.doFeatureKeys';
  27. default: throw "Not implemented from selected list '" + from + "' - expected 'OD' or 'DO'";
  28. }
  29. }
  30. function getSelectedListFromLocalStorage(from) {
  31. var key = getSelectedListLocalStorageKey(from);
  32. return JSON.parse( localStorage.getItem(key) || '[]' );
  33. }
  34. function saveToSelectedListInLocalStorage(from, featureKey) {
  35. DBG && console.log("DBG::saveToSelectedListInLocalStorage(from, featureKey)", {from, featureKey}, {added: getSelectedListFromLocalStorage(from).concat(featureKey)});
  36. var key = getSelectedListLocalStorageKey(from);
  37. var newValue = getSelectedListFromLocalStorage(from).concat(featureKey)
  38. newValue = Array.from(new Set(newValue))
  39. localStorage.setItem(key, JSON.stringify(newValue))
  40. }
  41. function saveSelectedListInLocalStorage(from, listFeatureKey) {
  42. DBG && console.log("DBG::saveSelectedListInLocalStorage(from, listFeatureKey)", {from, listFeatureKey}, {added: getSelectedListFromLocalStorage(from).concat(listFeatureKey)});
  43. var key = getSelectedListLocalStorageKey(from);
  44. // var newValue = getSelectedListFromLocalStorage(from).concat(listFeatureKey)
  45. var newValue = listFeatureKey
  46. localStorage.setItem(key, JSON.stringify(newValue))
  47. }
  48. function removeFromSelectedListInLocalStorage(from, featureKey) {
  49. DBG && console.log("DBG::removeFromSelectedListInLocalStorage(from, featureKey)", {from, featureKey});
  50. localStorage.setItem(getSelectedListLocalStorageKey(from), JSON.stringify(
  51. getSelectedListFromLocalStorage(from).filter(function (item) {
  52. return ( item !== featureKey );
  53. })
  54. ))
  55. }
  56. }
  57. function getCurrentBazaSelectedList(listPrimaryKeys, selected, prefix) {
  58. // selected: (3) ["KRS/p.5872624", "KRS/p.4616336", "KRS.1533062"]
  59. return listPrimaryKeys.filter(function (pk) {
  60. return -1 !== selected.indexOf(prefix + '.' + pk);
  61. })
  62. }
  63. function selectedStore(state, action) {
  64. var prevState = state || { isLoading: false, selected: [], loading: [], listPrimaryKeys: [], totalSelected: 0 };
  65. DBG1 && console.log('DBG::selectedStore', { prevState, action });
  66. switch (action.type) {
  67. case 'SET_CHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  68. loading: p5Utils__arrayRemove(prevState.loading, action.primaryKey),
  69. selected: prevState.selected.concat(action.primaryKey),
  70. totalSelected: action.totalSelected,
  71. }));
  72. case 'SET_UNCHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  73. loading: p5Utils__arrayRemove(prevState.loading, action.primaryKey),
  74. selected: p5Utils__arrayRemove(prevState.selected, action.primaryKey),
  75. totalSelected: action.totalSelected,
  76. }));
  77. case 'SET_LIST_CHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  78. loading: [], // TODO: p5Utils__arrayExcept(prevState.loading, action.listPrimaryKeys),
  79. selected: [].concat(action.listPrimaryKeys), // TODO: p5Utils__arrayUniqueUnion(prevState.selected, action.listPrimaryKeys)
  80. totalSelected: action.totalSelected,
  81. }));
  82. case 'SET_LIST_UNCHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  83. loading: [], // TODO: p5Utils__arrayExcept(prevState.loading, action.listPrimaryKeys),
  84. selected: [], // TODO: p5Utils__arrayUniqueUnion(prevState.selected, action.listPrimaryKeys)
  85. totalSelected: action.totalSelected,
  86. }));
  87. case 'SET_LOADING': return Object.assign(prevState, {
  88. loading: prevState.loading.concat(action.primaryKey)
  89. });
  90. case 'SET_LIST_LOADING': return Object.assign(prevState, {
  91. loading: [].concat(action.listPrimaryKeys)
  92. });
  93. case 'SET_PRIMARY_KEYS': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  94. listPrimaryKeys: [].concat(action.listPrimaryKeys),
  95. loading: [].concat(action.listPrimaryKeys)
  96. }));
  97. // case 'SET_ERROR_MSG': return Object.assign(prevState, {
  98. // errorMsg: action.errorMsg
  99. // });
  100. default: return prevState;
  101. }
  102. }
  103. function fixSelectAllInSelectedState(state) {
  104. var len = state.listPrimaryKeys.length;
  105. var selLen = state.selected.length;
  106. var isAllSelected = ( len > 0 && selLen >= len ); // selected array may contain 'select-all'
  107. for (var i = 0, pk = ''; i < len; i++) {
  108. pk = state.listPrimaryKeys[i];
  109. if (-1 === state.selected.indexOf(pk)) {
  110. isAllSelected = false;
  111. break;
  112. }
  113. }
  114. // DBG1 && console.log('fixSelectAllInSelectedState', { isAllSelected, state });
  115. var isSelectedSelectAll = ( -1 !== state.selected.indexOf('select-all') );
  116. if (isAllSelected && !isSelectedSelectAll) return Object.assign(state, {
  117. selected: ['select-all'].concat(state.selected)
  118. });
  119. if (!isAllSelected && isSelectedSelectAll) return Object.assign(state, {
  120. selected: p5Utils__arrayRemove(state.selected, 'select-all'),
  121. });
  122. return state;
  123. }
  124. function p5Utils__arrayRemove(array, toRemoveItem) {
  125. return array.filter(function (item) {
  126. return ( item !== toRemoveItem );
  127. });
  128. }
  129. var p5WPSUtils__createConvertToWpsDataInputFunction = function (identifier) {
  130. return function (value) {
  131. if (!value) return null; // WPS function require value, but for eg. featureQuery mey be empty
  132. return { // "wps:Input"
  133. identifier: identifier, // "ows:Identifier"
  134. // title: "...", // "ows:Title"
  135. data: { literalData: { value: value } }, // "wps:Data"
  136. // reference: "???", // "wps:Reference"
  137. // boundingBoxData: "???", // "wps:BoundingBoxData"
  138. };
  139. }
  140. };
  141. var p5WPSHelper_generateProcessSelectFeatureWithArgs = function (identifier, args) {
  142. var dataInputs = Object.keys(args).reduce(function (ret, argName) {
  143. var value = args[argName];
  144. var convertValueToWpsDataInput = p5WPSUtils__createConvertToWpsDataInputFunction(argName);
  145. return (p5Utils__isArray(value))
  146. ? ret.concat( value.map( convertValueToWpsDataInput ) )
  147. : ret.concat([ convertValueToWpsDataInput(value) ])
  148. ;
  149. }, []).filter(function (wpsTag) {
  150. return !! wpsTag;
  151. })
  152. return {
  153. identifier: identifier, // "ows:Identifier"
  154. dataInputs: dataInputs,
  155. responseForm: { // "wps:ResponseForm"
  156. // rawDataOutput: "???", // "wps:RawDataOutput"
  157. // responseDocument: "???", // "wps:ResponseDocument"
  158. }
  159. }
  160. }
  161. function selectedActions(idContext) {
  162. var idContext = idContext || null;
  163. function setChecked(primaryKey, totalSelected) {
  164. return { type: 'SET_CHECKED', primaryKey: primaryKey, totalSelected: totalSelected }
  165. }
  166. function setUnchecked(primaryKey, totalSelected) {
  167. return { type: 'SET_UNCHECKED', primaryKey: primaryKey, totalSelected: totalSelected }
  168. }
  169. function setLoading(primaryKey) {
  170. return { type: 'SET_LOADING', primaryKey: primaryKey }
  171. }
  172. function setListChecked(listPrimaryKeys, totalSelected) {
  173. return { type: 'SET_LIST_CHECKED', listPrimaryKeys: listPrimaryKeys, totalSelected: totalSelected }
  174. }
  175. function setListUnchecked(listPrimaryKeys, totalSelected) {
  176. return { type: 'SET_LIST_UNCHECKED', listPrimaryKeys: listPrimaryKeys, totalSelected: totalSelected }
  177. }
  178. function setListLoading(listPrimaryKeys) {
  179. return { type: 'SET_LIST_LOADING', listPrimaryKeys: listPrimaryKeys }
  180. }
  181. function setErrorMsg(errorMsg) {
  182. return { type: 'SET_ERROR_MSG', errorMsg: errorMsg }
  183. }
  184. function toggle(namespace, primaryKey, checked) {
  185. DBG1 && console.log('DBG::toggle action: (pks:['+primaryKey+'])...');
  186. if ('select-all' === primaryKey) return toggleAll(namespace, checked);
  187. return function(dispatch, getState) {
  188. dispatch(setLoading(primaryKey));
  189. return new Promise(function (resolve, reject) {
  190. DBG1 && console.log('DBG::toggle action: (pks:['+primaryKey+'])...');
  191. if (checked) {
  192. saveToSelectedListInLocalStorage(BAZA_OD_DO, KEY_PREFIX + '.' + primaryKey)
  193. } else {
  194. removeFromSelectedListInLocalStorage(BAZA_OD_DO, KEY_PREFIX + '.' + primaryKey)
  195. }
  196. var selected = getSelectedListFromLocalStorage(BAZA_OD_DO)
  197. DBG1 && console.log('DBG:setPrimaryKeys TODO read localStorage and setListChecked:', { selected, BAZA_OD_DO, LOCAL_STORAGE_KEY, KEY_PREFIX })
  198. dispatch( checked ? setChecked(primaryKey, selected.length) : setUnchecked(primaryKey, selected.length) );
  199. });
  200. }
  201. }
  202. function setPrimaryKeys(namespace, listPrimaryKeys) { // TODO: should set list primaryKeys, change checkboxes to loading and fetch its state, then update gui
  203. DBG1 && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+'])...');
  204. return function(dispatch, getState) {
  205. dispatch({ type: 'SET_PRIMARY_KEYS', listPrimaryKeys: listPrimaryKeys });
  206. // dispatch( setListLoading(listPrimaryKeys) );
  207. if (!listPrimaryKeys.length) return;
  208. return new Promise(function (resolve, reject) {
  209. DBG1 && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+'])...');
  210. var selected = getSelectedListFromLocalStorage(BAZA_OD_DO)
  211. // selected: (3) ["KRS/p.5872624", "KRS/p.4616336", "KRS.1533062"]
  212. var curSelectedPK = getCurrentBazaSelectedList(listPrimaryKeys, selected, KEY_PREFIX)
  213. DBG1 && console.log('DBG:setPrimaryKeys TODO read localStorage and setListChecked:', { selected, curSelectedPK, BAZA_OD_DO, LOCAL_STORAGE_KEY, KEY_PREFIX })
  214. dispatch( setListChecked(curSelectedPK, selected.length) );
  215. });
  216. }
  217. }
  218. function toggleAll(namespace, checked) {
  219. var primaryKey = 'select-all';
  220. return function(dispatch, getState) {
  221. dispatch(setLoading(primaryKey));
  222. var state = getState();
  223. var listPrimaryKeys = state.listPrimaryKeys;
  224. return new Promise(function (resolve, reject) {
  225. DBG1 && console.log('DBG::toggleAll action: (pks:['+listPrimaryKeys.join(',')+'])...');
  226. var selected = getSelectedListFromLocalStorage(BAZA_OD_DO)
  227. // selected: (3) ["KRS/p.5872624", "KRS/p.4616336", "KRS.1533062"]
  228. var toAdd = listPrimaryKeys.map(function (pk) {
  229. return KEY_PREFIX + '.' + pk;
  230. }).filter(function (key) {
  231. return (-1 === selected.indexOf(key));
  232. })
  233. DBG1 && console.log('DBG:setPrimaryKeys TODO read localStorage and setListChecked:', { selected, toAdd, BAZA_OD_DO, LOCAL_STORAGE_KEY, KEY_PREFIX })
  234. var newSelected = new Set(selected)
  235. listPrimaryKeys.map(function (pk) { return KEY_PREFIX + '.' + pk; }).forEach(function (key) {
  236. (checked) ? newSelected.add(key) : newSelected.delete(key)
  237. })
  238. saveSelectedListInLocalStorage(BAZA_OD_DO, Array.from(newSelected))
  239. selected = getSelectedListFromLocalStorage(BAZA_OD_DO)
  240. dispatch( checked ? setListChecked(listPrimaryKeys, selected.length) : setListUnchecked(listPrimaryKeys, selected.length) );
  241. });
  242. }
  243. }
  244. function unselectAll(namespace) {
  245. // dispatch(setLoading());
  246. return function(dispatch, getState) {
  247. // var reqArgs = { typeName: namespace };
  248. // if (idContext) reqArgs.idContext = idContext;
  249. // var reqPromise = p5WPS__unselecAllFeatures(reqArgs);
  250. // return reqPromise.then(function (response) {
  251. // DBG1 && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) dispatch success');
  252. // // dispatch( setListChecked(response.selected, response.totalSelected) );
  253. // dispatch( setListChecked([], 0) );
  254. // }).catch(function (e) {
  255. // p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA4: ' + e});
  256. // DBG1 && console.warn('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) ERROR dispatch error');
  257. // // var fullListPks = ['select-all'].concat(listPrimaryKeys)
  258. // // dispatch( checked ? setListUnchecked(fullListPks) : setListChecked(fullListPks) );
  259. // // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
  260. // // dispatch( setListLoading([]) );
  261. // });
  262. return new Promise(function (resolve, reject) {
  263. DBG1 && console.log('DBG::unselectAll action: (pks:['+listPrimaryKeys.join(',')+'])...');
  264. {
  265. reject('TODO: unselectAll');
  266. return;
  267. }
  268. // resolve();
  269. });
  270. };
  271. }
  272. function selectAllMatchingFilter(namespace, filterQuery) {
  273. DBG1 && console.log('DBG::selectAllMatchingFilter', { filterQuery });
  274. return function(dispatch, getState) {
  275. DBG1 && console.log('DBG::selectAllMatchingFilter state', state);
  276. var state = getState();
  277. var listPrimaryKeys = state.listPrimaryKeys;
  278. // var reqArgs = { typeName: namespace, primaryKey: listPrimaryKeys, filterQuery: filterQuery };
  279. // if (idContext) reqArgs.idContext = idContext;
  280. // return p5WPS__selectAllFeaturesMatchingFilter(reqArgs).then(function (listSelected) {
  281. // DBG1 && console.log('DBG::selectAllMatchingFilter dispatch success');
  282. // dispatch( setListChecked(listSelected.selected, listSelected.totalSelected) );
  283. // }).catch(function (e) {
  284. // p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA5: ' + e});
  285. // DBG1 && console.warn('DBG::selectAllMatchingFilter ERROR dispatch error');
  286. // // var fullListPks = ['select-all'].concat(listPrimaryKeys);
  287. // // dispatch( setListUnchecked(fullListPks) );
  288. // // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
  289. // dispatch( setListLoading([]) );
  290. // });
  291. return new Promise(function (resolve, reject) {
  292. DBG1 && console.log('DBG::selectAllMatchingFilter action: (pks:['+listPrimaryKeys.join(',')+'])...');
  293. {
  294. reject('TODO: selectAllMatchingFilter');
  295. return;
  296. }
  297. // resolve();
  298. });
  299. }
  300. }
  301. return {
  302. setPrimaryKeys: setPrimaryKeys,
  303. setChecked: setChecked,
  304. setUnchecked: setUnchecked,
  305. toggle: toggle,
  306. unselectAll: unselectAll,
  307. selectAllMatchingFilter: selectAllMatchingFilter,
  308. }
  309. }
  310. function bocian_createTableSelectedStateObject(idContext) {
  311. var _idContext = idContext || 0;
  312. return {
  313. store: createStoreWithThunkMiddleware(selectedStore),
  314. actions: selectedActions(_idContext),
  315. }
  316. }
  317. // TOOD: select OD/DO or default
  318. // swal({
  319. // title: 'Are you sure?',
  320. // text: "You won't be able to revert this!",
  321. // type: 'warning',
  322. // showCancelButton: true,
  323. // confirmButtonText: 'Yes, delete it!',
  324. // cancelButtonText: 'No, cancel!',
  325. // reverseButtons: true,
  326. // confirmButtonClass: 'btn btn-success',
  327. // cancelButtonClass: 'btn btn-danger',
  328. // buttonsStyling: false,
  329. // }).then((result) => {
  330. // if (result.value) {
  331. // DBG1 && console.log('DBG::setPrimaryKeys swal(value:'+result.value+') action: (pks:['+listPrimaryKeys.join(',')+'])');
  332. // // swalWithBootstrapButtons(
  333. // // 'Deleted!',
  334. // // 'Your file has been deleted.',
  335. // // 'success'
  336. // // )
  337. // } else if (result.dismiss === swal.DismissReason.cancel) {
  338. // DBG1 && console.log('DBG::setPrimaryKeys swal(cancel) action: (pks:['+listPrimaryKeys.join(',')+'])');
  339. // // swalWithBootstrapButtons(
  340. // // 'Cancelled',
  341. // // 'Your imaginary file is safe :)',
  342. // // 'error'
  343. // // )
  344. // } else {
  345. // DBG1 && console.log('DBG::setPrimaryKeys swal(else?) action: (pks:['+listPrimaryKeys.join(',')+'])');
  346. // }
  347. // })
  348. function _px(px) { return (!px) ? '0px' : '' + px + 'px'; }
  349. // var original_global__createTableSelectedStateObject = global.createTableSelectedStateObject; // to revert back to original
  350. { // make fixed panel to select checkbox context OD, DO or default
  351. var panelNode = document.createElement('div')
  352. var panelWidth = 600;
  353. panelNode.style.position = 'fixed';
  354. panelNode.style.top = _px(0);
  355. panelNode.style.width = _px(panelWidth);
  356. panelNode.style.left = _px(window.innerWidth > panelWidth ? Math.floor(window.innerWidth / 2 - panelWidth / 2) : 0);
  357. panelNode.style.padding = '8px 15px'
  358. panelNode.style.textAlign = 'center'
  359. panelNode.className = 'alert alert-info'
  360. panelNode.style.boxShadow = '6px 6px 20px 0px #31708f'
  361. // panelNode.style.border = '1px solid red'
  362. // panelNode.style.padding = '6px'
  363. // panelNode.style.backgroundColor = 'lightRed'
  364. // panelNode.style.color = 'black'
  365. panelNode.innerHTML = 'Wybierz elementy do raportu: ' +
  366. '<div class="tblAjax__footer__toolbar__pagination" style="display:inline-block">' +
  367. '<a class="btn btn-xs btn-default' + (BAZA_OD_DO === 'OD' ? ' active' : '') + '" href="' + URL_BAZA_OD + '">' + 'OD' + '</a>' +
  368. ' ' +
  369. '<a class="btn btn-xs btn-default' + (BAZA_OD_DO === 'DO' ? ' active' : '') + '" href="' + URL_BAZA_DO + '">' + 'DO' + '</a>' +
  370. ' ' +
  371. (!BAZA_OD_DO ? '' : '<a class="btn btn-xs btn-default" href="' + URL_BAZA_NONE + '">' + 'Anuluj' + '</a>') +
  372. '</div>' +
  373. '';
  374. document.body.appendChild(panelNode)
  375. }
  376. if (BAZA_OD_DO) {
  377. global.createTableSelectedStateObject = bocian_createTableSelectedStateObject;
  378. }