Ver código fonte

copy from bocian with new logo

Piotr Labudda 5 anos atrás
pai
commit
b95e33be3e
38 arquivos alterados com 13011 adições e 31 exclusões
  1. 0 0
      schema/ant-object/.gitkeep
  2. BIN
      schema/ant-object/default_db.BI___.zip
  3. 82 31
      theme/anton1.php
  4. 0 0
      theme/assets/css/styles.css
  5. BIN
      theme/assets/file_example/kontrahenci_example.zip
  6. BIN
      theme/assets/file_example/pracownicy_example.zip
  7. BIN
      theme/assets/images/button-red-border.png
  8. BIN
      theme/assets/images/button-red.png
  9. BIN
      theme/assets/images/logo-anton1-big.png
  10. BIN
      theme/assets/images/logo-anton1.png
  11. BIN
      theme/assets/images/logout.png
  12. 301 0
      theme/assets/js/graph/csaladenes/sankey/sankey-init.js
  13. 564 0
      theme/assets/js/graph/csaladenes/sankey/sankey.js
  14. 0 0
      theme/assets/js/graph/d3.v3.min.js
  15. 117 0
      theme/assets/js/graph/parser.js
  16. 330 0
      theme/assets/js/graph/sankey-init-widget.js
  17. 0 0
      theme/assets/js/scripts.js
  18. 86 0
      theme/assets/js/updateLastRaportProgress.js
  19. 137 0
      theme/assets/js/updateRaportProgress.js
  20. 457 0
      theme/assets/less/buttons.less
  21. 733 0
      theme/assets/less/styles.less
  22. 53 0
      theme/assets/less/variables.less
  23. 22 0
      theme/view/footer.php
  24. 212 0
      theme/view/home-old.php
  25. 38 0
      theme/view/home.php
  26. 75 0
      theme/view/login.php
  27. 41 0
      theme/view/logout.php
  28. 251 0
      theme/view/top.php
  29. 3352 0
      tools/Anton1.php
  30. 820 0
      tools/Anton1.php.addItemToRaport.js
  31. 1052 0
      tools/Anton1.php.graphShowHide.js
  32. 419 0
      tools/Anton1.php.graphTest.php
  33. 24 0
      tools/Anton1.php.page-about.view.php
  34. 63 0
      tools/Anton1.php.page-help.view.php
  35. 24 0
      tools/Anton1.php.page-offer.view.php
  36. 24 0
      tools/Anton1.php.page-training.view.php
  37. 171 0
      tools/Anton1.php.store.js
  38. 3563 0
      tools/Anton1.php.view.js

+ 0 - 0
schema/ant-object/.gitkeep


BIN
schema/ant-object/default_db.BI___.zip


+ 82 - 31
theme/anton1.php

@@ -4,36 +4,87 @@
 
 class Theme_anton1 extends ThemeDefault {
 
-	// function head() { // TODO: echo 'html tag inside <head>'
-	// }
-
-	// function top() { // TODO: first tag after body: top menu or header
-	// 	include dirname(__FILE__) . '/Bocian/top.php';
-	// }
-
-	// function footer() { // TODO: before </body>
-	// 	include dirname(__FILE__) . '/view/footer.php';
-	// }
-
-	// function login($data) { // TODO: login view
-	// 	if (is_array($data) && !empty($data)) {
-	// 		extract($data);
-	// 	}
-	// 	include dirname(__FILE__) . '/view/login.php';
-	// }
-
-	// function logout($data) { // TODO: logout view
-	// 	if (is_array($data) && !empty($data)) {
-	// 		extract($data);
-	// 	}
-	// 	include dirname(__FILE__) . '/view/logout.php';
-	// }
-
-	// function home($data) { // TODO: home page view
-	// 	if (is_array($data) && !empty($data)) {
-	// 		extract($data);
-	// 	}
-	// 	include dirname(__FILE__) . '/view/home.php';
-	// }
+	function head() {
+		// echo ''; // TODO: dodać bootsrap-theme-anton1
+		echo '<meta name="robots" content="noindex, nofollow">';
+		UI::inlineCSS(dirname(__FILE__) . '/assets/css/styles.css');
+		// main color: #d7142d - red
+		echo UI::h('style', [ 'type' => "text/css" ], "
+			.AjaxTable { font-size:14px }
+			.AjaxTable .tblAjax__head__filter .stickyCol1 button { padding:1px 3px }
+			.AjaxTable tbody .stickyCol1 { font-size:12px }
+			.popover-content li { text-align:left; font-size:14px }
+
+			.bi-btn-primary { padding:6px 12px; font-size:14px; background-color:#fff; color:#d7142d; border-color:#d7142d; }
+			.bi-btn-primary:hover { background-color:#d7142d; color:#fff; border-color:#d7142d; }
+			.bi-btn-primary .badge { background-color:#d7142d; color:#fff; border-color:#d7142d; }
+			.bi-btn-primary:hover .badge { background-color:#fff; color:#d7142d; border-color:#d7142d; }
+			.bi-btn-disabled-group-label { cursor: default; padding:6px 12px; font-size:14px; background-color:#fff; color:#d7142d; border-color:#d7142d; }
+
+			.btn-primary .badge { background-color:#d7142d; color:#fff; }
+			.btn-primary:hover .badge { background-color:#fff; color:#d7142d; }
+
+			.btn-xs { padding:6px 12px; }
+			.btn-xs .badge { padding:2px 5px; }
+		");
+		UI::inlineRawJS(dirname(__FILE__) . '/assets/js/graph/d3.v3.min.js');
+		UI::inlineRawJS(dirname(__FILE__) . '/assets/js/graph/csaladenes/sankey/sankey.js');
+		// UI::inlineRawJS(dirname(__FILE__) . '/assets/js/graph/csaladenes/sankey/sankey-init.js');
+		UI::inlineRawJS(dirname(__FILE__) . '/assets/js/graph/sankey-init-widget.js');
+	}
+
+
+	function top() {
+		include dirname(__FILE__) . '/view/top.php';
+		//todo: demo load data for graph :DELETE line if tested
+		// UI::inlineRawJS(dirname(__FILE__) . '/demoGraph/sampleData/sampleData.js');
+		// UI::inlineRawJS(dirname(__FILE__) . '/assets/js/graph/GetFeature.js');
+		// UI::inlineRawJS(dirname(__FILE__) . '/assets/js/graph/parser.js');
+	}
+
+	function footer() {
+		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_Anton1')->getLink('fetchProgressAjax', [ 'SKIP_TIMER' => "1" ])
+			]);
+		}
+
+		UI::inlineJS(dirname(__FILE__) . '/assets/js/updateLastRaportProgress.js', [
+			'DBG' => (V::get('DBG', '', $_GET)),
+			'DBG_FAKE_ANIM' => (V::get('DBG_FAKE_ANIM', '', $_GET)),
+			'URL_FETCH_BI_AUDIT_PROGRESS' => Router::getRoute('UrlAction_Anton1')->getLink('fetchProgressAjax', [ 'SKIP_TIMER' => "1" ]),
+			'URL_BI_AUDIT_RESULT' => Router::getRoute('UrlAction_BiAuditGenerate')->getLink(''),
+			'ID_ARG_BI_AUDIT_RESULT' => 'ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA'
+		]);
+	}
+
+	function login($data) {
+		if (is_array($data) && !empty($data)) {
+			extract($data);
+		}
+		include dirname(__FILE__) . '/view/login.php';
+	}
+
+	function logout($data) {
+		if (is_array($data) && !empty($data)) {
+			extract($data);
+		}
+		include dirname(__FILE__) . '/view/logout.php';
+	}
+
+	function home($data) {
+		if (is_array($data) && !empty($data)) {
+			extract($data);
+		}
+		include dirname(__FILE__) . '/view/home.php';
+	}
 
 }

Diferenças do arquivo suprimidas por serem muito extensas
+ 0 - 0
theme/assets/css/styles.css


BIN
theme/assets/file_example/kontrahenci_example.zip


BIN
theme/assets/file_example/pracownicy_example.zip


BIN
theme/assets/images/button-red-border.png


BIN
theme/assets/images/button-red.png


BIN
theme/assets/images/logo-anton1-big.png


BIN
theme/assets/images/logo-anton1.png


BIN
theme/assets/images/logout.png


+ 301 - 0
theme/assets/js/graph/csaladenes/sankey/sankey-init.js

@@ -0,0 +1,301 @@
+/*This software is released under the MIT License
+MIT License 2014 Denes Csala http://www.csaladen.es
+The following software uses the javascript frameworks below,
+all of which are distributed under the MIT or GNU/GPL license:
+D3.js http://d3js.org/  data-oriented javascript framework.
+	- Sankey plugin http://bost.ocks.org/mike/sankey/ for D3.js (modified) by Mike Bostock,
+	  which is based on the initial version http://tamc.github.io/Sankey/ by Thomas Counsell.
+	  I have incorporated the ability to render Sankey cycles, as pioneered by https://github.com/cfergus
+	- Dragdealer.js href="http://skidding.github.io/dragdealer/ by Ovidiu Chereches
+*/
+
+//<!--DATA ENTRY-->
+
+nodesform=d3.select("#nodes-form");
+function addnode() {
+	var a=nodesform.append("div");
+	a.text(nodesform[0][0].children.length-1+' ');
+	a.append("input").attr("value",'{"name":"New Node"}');
+}
+function removenode() {
+	nodesform[0][0].children[nodesform[0][0].children.length-1].remove("div")
+}
+linksform=d3.select("#links-form");
+function addlink() {
+	linksform.append("div").append("input").attr("value",'{"source":0,"target":1,"value":0.52}');
+}
+function removelink() {
+	linksform[0][0].children[linksform[0][0].children.length-1].remove("div")
+}
+function draw() {
+	change(data);
+}
+function save(){
+	d3.select('#save').style('z-index',100).transition().style('opacity',0.9);
+	st='{"sankey":{"nodes":['
+	for (i = 0; i < nodesform[0][0].children.length; i++) {
+		st=st+nodesform[0][0].children[i].children[0].value+',';
+	}
+	st=st.substring(0, st.length - 1)+'],"links":[';
+	for (i = 0; i < linksform[0][0].children.length; i++) {
+		st=st+linksform[0][0].children[i].children[0].value+',';
+	}
+	st = st.substring(0, st.length - 1)+']},"params":['+densityslider.value.current[0]+','+opacityslider.value.current[0]+','+labelformat+','+labeltextformat+','+showlinkcount+']';
+	if (document.getElementById("fixedlayout").checked){
+		var coords=[]
+		sankey.nodes().forEach(function(d){
+			coords.push([d.x,d.y])
+		})
+		st=st+',"fixedlayout":'+JSON.stringify(coords);
+	}
+	st=st+'}';
+	d3.select('#savetext').text(st);
+}
+function load(){
+	d3.select('#load').style('z-index',100).transition().style('opacity',0.9);
+}
+function loadsubmit(){
+	d3.select('#load').transition().style('opacity',0).style('z-index',-1);
+	var rawtext=d3.select('#load')[0][0].children[1].value;
+	if (rawtext!="") {
+		//parse data
+		var rawdata=JSON.parse(rawtext);
+		if ("sankey" in rawdata) {
+			var newdata=rawdata.sankey;
+		}
+		else {
+			var newdata=rawdata;
+		}
+		var loadtext=JSON.stringify(newdata)
+		//remove existing node entry boxes
+		var n=nodesform[0][0].children.length;
+		for (i = 0; i < n; i++) {
+			nodesform[0][0].children[0].remove("div");
+		}
+		//remove existing link entry boxes
+		var n=linksform[0][0].children.length;
+		for (i = 0; i < n; i++) {
+			linksform[0][0].children[0].remove("div");
+		}
+		//add new node entry boxes
+		var newdata2=JSON.parse(loadtext.substring(loadtext.indexOf('"nodes":[')+8, loadtext.indexOf('"links":[')-1));
+		for (i = 0; i < newdata2.length; i++) {
+			var a=nodesform.append("div");
+			a.text(nodesform[0][0].children.length-1+' ');
+			a.append("input").attr("value",JSON.stringify(newdata2[i]));
+		}
+		//add new link entry boxes
+		var newdata2=JSON.parse(loadtext.substring(loadtext.indexOf('"links":[')+8, loadtext.length - 1))
+		for (i = 0; i < newdata2.length; i++) {
+			linksform.append("div").append("input").attr("value",JSON.stringify(newdata2[i]));
+		}
+		//set parameters
+		if ("fixedlayout" in rawdata) {
+			fixedlayout=document.getElementById("ignorelayout").checked?[]:rawdata.fixedlayout;
+		} else {
+			fixedlayout=[];
+		}
+		if ("params" in rawdata) {
+			labelformat=rawdata.params[2];
+			labeltextformat=rawdata.params[3];
+			if (rawdata.params.length>4) showlinkcount=rawdata.params[4];
+			else showlinkcount=0;
+			document.getElementById("vlabel").checked=(labelformat==0)?true:false;
+			document.getElementById("tlabel").checked=(labeltextformat==0)?true:false;
+			document.getElementById("clabel").checked=(showlinkcount==1)?true:false;
+			densityslider.setValue(rawdata.params[0]);
+			opacityslider.setValue(rawdata.params[1]);
+		}
+		else {
+			change(newdata);
+		}
+	}
+}
+
+//<!--SANKEY DIAGRAM-->
+
+var parallelrendering=false;
+var minnodewidth = 50;
+var padding = 28;
+var labelformat = 0;
+var labeltextformat = 0;
+var showlinkcount = 0;
+var paddingmultiplier = 100;
+var lowopacity = 0.3;
+var highopacity = 0.7;
+var fixedlayout=[];
+var format2Number = d3.format(",.2f"),
+    format1Number = d3.format(",.1f"),
+	format3Number = d3.format(",.3f"),
+	formatNumber = d3.format(",.0f"),
+    format = function(a) {
+        return formatNumber(a)
+    },color = d3.scale.category20();
+	linkformat= function(a) {
+		// if (d3.select("#ldec").node().value==0) return formatNumber(a);
+		// if (d3.select("#ldec").node().value==1) return format1Number(a);
+		// if (d3.select("#ldec").node().value==2) return format2Number(a);
+		return formatNumber(a);
+	},
+	nodeformat= function(a) {
+		// if (d3.select("#ndec").node().value==0) return formatNumber(a);
+		// if (d3.select("#ndec").node().value==1) return format1Number(a);
+		// if (d3.select("#ndec").node().value==2) return format2Number(a);
+		return formatNumber(a);
+	};
+//
+// d3.select("#ndec")
+// .on("change",draw);
+// d3.select("#ldec")
+// .on("change",draw);
+
+
+
+  d3.select("#chart").style("width", document.getElementById("chart").offsetWidth)
+  var margin = {
+          top: 10,
+          right: 10,
+          bottom: 10,
+          left: 40
+      },
+  		width = document.getElementById("chart").offsetWidth - margin.left - margin.right,
+      height = document.getElementById("chart").offsetHeight - margin.bottom;
+  var svg = d3.select("#chart").append("svg")
+  svg.append("rect").attr("x",0).attr("y",0).attr("width","100%").attr("height","100%").attr("fill","white").attr('class','background').on('mouseup', () => redraw())
+  svg=svg.attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom).append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
+
+  //set svg background color via rectangle trick
+  d3.select("#chart").select("svg")
+
+  var sankey = d3.sankey().nodeWidth(30).nodePadding(padding).size([width, height]);
+  var path = sankey.reversibleLink();
+  var change = function(d) {
+
+  	svg.selectAll("g").remove();
+  	sankey = d3.sankey().nodeWidth(30).nodePadding(padding).size([width, height]);
+  	sankey.nodes(d.nodes).links(d.links).layout(500);
+  	var g = svg.append("g") //link
+  		.selectAll(".link").data(d.links).enter().append("g").attr("class", "link").sort(function(j, i) {
+  			return i.dy - j.dy
+  		});
+  	var h = g.append("path") //path0
+  		.attr("d", path(0));
+  	var f = g.append("path") //path1
+  		.attr("d", path(1));
+  	var e = g.append("path") //path2
+  		.attr("d", path(2));
+  	g.attr("fill", function(i) {
+  			if (i.fill) return i.fill;
+  			else if (i.source.fill) return i.source.fill;
+  			else return i.source.color = color(i.source.name.replace(/ .*/, ""))
+  		}).attr("opacity", lowopacity).on("mouseover", function(d) {
+  			d3.select(this).style('opacity', highopacity);
+  		}).on("mouseout", function(d) {
+  			d3.select(this).style('opacity', lowopacity);
+  		}).append("title") //link
+  		.text(function(i) {
+  			return i.source.name + " → " + i.target.name + "\n" + linkformat(i.value)
+  		});
+  	var c = svg.append("g") //node
+  		.selectAll(".node").data(d.nodes).enter().append("g").attr("class", "node").attr("transform", function(i) {
+  			return "translate(" + i.x + "," + i.y + ")"
+  		}).call(d3.behavior.drag().origin(function(i) {
+  			return i
+  		}).on("dragstart", function() {
+  			this.parentNode.appendChild(this)
+  		}).on("drag", b));
+  	c.append("rect") //node
+  		.attr("height", function(i) {
+  			return i.dy
+  		}).attr("width", sankey.nodeWidth()).style("fill", function(i) {
+  			if (i.fill) return i.color = i.fill;
+  								else return i.color = color(i.name.replace(/ .*/, ""))
+  		}).style("stroke", function(i) {
+  			return d3.rgb(i.color).darker(2)
+  		}).on("mouseover", function(d) {
+  			svg.selectAll(".link").filter(function(l) {
+  				return l.source == d || l.target == d;
+  			}).transition().style('opacity', highopacity);
+  		}).on("mouseout", function(d) {
+  			svg.selectAll(".link").filter(function(l) {
+  				return l.source == d || l.target == d;
+  			}).transition().style('opacity', lowopacity);
+  		}).on("dblclick", function(d) {
+  			svg.selectAll(".link").filter(function(l) {
+  				return l.target == d;
+  			}).attr("display", function() {
+  				if (d3.select(this).attr("display") == "none") return "inline"
+  				else return "none"
+  			});
+  		}).append("title").text(function(i) {
+  			return i.name + "\n" + nodeformat(i.value)
+
+  		});
+  	c.append("text") //node
+  		.attr("x", -6).attr("y", function(i) {
+  			return i.dy / 2
+  		}).attr("dy", ".35em").attr("text-anchor", "end").attr("font-size","16px")
+  		.text(function(i) {
+  		if (labeltextformat<1){
+  				return i.name;
+  			} else {
+  				return "";
+  			}
+  		}).filter(function(i) {
+  			return i.x < width / 2
+  		}).attr("x", 6 + sankey.nodeWidth()).attr("text-anchor", "start")
+  	if (showlinkcount>0) c.append("text") //node
+  		.attr("x", -6).attr("y", function(i) {
+  			return i.dy / 2 + 20
+  		}).attr("dy", ".35em").attr("text-anchor", "end").attr("font-size","16px")
+  		.text(function(i) {
+  			return "→ "+(i.targetLinks.length)+" | "+(i.sourceLinks.length)+" →";
+  		}).filter(function(i) {
+  			return i.x < width / 2
+  		}).attr("x", 6 + sankey.nodeWidth()).attr("text-anchor", "start")
+  	c.append("text") //node
+  		.attr("x", function(i) {return -i.dy / 2})
+  		.attr("y", function(i) {return i.dx / 2 + 9})
+  		.attr("transform", "rotate(270)").attr("text-anchor", "middle").attr("font-size","23px").text(function(i) {
+  			if ((i.dy>minnodewidth)&&(labelformat<1)){
+  				return nodeformat(i.value);
+  			}
+  		}).attr("fill",function(d){
+  			return d3.rgb(d["color"]).brighter(2)
+  		}).attr("stroke",function(d){
+  			return d3.rgb(d["color"]).darker(2)
+  		}).attr("stroke-width","1px");
+  		svg.selectAll('rect')
+  		.on('mouseover', (a, b, c, d, e) => {console.log('mouseover', a, b, c, d, e)})
+  		.on('mouseout', (a, b, c, d, e) => {console.log('mouseout', a, b, c, d, e)})
+  		.on('mousedown', (a, b, c, d, e) => {console.log('mousedown', a, b, c, d, e)})
+  		.on('mouseup', a => !a.expanded && redraw({type: a.name, criteria: 'ID'}));
+
+  	function b(i) { //dragmove
+  		// if (document.getElementById("ymove").checked) {
+  			// if (document.getElementById("xmove").checked) {
+  			// 	d3.select(this).attr("transform", "translate(" + (i.x = Math.max(0, Math.min(width - i.dx, d3.event.x))) + "," + (i.y = Math.max(0, Math.min(height - i.dy, d3.event.y))) + ")")
+  			// } else {
+  			dragged = true;
+  				d3.select(this).attr("transform", "translate(" + i.x + "," + (i.y = Math.max(0, Math.min(height - i.dy, d3.event.y))) + ")")
+  		// 	}
+  		// } else {
+  		// 	if (document.getElementById("xmove").checked) {
+  		// 		d3.select(this).attr("transform", "translate(" + (i.x = Math.max(0, Math.min(width - i.dx, d3.event.x))) + "," + i.y + ")")
+  		// 	}
+  		// }
+  		sankey.relayout();
+  		f.attr("d", path(1));
+  		h.attr("d", path(0));
+  		e.attr("d", path(2))
+  	};
+  };
+  draw();
+
+
+
+function seturl(){
+exportInlineSVG(d3.select("#chart").select("svg").node(), function(data) {
+	d3.select("#pngdownload").node().href=data;
+});
+}

+ 564 - 0
theme/assets/js/graph/csaladenes/sankey/sankey.js

@@ -0,0 +1,564 @@
+d3.sankey = function() {
+  var sankey = {},
+      nodeWidth = 24,
+      nodePadding = 8,
+      size = [1, 1],
+      nodes = [],
+      links = [],
+      components = [];
+
+  sankey.nodeWidth = function(_) {
+    if (!arguments.length) return nodeWidth;
+    nodeWidth = +_;
+    return sankey;
+  };
+
+  sankey.nodePadding = function(_) {
+    if (!arguments.length) return nodePadding;
+    nodePadding = +_;
+    return sankey;
+  };
+
+  sankey.nodes = function(_) {
+    if (!arguments.length) return nodes;
+    nodes = _;
+    return sankey;
+  };
+
+  sankey.links = function(_) {
+    if (!arguments.length) return links;
+    links = _;
+    return sankey;
+  };
+
+  sankey.size = function(_) {
+    if (!arguments.length) return size;
+    size = _;
+    return sankey;
+  };
+
+  sankey.layout = function(iterations) {
+    computeNodeLinks();
+    computeNodeValues();
+
+    computeNodeStructure();
+    computeNodeBreadths();
+
+    computeNodeDepths(iterations);
+    computeLinkDepths();
+
+    return sankey;
+  };
+
+  sankey.relayout = function() {
+    computeLinkDepths();
+    return sankey;
+  };
+
+  sankey.reversibleLink = function() {
+    var curvature = .5;
+
+    // Used when source is behind target, the first and last paths are simple
+    // lines at the start and end node while the second path is the spline
+    function forwardLink(part, d) {
+      var x0 = d.source.x + d.source.dx,
+          x1 = d.target.x,
+          xi = d3.interpolateNumber(x0, x1),
+          x2 = xi(curvature),
+          x3 = xi(1 - curvature),
+          y0 = d.source.y + d.sy,
+          y1 = d.target.y + d.ty,
+          y2 = d.source.y + d.sy + d.dy,
+          y3 = d.target.y + d.ty + d.dy;
+
+      switch (part) {
+        case 0:
+          return "M" + x0 + "," + y0 + "L" + x0 + "," + (y0 + d.dy);
+
+        case 1:
+          return "M" + x0 + "," + y0
+               + "C" + x2 + "," + y0 + " " + x3 + "," + y1 + " " + x1 + "," + y1
+               + "L" + x1 + "," + y3
+               + "C" + x3 + "," + y3 + " " + x2 + "," + y2 + " " + x0 + "," + y2
+               + "Z";
+
+        case 2:
+          return "M" + x1 + "," + y1 + "L" + x1 + "," + (y1 + d.dy);
+      }
+    }
+
+    // Used for self loops and when the source is actually in front of the
+    // target; the first element is a turning path from the source to the
+    // destination, the second element connects the two twists and the last
+    // twists into the target element.
+    //
+    //
+    //  /--Target
+    //  \----------------------\
+    //                 Source--/
+    //
+    function backwardLink(part, d) {
+      var curveExtension = 30;
+      var curveDepth = 15;
+
+      function getDir(d) {
+        return d.source.y + d.sy > d.target.y + d.ty ? -1 : 1;
+      }
+
+      function p(x, y) {
+        return x + "," + y + " ";
+      }
+
+      var dt = getDir(d) * curveDepth,
+          x0 = d.source.x + d.source.dx,
+          y0 = d.source.y + d.sy,
+          x1 = d.target.x,
+          y1 = d.target.y + d.ty;
+
+      switch (part) {
+        case 0:
+          return "M" + p(x0, y0) +
+                 "C" + p(x0, y0) +
+                       p(x0 + curveExtension, y0) +
+                       p(x0 + curveExtension, y0 + dt) +
+                 "L" + p(x0 + curveExtension, y0 + dt + d.dy) +
+                 "C" + p(x0 + curveExtension, y0 + d.dy) +
+                       p(x0, y0 + d.dy) +
+                       p(x0, y0 + d.dy) +
+                 "Z";
+        case 1:
+          return "M" + p(x0 + curveExtension, y0 + dt) +
+                 "C" + p(x0 + curveExtension, y0 + 3 * dt) +
+                       p(x1 - curveExtension, y1 - 3 * dt) +
+                       p(x1 - curveExtension, y1 - dt) +
+                 "L" + p(x1 - curveExtension, y1 - dt + d.dy) +
+                 "C" + p(x1 - curveExtension, y1 - 3 * dt + d.dy) +
+                       p(x0 + curveExtension, y0 + 3 * dt + d.dy) +
+                       p(x0 + curveExtension, y0 + dt + d.dy) +
+                 "Z";
+
+        case 2:
+          return "M" + p(x1 - curveExtension, y1 - dt) +
+                 "C" + p(x1 - curveExtension, y1) +
+                       p(x1, y1) +
+                       p(x1, y1) +
+                 "L" + p(x1, y1 + d.dy) +
+                 "C" + p(x1, y1 + d.dy) +
+                       p(x1 - curveExtension, y1 + d.dy) +
+                       p(x1 - curveExtension, y1 + d.dy - dt) +
+                 "Z";
+      }
+    }
+
+    return function(part) {
+      return function(d) {
+        if (d.source.x < d.target.x) {
+          return forwardLink(part, d);
+        } else {
+          return backwardLink(part, d);
+        }
+      }
+    }
+  };
+
+  // The standard link path using a constant width spline that needs a
+  // single path element.
+  sankey.link = function() {
+    var curvature = .5;
+
+    function link(d) {
+      var x0 = d.source.x + d.source.dx,
+          x1 = d.target.x,
+          xi = d3.interpolateNumber(x0, x1),
+          x2 = xi(curvature),
+          x3 = xi(1 - curvature),
+          y0 = d.source.y + d.sy + d.dy / 2,
+          y1 = d.target.y + d.ty + d.dy / 2;
+      return "M" + x0 + "," + y0
+           + "C" + x2 + "," + y0
+           + " " + x3 + "," + y1
+           + " " + x1 + "," + y1;
+    }
+
+    link.curvature = function(_) {
+      if (!arguments.length) return curvature;
+      curvature = +_;
+      return link;
+    };
+
+    return link;
+  };
+
+  // Populate the sourceLinks and targetLinks for each node.
+  // Also, if the source and target are not objects, assume they are indices.
+  function computeNodeLinks() {
+    nodes.forEach(function(node) {
+      node.sourceLinks = [];
+      node.targetLinks = [];
+    });
+
+    links.forEach(function(link) {
+      var source = link.source,
+          target = link.target;
+      source = (typeof source === "number") ? nodes[source] : nodes.find(node => node.name === source);
+      target = (typeof target === "number") ? nodes[target] : nodes.find(node => node.name === target);
+      link.source = source
+      link.target = target
+      source.sourceLinks.push(link);
+      target.targetLinks.push(link);
+    });
+  }
+
+  // Compute the value (size) of each node by summing the associated links.
+  function computeNodeValues() {
+    nodes.forEach(function(node) {
+      if (!(node.value)) //if not already given
+	  node.value = Math.max(
+        d3.sum(node.sourceLinks, value),
+        d3.sum(node.targetLinks, value)
+      );
+    });
+  }
+
+  // Take the list of nodes and create a DAG of supervertices, each consisting
+  // of a strongly connected component of the graph
+  //
+  // Based off:
+  // http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
+  function computeNodeStructure() {
+    var nodeStack = [],
+        index = 0;
+
+    nodes.forEach(function(node) {
+      if (!node.index) {
+        connect(node);
+      }
+    });
+
+    function connect(node) {
+      node.index = index++;
+      node.lowIndex = node.index;
+      node.onStack = true;
+      nodeStack.push(node);
+
+      if (node.sourceLinks) {
+        node.sourceLinks.forEach(function(sourceLink){
+          var target = sourceLink.target;
+          if (!target.hasOwnProperty('index')) {
+            connect(target);
+            node.lowIndex = Math.min(node.lowIndex, target.lowIndex);
+          } else if (target.onStack) {
+            node.lowIndex = Math.min(node.lowIndex, target.index);
+          }
+        });
+
+        if (node.lowIndex === node.index) {
+          var component = [], currentNode;
+          do {
+            currentNode = nodeStack.pop()
+            currentNode.onStack = false;
+            component.push(currentNode);
+          } while (currentNode != node);
+          components.push({
+            root: node,
+            scc: component
+          });
+        }
+      }
+    }
+
+    components.forEach(function(component, i){
+      component.index = i;
+      component.scc.forEach(function(node) {
+        node.component = i;
+      });
+    });
+  }
+
+  // Assign the breadth (x-position) for each strongly connected component,
+  // followed by assigning breadth within the component.
+  function computeNodeBreadths() {
+
+    layerComponents();
+
+    components.forEach(function(component, i){
+      bfs(component.root, function(node){
+        var result = node.sourceLinks
+          .filter(function(sourceLink){
+            return sourceLink.target.component == i;
+          })
+          .map(function(sourceLink){
+            return sourceLink.target;
+          });
+        return result;
+      });
+    });
+
+    var max = 0;
+    var componentsByBreadth = d3.nest()
+      .key(function(d) { return d.x; })
+      .sortKeys(d3.ascending)
+      .entries(components)
+      .map(function(d) { return d.values; });
+
+    var max = -1, nextMax = -1;
+    componentsByBreadth.forEach(function(c){
+      c.forEach(function(component){
+        component.x = max + 1;
+        component.scc.forEach(function(node){
+		  if (node.layer) node.x=node.layer;
+          else node.x = component.x + node.x;
+          nextMax = Math.max(nextMax, node.x);
+        });
+      });
+      max = nextMax;
+    });
+
+
+    nodes
+      .filter(function(node) {
+        var outLinks = node.sourceLinks.filter(function(link){ return link.source.name != link.target.name; });
+        return (outLinks.length == 0);
+      })
+      .forEach(function(node) { node.x = (node.layer)?node.x:max; })
+
+    scaleNodeBreadths((size[0] - nodeWidth) / Math.max(max, 1));
+
+    function flatten(a) {
+      return [].concat.apply([], a);
+    }
+
+    function layerComponents() {
+      var remainingComponents = components,
+          nextComponents,
+          visitedIndex,
+          x = 0;
+
+      while (remainingComponents.length) {
+        nextComponents = [];
+        visitedIndex = {};
+
+        remainingComponents.forEach(function(component) {
+          component.x = x;
+
+          component.scc.forEach(function(n) {
+            n.sourceLinks.forEach(function(l) {
+              if (!visitedIndex.hasOwnProperty(l.target.component) &&
+                   l.target.component != component.index) {
+                nextComponents.push(components[l.target.component]);
+                visitedIndex[l.target.component] = true;
+              }
+            })
+          });
+        });
+
+        remainingComponents = nextComponents;
+        ++x;
+      }
+    }
+
+    function bfs(node, extractTargets) {
+      var queue = [node], currentCount = 1, nextCount = 0;
+      var x = 0;
+
+      while(currentCount > 0) {
+        var currentNode = queue.shift();
+        currentCount--;
+
+        if (!currentNode.hasOwnProperty('x')) {
+          currentNode.x = x;
+          currentNode.dx = nodeWidth;
+
+          var targets = extractTargets(currentNode);
+
+          queue = queue.concat(targets);
+          nextCount += targets.length;
+        }
+
+
+        if (currentCount == 0) { // level change
+          x++;
+          currentCount = nextCount;
+          nextCount = 0;
+        }
+
+      }
+    }
+
+	//extra code for fixed layout - x part
+	if (fixedlayout.length>0) {
+	  sankey.nodes().forEach(function(d,i){
+		d.x=fixedlayout[i][0];
+	  })
+	}
+
+  }
+
+  function moveSourcesRight() {
+    nodes.forEach(function(node) {
+      if (!node.targetLinks.length) {
+        node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
+      }
+    });
+  }
+
+  function moveSinksRight(x) {
+    nodes.forEach(function(node) {
+      if (!node.sourceLinks.length) {
+        node.x = x - 1;
+      }
+    });
+  }
+
+  function scaleNodeBreadths(kx) {
+    nodes.forEach(function(node) {
+      node.x *= kx;
+    });
+  }
+
+  function computeNodeDepths(iterations) {
+    var nodesByBreadth = d3.nest()
+        .key(function(d) { return d.x; })
+        .sortKeys(d3.ascending)
+        .entries(nodes)
+        .map(function(d) { return d.values; });
+
+    initializeNodeDepth();
+    resolveCollisions();
+
+    for (var alpha = 1; iterations > 0; --iterations) {
+      relaxRightToLeft(alpha *= .99);
+      resolveCollisions();
+      relaxLeftToRight(alpha);
+      resolveCollisions();
+    }
+
+    function initializeNodeDepth() {
+      var ky = d3.min(nodesByBreadth, function(nodes) {
+        return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value);
+      });
+
+      nodesByBreadth.forEach(function(nodes) {
+        nodes.forEach(function(node, i) {
+          node.y = i;
+          node.dy = node.value * ky;
+        });
+      });
+
+      links.forEach(function(link) {
+        link.dy = link.value * ky;
+      });
+    }
+
+    function relaxLeftToRight(alpha) {
+      nodesByBreadth.forEach(function(nodes, breadth) {
+        nodes.forEach(function(node) {
+          if (node.targetLinks.length) {
+            var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);
+            node.y += (y - center(node)) * alpha;
+          }
+        });
+      });
+
+      function weightedSource(link) {
+        return center(link.source) * link.value;
+      }
+    }
+
+    function relaxRightToLeft(alpha) {
+      nodesByBreadth.slice().reverse().forEach(function(nodes) {
+        nodes.forEach(function(node) {
+          if (node.sourceLinks.length) {
+            var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value);
+            node.y += (y - center(node)) * alpha;
+          }
+        });
+      });
+
+      function weightedTarget(link) {
+        return center(link.target) * link.value;
+      }
+    }
+
+    function resolveCollisions() {
+      nodesByBreadth.forEach(function(nodes) {
+        var node,
+            dy,
+            y0 = 0,
+            n = nodes.length,
+            i;
+
+        // Push any overlapping nodes down.
+        nodes.sort(ascendingDepth);
+        for (i = 0; i < n; ++i) {
+          node = nodes[i];
+          dy = y0 - node.y;
+          if (dy > 0) node.y += dy;
+          y0 = node.y + node.dy + nodePadding;
+        }
+
+        // If the bottommost node goes outside the bounds, push it back up.
+        dy = y0 - nodePadding - size[1];
+        if (dy > 0) {
+          y0 = node.y -= dy;
+
+          // Push any overlapping nodes back up.
+          for (i = n - 2; i >= 0; --i) {
+            node = nodes[i];
+            dy = node.y + node.dy + nodePadding - y0;
+            if (dy > 0) node.y -= dy;
+            y0 = node.y;
+          }
+        }
+      });
+    }
+
+    function ascendingDepth(a, b) {
+      return a.y - b.y;
+    }
+
+	//extra code for fixed layout - y part
+	if (fixedlayout.length>0) {
+	  sankey.nodes().forEach(function(d,i){
+		d.y=fixedlayout[i][1];
+	  })
+	}
+  }
+
+  function computeLinkDepths() {
+    nodes.forEach(function(node) {
+      if (parallelrendering) {}
+	  else node.sourceLinks.sort(ascendingTargetDepth);
+      node.targetLinks.sort(ascendingSourceDepth);
+    });
+    nodes.forEach(function(node) {
+      var sy = 0, ty = 0;
+      node.sourceLinks.forEach(function(link) {
+        link.sy = sy;
+        sy += link.dy;
+      });
+      node.targetLinks.forEach(function(link) {
+        link.ty = ty;
+        ty += link.dy;
+      });
+    });
+
+    function ascendingSourceDepth(a, b) {
+      return a.source.y - b.source.y;
+    }
+
+    function ascendingTargetDepth(a, b) {
+      return a.target.y - b.target.y;
+    }
+  }
+
+  function center(node) {
+    return node.y + node.dy / 2;
+  }
+
+  function value(link) {
+    return link.value;
+  }
+
+  return sankey;
+};

Diferenças do arquivo suprimidas por serem muito extensas
+ 0 - 0
theme/assets/js/graph/d3.v3.min.js


+ 117 - 0
theme/assets/js/graph/parser.js

@@ -0,0 +1,117 @@
+var responseObjects = p5WFS_GetFeature();
+var object = responseObjects[0];
+
+var nodes = {};
+var nodesArray = [];
+var links = {};
+var linksArray = [];
+var instanceTypes = {};
+var dragged = false;
+
+const hasTargetArray = node => {
+  for (const prop in node)
+    if (node[prop].constructor === Array)
+      return {array: node[prop], name: prop.split(':').pop().replace(/BI_audit_/, '')};
+  return false;
+}
+
+const getLinks = (array, expansion) => {
+
+  if (array != undefined && expansion !== undefined) {
+    array.forEach(element => {
+      const rowObject = hasTargetArray(element);
+      if (rowObject) {
+        for (let i = rowObject.array.length - 2; i >= 0; i--) {
+          const target = hasTargetArray(rowObject.array[i]);
+          const source = hasTargetArray(rowObject.array[i + 1]);
+          let sourceGroup = source.name;
+          let targetGroup = target.name;
+          if (expansion && expansion.type) {
+            if (sourceGroup === expansion.type)
+              sourceGroup = source.array[0][expansion.criteria];
+            if (targetGroup === expansion.type)
+              targetGroup = target.array[0][expansion.criteria];
+          }
+          if (!links.hasOwnProperty(sourceGroup))
+            links[sourceGroup] = {};
+          if (links[sourceGroup].hasOwnProperty(targetGroup)) {
+            links[sourceGroup][targetGroup]++;
+          } else if (targetGroup) {
+            links[sourceGroup][targetGroup] = 1;
+          }
+        }
+      }
+    })
+  }
+};
+
+const getNodes = (array, expansion) => {
+
+    if (array != undefined && expansion !== undefined) {
+      array.forEach(element => {
+        const rowObject = hasTargetArray(element);
+        if (rowObject)
+          rowObject.array.forEach(objectElement => {
+            const trackNode = hasTargetArray(objectElement);
+            if (trackNode) {
+              let group = trackNode.name;
+              let expanded = false;
+              if (expansion && expansion.type && group === expansion.type) {
+                group = trackNode.array[0][expansion.criteria];
+                expanded = true;
+              }
+              nodes[group] = {expanded: expanded, type: trackNode.name};
+              instanceTypes[trackNode.array[0].ID] = group;
+            }
+          });
+      });
+    }
+
+};
+
+const parseNodes = () => {
+  for (const node in nodes) {
+    if (nodes.hasOwnProperty(node))
+      nodesArray.push({name: node, expanded: nodes[node].expanded, type: nodes[node].type});
+  }
+};
+
+const parseLinks = () => {
+  for (const link in links) {
+    if (links.hasOwnProperty(link)) {
+      for (const target in links[link]) {
+        if (links[link].hasOwnProperty(target)) {
+          linksArray.push({
+            source: link,
+            target: target,
+            value: links[link][target]
+          });
+        }
+      }
+    }
+  }
+};
+
+const parseGraph = (expansion) => {
+  nodes = {};
+  links = {};
+  nodesArray = [];
+  linksArray = [];
+  getNodes(responseObjects[0]["default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row"], expansion);
+  parseNodes();
+  getLinks(responseObjects[0]["default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row"], expansion);
+  parseLinks();
+  dataModel = data = {
+    nodes: nodesArray,
+    links: linksArray
+  };
+};
+
+const redraw = (expansion) => {
+  if (dragged)
+    return dragged = false;
+  parseGraph(expansion);
+  draw();
+};
+
+parseGraph();

+ 330 - 0
theme/assets/js/graph/sankey-init-widget.js

@@ -0,0 +1,330 @@
+(function (global) {
+
+	var dispatch = d3.dispatch("click");
+
+// ----
+
+/*This software is released under the MIT License
+
+MIT License 2014 Denes Csala http://www.csaladen.es
+
+The following software uses the javascript frameworks below,
+all of which are distributed under the MIT or GNU/GPL license:
+D3.js http://d3js.org/  data-oriented javascript framework.
+	- Sankey plugin http://bost.ocks.org/mike/sankey/ for D3.js (modified) by Mike Bostock,
+	  which is based on the initial version http://tamc.github.io/Sankey/ by Thomas Counsell.
+	  I have incorporated the ability to render Sankey cycles, as pioneered by https://github.com/cfergus
+	- Dragdealer.js href="http://skidding.github.io/dragdealer/ by Ovidiu Chereches
+*/
+
+//<!--DATA INIT-->
+
+var data={"nodes": [], "links": []}
+
+//<!--DATA ENTRY-->
+
+nodesform=d3.select("#nodes-form");
+function addnode() {
+	var a=nodesform.append("div");
+	a.text(nodesform[0][0].children.length-1+' ');
+	a.append("input").attr("value",'{"name":"New Node"}');
+}
+function removenode() {
+	nodesform[0][0].children[nodesform[0][0].children.length-1].remove("div")
+}
+linksform=d3.select("#links-form");
+function addlink() {
+	linksform.append("div").append("input").attr("value",'{"source":0,"target":1,"value":0.52}');
+}
+function removelink() {
+	linksform[0][0].children[linksform[0][0].children.length-1].remove("div")
+}
+function draw() {
+	change(data);
+}
+function save(){
+	d3.select('#save').style('z-index',100).transition().style('opacity',0.9);
+	st='{"sankey":{"nodes":['
+	for (i = 0; i < nodesform[0][0].children.length; i++) {
+		st=st+nodesform[0][0].children[i].children[0].value+',';
+	}
+	st=st.substring(0, st.length - 1)+'],"links":[';
+	for (i = 0; i < linksform[0][0].children.length; i++) {
+		st=st+linksform[0][0].children[i].children[0].value+',';
+	}
+	st = st.substring(0, st.length - 1)+']},"params":['+densityslider.value.current[0]+','+opacityslider.value.current[0]+','+labelformat+','+labeltextformat+','+showlinkcount+']';
+	if (document.getElementById("fixedlayout").checked){
+		var coords=[]
+		sankey.nodes().forEach(function(d){
+			coords.push([d.x,d.y])
+		})
+		st=st+',"fixedlayout":'+JSON.stringify(coords);
+	}
+	st=st+'}';
+	d3.select('#savetext').text(st);
+}
+function load(){
+	d3.select('#load').style('z-index',100).transition().style('opacity',0.9);
+}
+function loadsubmit(){
+	d3.select('#load').transition().style('opacity',0).style('z-index',-1);
+	var rawtext=d3.select('#load')[0][0].children[1].value;
+	if (rawtext!="") {
+		//parse data
+		var rawdata=JSON.parse(rawtext);
+		if ("sankey" in rawdata) {
+			var newdata=rawdata.sankey;
+		}
+		else {
+			var newdata=rawdata;
+		}
+		var loadtext=JSON.stringify(newdata)
+		//remove existing node entry boxes
+		var n=nodesform[0][0].children.length;
+		for (i = 0; i < n; i++) {
+			nodesform[0][0].children[0].remove("div");
+		}
+		//remove existing link entry boxes
+		var n=linksform[0][0].children.length;
+		for (i = 0; i < n; i++) {
+			linksform[0][0].children[0].remove("div");
+		}
+		//add new node entry boxes
+		var newdata2=JSON.parse(loadtext.substring(loadtext.indexOf('"nodes":[')+8, loadtext.indexOf('"links":[')-1));
+		for (i = 0; i < newdata2.length; i++) {
+			var a=nodesform.append("div");
+			a.text(nodesform[0][0].children.length-1+' ');
+			a.append("input").attr("value",JSON.stringify(newdata2[i]));
+		}
+		//add new link entry boxes
+		var newdata2=JSON.parse(loadtext.substring(loadtext.indexOf('"links":[')+8, loadtext.length - 1))
+		for (i = 0; i < newdata2.length; i++) {
+			linksform.append("div").append("input").attr("value",JSON.stringify(newdata2[i]));
+		}
+		//set parameters
+		if ("fixedlayout" in rawdata) {
+			fixedlayout=document.getElementById("ignorelayout").checked?[]:rawdata.fixedlayout;
+		} else {
+			fixedlayout=[];
+		}
+		if ("params" in rawdata) {
+			labelformat=rawdata.params[2];
+			labeltextformat=rawdata.params[3];
+			if (rawdata.params.length>4) showlinkcount=rawdata.params[4];
+			else showlinkcount=0;
+			document.getElementById("vlabel").checked=(labelformat==0)?true:false;
+			document.getElementById("tlabel").checked=(labeltextformat==0)?true:false;
+			document.getElementById("clabel").checked=(showlinkcount==1)?true:false;
+			densityslider.setValue(rawdata.params[0]);
+			opacityslider.setValue(rawdata.params[1]);
+		}
+		else {
+			change(newdata);
+		}
+	}
+}
+
+//<!--SANKEY DIAGRAM-->
+
+var parallelrendering=false;
+var minnodewidth = 50;
+var padding = 28;
+var labelformat = 0;
+var labeltextformat = 0;
+var showlinkcount = 0;
+var paddingmultiplier = 100;
+var lowopacity = 0.3;
+var highopacity = 0.7;
+var fixedlayout=[];
+var sankeyColor = d3.scale.category20();
+var sankeyNumberFormat = d3.format(",.0f");
+
+// d3.select("#ndec")
+// .on("change",draw);
+// d3.select("#ldec")
+// .on("change",draw);
+
+var margin = {
+        top: 10,
+        right: 10,
+        bottom: 10,
+        left: 40
+    };
+var width = 1000; //document.getElementById("chart").offsetWidth - margin.left - margin.right,
+var height = 500; // document.getElementById("chart").offsetHeight - margin.bottom;
+var svg = null;//d3.select("#chart").append("svg")
+//svg.append("rect").attr("x",0).attr("y",0).attr("width","100%").attr("height","100%").attr("fill","white").attr('class','background')
+//svg=svg.attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom).append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
+
+//set svg background color via rectangle trick
+// d3.select("#chart").select("svg")
+
+var sankey = null;
+// var sankey = d3.sankey().nodeWidth(30).nodePadding(padding).size([width, height]);
+// var path = sankey.reversibleLink();
+var change = function(d) {
+
+	svg.selectAll("g").remove();
+	sankey = d3.sankey().nodeWidth(30).nodePadding(padding).size([width, height]);
+	sankey.nodes(d.nodes).links(d.links).layout(500);
+	var g = svg.append("g") //link
+		.selectAll(".link").data(d.links).enter().append("g").attr("class", "link").sort(function(j, i) {
+			return i.dy - j.dy
+		});
+	var path = sankey.reversibleLink();
+	var h = g.append("path") //path0
+		.attr("d", path(0));
+	var f = g.append("path") //path1
+		.attr("d", path(1));
+	var e = g.append("path") //path2
+		.attr("d", path(2));
+	g.attr("fill", function(i) {
+			if (i.fill) return i.fill;
+			else if (i.source.fill) return i.source.fill;
+			else return i.source.color = sankeyColor(i.source.name.replace(/ .*/, ""))
+		}).attr("opacity", lowopacity).on("mouseover", function(d) {
+			d3.select(this).style('opacity', highopacity);
+		}).on("mouseout", function(d) {
+			d3.select(this).style('opacity', lowopacity);
+		}).append("title")
+		.text(sankeyEdgeTitle);
+	var c = svg.append("g") //node
+		.selectAll(".node").data(d.nodes).enter().append("g").attr("class", "node").attr("transform", function(i) {
+			return "translate(" + i.x + "," + i.y + ")"
+		}).call(d3.behavior.drag().origin(function(i) {
+			return i
+		}).on("dragstart", function() {
+			this.parentNode.appendChild(this)
+		}).on("drag", samkeyOnDragMove));
+	c.append("rect") //node
+		.attr("height", function(i) {
+			return i.dy
+		}).attr("width", sankey.nodeWidth()).style("fill", function(i) {
+			if (i.fill) return i.color = i.fill;
+								else return i.color = sankeyColor(i.name.replace(/ .*/, ""))
+		}).style("stroke", function(i) {
+			return d3.rgb(i.color).darker(2)
+		}).on("mouseover", function(d) {
+			svg.selectAll(".link").filter(function(l) {
+				return l.source == d || l.target == d;
+			}).transition().style('opacity', highopacity);
+		}).on("mouseout", function(d) {
+			svg.selectAll(".link").filter(function(l) {
+				return l.source == d || l.target == d;
+			}).transition().style('opacity', lowopacity);
+		}).on("dblclick", function(d) {
+			svg.selectAll(".link").filter(function(l) {
+				return l.target == d;
+			}).attr("display", function() {
+				if (d3.select(this).attr("display") == "none") return "inline"
+				else return "none"
+			});
+		}).append("title").text(sankeyNodeTitle);
+	c.append("text") //node
+		.attr("x", -6).attr("y", function(i) {
+			return i.dy / 2
+		}).attr("dy", ".35em").attr("text-anchor", "end").attr("font-size","16px")
+		.text(sankeyNodeLabel)
+		.filter(function(i) {
+			return i.x < width / 2
+		}).attr("x", 6 + sankey.nodeWidth()).attr("text-anchor", "start")
+	if (showlinkcount>0) c.append("text") //node
+		.attr("x", -6).attr("y", function(i) {
+			return i.dy / 2 + 20
+		}).attr("dy", ".35em").attr("text-anchor", "end").attr("font-size","16px")
+		.text(function(i) {
+			return "→ "+(i.targetLinks.length)+" | "+(i.sourceLinks.length)+" →";
+		}).filter(function(i) {
+			return i.x < width / 2
+		}).attr("x", 6 + sankey.nodeWidth()).attr("text-anchor", "start")
+	c.append("text") //node
+		.attr("x", function(i) {return -i.dy / 2})
+		.attr("y", function(i) {return i.dx / 2 + 9})
+		.attr("transform", "rotate(270)").attr("text-anchor", "middle").attr("font-size","23px").text(function(i) {
+			if ((i.dy>minnodewidth)&&(labelformat<1)){
+				return sankeyNumberFormat(i.value);
+			}
+		}).attr("fill",function(d){
+			return d3.rgb(d["color"]).brighter(2)
+		}).attr("stroke",function(d){
+			return d3.rgb(d["color"]).darker(2)
+		}).attr("stroke-width","1px");
+
+		svg.selectAll('rect')
+		.on('mouseover', (a, b, c, d, e) => {console.log('mouseover', a, b, c, d, e)})
+		.on('mouseout', (a, b, c, d, e) => {console.log('mouseout', a, b, c, d, e)})
+		.on('mousedown', (a, b, c, d, e) => {console.log('mousedown', a, b, c, d, e)})
+		.on('mouseup', (a) => {
+			dispatch.click({
+				nativeEvent: d3.event,
+				node: a,
+				element: d3.event.srcElement
+			})
+		});
+
+		function samkeyOnDragMove(i) {
+			// if (document.getElementById("ymove").checked) {
+			// 	if (document.getElementById("xmove").checked) {
+			// 		d3.select(this).attr("transform", "translate(" + (i.x = Math.max(0, Math.min(width - i.dx, d3.event.x))) + "," + (i.y = Math.max(0, Math.min(height - i.dy, d3.event.y))) + ")")
+			// 	} else {
+			dragged = true
+			d3.select(this).attr("transform", "translate(" + i.x + "," + (i.y = Math.max(0, Math.min(height - i.dy, d3.event.y))) + ")")
+			// 	}
+			// } else {
+			// 	if (document.getElementById("xmove").checked) {
+			// 		d3.select(this).attr("transform", "translate(" + (i.x = Math.max(0, Math.min(width - i.dx, d3.event.x))) + "," + i.y + ")")
+			// 	}
+			// }
+			sankey.relayout();
+			f.attr("d", path(1)); // TODO: global var f
+			h.attr("d", path(0)); // TODO: global var h
+			e.attr("d", path(2)); // TODO: global var e
+		}
+
+};
+// draw();
+
+function sankeyEdgeTitle(i) {
+	return i.source.name + " → " + i.target.name + "\n" + sankeyNumberFormat(i.value)
+}
+function sankeyNodeTitle(i) {
+	if (i.label) return i.label + "\n" + sankeyNumberFormat(i.value)
+	return i.name + "\n" + sankeyNumberFormat(i.value)
+}
+
+function sankeyNodeLabel(i) {
+	if (labeltextformat < 1) {
+		if (i.label) return (i.label.length > 20) ? i.label.substr(0, 20) + '...' : i.label
+		return i.name;
+	} else {
+		return "";
+	}
+}
+
+	var renderGraph = (htmlNode, data, opts) => {
+		var opts = opts || {}
+		if (!htmlNode) throw "Missing html node";
+		if (!data) throw "Missing data";
+		// console.log('renderGraph data', data)
+
+		htmlNode.append("rect").attr("x",0).attr("y",0).attr("width","100%").attr("height","100%").attr("fill","white")
+		margin = {
+			top: 10,
+			right: 20,
+			bottom: 10,
+			left: 40
+		};
+		width = (opts.width) ? opts.width - margin.left - margin.right : 1020;
+		height = (opts.height) ? opts.height : 500;
+		htmlNode.attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom)
+		svg = htmlNode.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
+
+		change(data);
+
+		return dispatch
+	}
+
+	global.parallelrendering = parallelrendering
+	global.fixedlayout = fixedlayout
+	global.renderGraph = renderGraph
+})(window)

+ 0 - 0
theme/assets/js/scripts.js


+ 86 - 0
theme/assets/js/updateLastRaportProgress.js

@@ -0,0 +1,86 @@
+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('#last-raport-state').length) return;
+
+// 'URL_BI_AUDIT_RESULT' => Router::getRoute('UrlAction_BiAuditGenerate')->getLink(''),
+// 'ID_ARG_BI_AUDIT_RESULT' => 'ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA'
+// index.php?_route=UrlAction_BiAuditGenerate&ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA=102
+
+var IS_STARTED = false
+var DBG_COUNTER = 0;
+
+function updateLastRaportView(respJson) {
+	if (!respJson.body || !respJson.body.ids || !respJson.body.progress) return;
+
+	if (!jQuery('#last-raport-state').length) return;
+
+	if(DBG)console.log('DBG:updateLastRaportView', {respJson: respJson, tblStruct: tblStruct});
+
+	var idx = 0;
+	var respId = respJson.body.ids[idx]
+	var progress = respJson.body.progress[idx]
+	var percent = Math.round(100 * progress)
+	if (DBG_FAKE_ANIM && percent > 0 && percent < 100) percent += (DBG_COUNTER * 10)
+	var status = (respJson.body.statuses[idx]) ? respJson.body.statuses[idx] : ''
+	if (DBG_FAKE_ANIM) status = (percent < 100) ? 'IN_PROGRES' : 'DONE'
+	var statusInfo = (respJson.body.statusesInfo[idx]) ? respJson.body.statusesInfo[idx] : ''
+
+	jQuery('#last-raport-state').get(0).innerHTML = '';
+	var el = jQuery('<span style="display:inline-block; width:140px; text-align:center">' + status + '</span>');
+	jQuery('#last-raport-state').append(el);
+	if ('GENERATED' === status) {
+		var resultLink = URL_BI_AUDIT_RESULT + '&' + ID_ARG_BI_AUDIT_RESULT + '=' + respId;
+		jQuery('#last-raport-state').append('<a style="margin-left:8px; padding:6px 12px; vertical-align:top" class="btn btn-default btn-link" href="'+resultLink+'">Wyniki</a>');
+	}
+	jQuery('#last-raport-state').append('<span style="display:block; font-size:12px; color:#c0c0c0; line-height:16px"> '+statusInfo+' </span>');
+
+	if(DBG)console.log('DBG:updateLastRaportView loop ('+idx+', el)', {el: el, progress: progress, pr: percent });
+	updatePercentView(el, {
+		percent: percent,
+		status: status,
+	})
+}
+
+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 updateLastRaportProgress() {
+	DBG_COUNTER += 1
+	if(DBG)console.log('updateLastRaportProgress ('+DBG_COUNTER+')');
+
+	global.fetch(URL_FETCH_BI_AUDIT_PROGRESS, {
+	  method: 'POST',
+		credentials: 	'same-origin',
+	  body: JSON.stringify({
+	    ids: 'last'
+	  })
+	}).then(function (response) {
+		return response.json()
+	}).then(function (respJson) {
+		updateLastRaportView(respJson)
+		IS_STARTED = false;
+		startUpdateLastRaportProgress()
+	}).catch(function (e) {
+		if(DBG)console.warn('e:', e)
+		IS_STARTED = false
+	})
+
+	IS_STARTED = false
+}
+
+function startUpdateLastRaportProgress() {
+	if (IS_STARTED) return;
+	IS_STARTED = true
+	if(DBG)console.log('START updateLastRaportProgress ...');
+	global.setTimeout(updateLastRaportProgress, 1000)
+}
+
+
+setTimeout(startUpdateLastRaportProgress, 100);

+ 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(3)')
+	// 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(' + (3 + fieldStatusIdx) + ')').toArray() : []
+	var statusInfoNodes = (fieldStatusInfoIdx > 0) ? tblNode.find('> tbody > tr > td:nth-child(' + (3 + 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)

+ 457 - 0
theme/assets/less/buttons.less

@@ -0,0 +1,457 @@
+
+.btn {
+  display: inline-block;
+  padding: 10px 15px;
+  margin-bottom: 0;
+  font-size: 14px;
+  font-weight: normal;
+  line-height: 1.428571429;
+  text-align: center;
+  white-space: nowrap;
+  vertical-align: middle;
+  cursor: pointer;
+  background-image: none;
+  border: 1px solid transparent;
+  border-radius: 4px;
+  -webkit-user-select: none;
+  -moz-user-select: none;
+  -ms-user-select: none;
+  -o-user-select: none;
+  user-select: none;
+}
+
+.btn:focus {
+  outline: thin dotted;
+  outline: 5px auto -webkit-focus-ring-color;
+  outline-offset: -2px;
+}
+
+.btn:hover,
+.btn:focus {
+  color: #333333;
+  text-decoration: none;
+}
+
+.btn:active,
+.btn.active {
+  background-image: none;
+  outline: 0;
+  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
+  box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
+}
+
+.btn.disabled,
+.btn[disabled],
+fieldset[disabled] .btn {
+  pointer-events: none;
+  cursor: not-allowed;
+  opacity: 0.65;
+  filter: alpha(opacity=65);
+  -webkit-box-shadow: none;
+  box-shadow: none;
+}
+
+.btn-default {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+
+.btn-default:hover,
+.btn-default:focus,
+.btn-default:focus,
+.btn-default.active,
+.open .dropdown-toggle.btn-default {
+  color: @brand-primary;
+  background-color: @brand-white;
+  border-color: @brand-primary;
+}
+
+/** pagination */
+ul.tblAjax__footer__toolbar__pagination {
+  list-style-type: none;
+
+  li {
+    display: inline-block;
+  }
+}
+ul.btn-group.tblAjax__footer__toolbar__pagination.smad-pagination  li:not(:nth-child(1)) a,
+ul.btn-group.tblAjax__footer__toolbar__pagination.smad-pagination  li:not(:nth-last-child(1)) a {
+  border-radius: 0;
+}
+ul.btn-group.tblAjax__footer__toolbar__pagination.smad-pagination  li:nth-last-child(1) a {
+  -webkit-border-top-right-radius: 4px;
+  -webkit-border-bottom-right-radius: 4px;
+  -moz-border-radius-topright: 4px;
+  -moz-border-radius-bottomright: 4px;
+  border-top-right-radius: 4px;
+  border-bottom-right-radius: 4px;
+}
+ul.btn-group.tblAjax__footer__toolbar__pagination.smad-pagination  li:nth-child(1) a {
+
+  -webkit-border-top-left-radius: 4px;
+  -webkit-border-bottom-left-radius: 4px;
+  -moz-border-radius-topleft: 4px;
+  -moz-border-radius-bottomleft: 4px;
+  border-top-left-radius: 4px;
+  border-bottom-left-radius: 4px;
+}
+.tblAjax__footer__toolbar__pagination {
+  .btn-default {
+    color: @brand-primary;
+    background-color: @brand-white;
+    border-color: @brand-primary;
+  }
+
+  .btn-default:hover,
+  .btn-default:focus,
+  .btn-default:focus,
+  .btn-default.active,
+  .open .dropdown-toggle.btn-default {
+    color: @brand-white;
+    background-color: @brand-primary;
+    border-color: @brand-primary;
+  }
+
+  .btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
+    border-radius: 0;
+  }
+}
+.footer_pagination_menu_items {
+  display: inline-block;
+}
+.tblAjax__footer__toolbar__info {
+  p {
+    font-size: 12px;
+  }
+}
+/* end pagination*/
+
+.btn-default:active:hover {
+  color: @brand-primary;
+  background-color: @brand-white;
+  border-color: @brand-primary;
+}
+
+
+.btn-default:active,
+.btn-default.active,
+.open .dropdown-toggle.btn-default {
+  color: @brand-primary;
+  background-color: @brand-white;
+  border-color: @brand-primary;
+}
+
+
+.btn-default.disabled,
+.btn-default[disabled],
+fieldset[disabled] .btn-default,
+.btn-default.disabled:hover,
+.btn-default[disabled]:hover,
+fieldset[disabled] .btn-default:hover,
+.btn-default.disabled:focus,
+.btn-default[disabled]:focus,
+fieldset[disabled] .btn-default:focus {
+  color: mix(@brand-white, @brand-primary, 50%);
+  background-color: @brand-white;
+  border-color: mix(@brand-white, @brand-primary, 50%);
+}
+
+.btn-default.disabled:active,
+.btn-default[disabled]:active,
+fieldset[disabled] .btn-default:active,
+.btn-default.disabled.active,
+.btn-default[disabled].active,
+fieldset[disabled] .btn-default.active {
+  color: @brand-primary;
+  background-color: @brand-white;
+  border-color: @brand-primary;
+}
+
+.btn-default .badge {
+  color: @brand-primary!important;
+  background-color: #fff;
+}
+
+.btn-primary {
+  color: @brand-primary;
+  background-color: @brand-white;
+  border-color: @brand-primary;
+}
+
+.btn-primary:hover,
+.btn-primary:focus,
+.btn-primary:active,
+.btn-primary.active,
+.open .dropdown-toggle.btn-primary {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+
+.btn-primary:active:hover {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+
+.btn-primary:active,
+.btn-primary:focus,
+.btn-primary.active,
+.open .dropdown-toggle.btn-primary {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+
+.btn-primary.disabled,
+.btn-primary[disabled],
+fieldset[disabled] .btn-primary,
+.btn-primary.disabled:hover,
+.btn-primary[disabled]:hover,
+fieldset[disabled] .btn-primary:hover,
+.btn-primary.disabled:focus,
+.btn-primary[disabled]:focus,
+fieldset[disabled] .btn-primary:focus,
+.btn-primary.disabled:active,
+.btn-primary[disabled]:active,
+fieldset[disabled] .btn-primary:active,
+.btn-primary.disabled.active,
+.btn-primary[disabled].active,
+fieldset[disabled] .btn-primary.active {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+
+.btn-primary .badge {
+  color: #428bca;
+  background-color: #fff;
+}
+
+.btn-warning {
+  color: @brand-white;
+  background-color: @brand-grey;
+  border-color: @brand-grey;
+}
+
+.btn-warning:hover,
+.btn-warning:focus,
+.btn-warning:active,
+.btn-warning.active,
+.open .dropdown-toggle.btn-warning {
+  color: @brand-text;
+  background-color: @brand-grey;
+  border-color: @brand-grey;
+}
+
+.btn-warning:active:hover {
+  color: @brand-text;
+  background-color: @brand-grey;
+  border-color: @brand-grey;
+}
+
+.btn-warning:active,
+.btn-warning:focus,
+.btn-warning.active,
+.open .dropdown-toggle.btn-warning {
+  color: @brand-text;
+  background-color: @brand-grey;
+  border-color: @brand-grey;
+}
+
+.btn-warning.disabled,
+.btn-warning[disabled],
+fieldset[disabled] .btn-warning,
+.btn-warning.disabled:hover,
+.btn-warning[disabled]:hover,
+fieldset[disabled] .btn-warning:hover,
+.btn-warning.disabled:focus,
+.btn-warning[disabled]:focus,
+fieldset[disabled] .btn-warning:focus,
+.btn-warning.disabled:active,
+.btn-warning[disabled]:active,
+fieldset[disabled] .btn-warning:active,
+.btn-warning.disabled.active,
+.btn-warning[disabled].active,
+fieldset[disabled] .btn-warning.active {
+  color: @brand-text;
+  background-color: @brand-grey;
+  border-color: @brand-grey;
+}
+
+.btn-warning .badge {
+  color: #f0ad4e;
+  background-color: #fff;
+}
+
+.btn-danger {
+  color: #ffffff;
+  background-color: #d9534f;
+  border-color: #d43f3a;
+}
+
+.btn-danger:hover,
+.btn-danger:focus,
+.btn-danger:active,
+.btn-danger.active,
+.open .dropdown-toggle.btn-danger {
+  color: #ffffff;
+  background-color: #d2322d;
+  border-color: #ac2925;
+}
+
+.btn-danger:active:hover {
+  color: #ffffff;
+  background-color: #d2322d;
+  border-color: #ac2925;
+}
+
+.btn-danger:active,
+.btn-danger.active,
+.open .dropdown-toggle.btn-danger {
+  background-image: none;
+}
+
+.btn-danger.disabled,
+.btn-danger[disabled],
+fieldset[disabled] .btn-danger,
+.btn-danger.disabled:hover,
+.btn-danger[disabled]:hover,
+fieldset[disabled] .btn-danger:hover,
+.btn-danger.disabled:focus,
+.btn-danger[disabled]:focus,
+fieldset[disabled] .btn-danger:focus,
+.btn-danger.disabled:active,
+.btn-danger[disabled]:active,
+fieldset[disabled] .btn-danger:active,
+.btn-danger.disabled.active,
+.btn-danger[disabled].active,
+fieldset[disabled] .btn-danger.active {
+  background-color: #d9534f;
+  border-color: #d43f3a;
+}
+
+.btn-danger .badge {
+  color: #d9534f;
+  background-color: #fff;
+}
+
+
+.btn-success {
+  color: @brand-text;
+  background-color: @brand-grey;
+  border-color: @brand-grey;
+}
+
+.btn-success:hover,
+.btn-success:focus,
+.btn-success:active,
+.btn-success.active,
+.open .dropdown-toggle.btn-success {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+
+.btn-success:active:hover {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+
+
+.btn-success:active,
+.btn-success.active,
+.open .dropdown-toggle.btn-success {
+  background-image: none;
+}
+
+.btn-success.disabled,
+.btn-success[disabled],
+fieldset[disabled] .btn-success,
+.btn-success.disabled:hover,
+.btn-success[disabled]:hover,
+fieldset[disabled] .btn-success:hover,
+.btn-success.disabled:focus,
+.btn-success[disabled]:focus,
+fieldset[disabled] .btn-success:focus,
+.btn-success.disabled:active,
+.btn-success[disabled]:active,
+fieldset[disabled] .btn-success:active,
+.btn-success.disabled.active,
+.btn-success[disabled].active,
+fieldset[disabled] .btn-success.active {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+
+.btn-success .badge {
+  color: #5cb85c;
+  background-color: #fff;
+}
+
+
+.btn-info {
+  color: @brand-secondary!important;
+  background-color: @brand-white;
+  border-color: @brand-secondary;
+}
+
+.btn-info:hover,
+.btn-info:focus,
+.btn-info:active,
+.btn-info.active,
+.open .dropdown-toggle.btn-info {
+  color: @brand-white!important;
+  background-color: @brand-secondary;
+  border-color: @brand-secondary;
+}
+
+.btn-info:active:hover {
+  color: @brand-white!important;
+  background-color: @brand-secondary;
+  border-color: @brand-secondary;
+}
+
+.btn-info:active,
+.btn-info.active,
+.open .dropdown-toggle.btn-info {
+  color: @brand-white!important;
+  background-color: @brand-secondary;
+  border-color: @brand-secondary;
+}
+
+.btn-info.disabled,
+.btn-info[disabled],
+fieldset[disabled] .btn-info,
+.btn-info.disabled:hover,
+.btn-info[disabled]:hover,
+fieldset[disabled] .btn-info:hover,
+.btn-info.disabled:focus,
+.btn-info[disabled]:focus,
+fieldset[disabled] .btn-info:focus,
+.btn-info.disabled:active,
+.btn-info[disabled]:active,
+fieldset[disabled] .btn-info:active,
+.btn-info.disabled.active,
+.btn-info[disabled].active,
+fieldset[disabled] .btn-info.active {
+  color: @brand-white!important;
+  background-color: @brand-secondary;
+  border-color: @brand-secondary;
+}
+
+.btn-info .badge {
+  color: #5bc0de;
+  background-color: #fff;
+}
+
+.btn.disabled, .btn[disabled], fieldset[disabled] .btn {
+  cursor: not-allowed;
+  filter: alpha(opacity=65);
+  -webkit-box-shadow: none;
+  box-shadow: none;
+  opacity: .65;
+}

+ 733 - 0
theme/assets/less/styles.less

@@ -0,0 +1,733 @@
+// Variables, Mixins
+@import "variables.less";
+@import "buttons.less";
+
+// html5
+article,
+aside,
+details,
+figcaption,
+figure,
+footer,
+header,
+hgroup,
+nav,
+section,
+summary {
+  display: block;
+}
+
+/* MIX */
+body {
+  margin: 0 0;
+  padding-bottom: 0!important;
+  font-family: @font-primary;
+  font-size: 17px;
+  line-height: 27px;
+  color: @brand-text;
+}
+
+p, ul, li {
+  font-size: 17px;
+  text-align: justify;
+}
+strong {
+  color: @brand-primary;
+}
+
+.link-primary {
+  color: @brand-primary!important;
+  cursor: pointer;
+}
+.font-weight-700 {
+  font-weight: 700;
+}
+
+.padding-0 {
+  padding: 0;
+}
+.padding-lr-0 {
+  padding-left: 0;
+  padding-right: 0;
+}
+.padding-top-bottom-25 {
+ padding-top: 25px;
+ padding-bottom: 25px;
+}
+.padding-bottom-25 {
+  padding-bottom: 25px;
+}
+.pl-20 {
+  padding-left: 20px;
+}
+
+.smad-divider {
+  margin: 20px 0;
+  height: 1px;
+  width: 100%;
+  background-color: @brand-grey;
+}
+
+.smad-line-grey {
+  color: @brand-grey;
+}
+.smad-line-red {
+  color: @brand-primary;
+}
+.text-grey {
+  color: @brand-text-light;
+}
+
+.bg-white {
+  background-color: @brand-white!important;
+}
+
+.btn {
+  padding-top: 10px;
+  padding-bottom: 10px;
+  padding-left: 15px;
+  padding-right: 15px;
+}
+.border-top-grey {
+  border-top: 2px solid @brand-grey;
+}
+.border-bottom-grey {
+  border-bottom: 2px solid @brand-grey;
+}
+
+ul.breadcrumb {
+  background-color: @brand-white;
+  li {
+    a {
+      color: @brand-dark;
+      font-weight: 700;
+
+      &:first-child:before {
+        padding-right: 5px;
+        content: "|";
+        color: @brand-primary;
+      }
+    }
+  }
+}
+
+/* menu hamburger*/
+#hamburger-menu {
+  .smad-menu-title {
+    font-size: 11px;
+    height: 17px;
+    text-align: center;
+    color: @brand-primary;
+    font-weight: bold;
+  }
+
+  float: right;
+  .hamburger-menu-line {
+    width: 35px;
+    height: 3px;
+    background-color: @brand-dark;
+    margin: 6px 0;
+    text-align: right;
+
+  }
+}
+
+
+/** drop down menu */
+#smad-header-section ul.dropdown-menu li{
+    display: block;
+}
+
+
+
+/** Bootstrap */
+.btn:focus,.btn:active {
+  outline: none !important;
+}
+/*.btn-primary {
+  color: @brand-text;
+  background-color: @brand-grey;
+  border-color: @brand-grey;
+}
+.btn-primary.active.focus, .btn-primary.active:focus, .btn-primary.active:hover, .btn-primary:active.focus, .btn-primary:active:focus, .btn-primary:active:hover, .open>.dropdown-toggle.btn-primary.focus, .open>.dropdown-toggle.btn-primary:focus, .open>.dropdown-toggle.btn-primary:hover {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+.btn-primary.active, .btn-primary:active, .btn-primary:hover, .open>.dropdown-toggle.btn-primary {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}*/
+
+/*
+.btn-default {
+  color: @brand-primary;
+  background-color: @brand-white;
+  border-color: @brand-primary;
+}
+
+.btn-default.active.focus, .btn-default.active:focus, .btn-default.active:hover, .btn-default:active.focus, .btn-default:active:focus, .btn-default:active:hover, .open>.dropdown-toggle.btn-default.focus, .open>.dropdown-toggle.btn-default:focus, .open>.dropdown-toggle.btn-default:hover {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+.btn-default.active, .btn-default:active, .btn-default:hover, .open>.dropdown-toggle.btn-default {
+  color: @brand-white;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}*/
+
+
+/*.btn-default-red {
+  color: @brand-white!important;
+  background-color: @brand-primary;
+  border-color: @brand-primary;
+}
+
+.btn-default-red.active.focus, .btn-default-red.active:focus, .btn-default-red.active:hover, .btn-default-red:active.focus, .btn-default-red:active:focus, .btn-default-red:active:hover, .open>.dropdown-toggle.btn-default-red.focus, .open>.dropdown-toggle.btn-default-red:focus, .open>.dropdown-toggle.btn-default-red:hover {
+  color: @brand-primary!important;
+  background-color: @brand-white;
+  border-color: @brand-primary;
+}
+.btn-default-red.active, .btn-default-red:active, .btn-default-red:hover, .open>.dropdown-toggle.btn-default-red {
+  color: @brand-primary!important;
+  background-color: @brand-white;
+  border-color: @brand-primary;
+}*/
+/*
+.btn-grey-border {
+  color: @brand-secondary!important;
+  background-color: @brand-white;
+  border-color: @brand-secondary;
+}
+
+.btn-grey-border.active.focus, .btn-grey-border.active:focus, .btn-grey-border.active:hover, .btn-grey-border:active.focus, .btn-grey-border:active:focus, .btn-grey-border:active:hover, .open>.dropdown-toggle.btn-grey-border.focus, .open>.dropdown-toggle.btn-grey-border:focus, .open>.dropdown-toggle.btn-grey-border:hover {
+  color: @brand-white!important;
+  background-color: @brand-secondary;
+  border-color: @brand-secondary;
+}
+.btn-grey-border.active, .btn-grey-border:active, .btn-grey-border:hover, .open>.dropdown-toggle.btn-grey-border {
+  color: @brand-white!important;
+  background-color: @brand-secondary;
+  border-color: @brand-secondary;
+}*/
+
+/* Select option */
+
+.col-centered {
+  margin: 0 auto;
+  float: none;
+}
+/**Table */
+.table {
+  thead {
+    td {
+      color: @brand-text;
+    }
+  }
+
+  tbody {
+    td {
+      color: @brand-text-light;
+    }
+  }
+}
+
+/** TOP */
+#smad-header-section {
+  padding: 10px 10px;
+  background-color: @brand-grey-light;
+
+  .smad-top-first {
+    margin-left: 4%;
+    padding-top: 20px;
+    border-bottom: 1px solid @brand-primary;
+  }
+
+  .smad-top-second {
+    text-align: right;
+  }
+
+  ul {
+    text-align: right;
+    list-style-type: none;
+
+    li {
+      padding: 0px;
+      display: inline-block;
+
+      .smad-header-title {
+        color: @brand-text-light;
+        font-size: 13px;
+      }
+      .smad-desc {
+        padding-right: 10px;
+        color: @brand-text;
+        font-size: 13px;
+
+        #ProcesMenuLoginDropdownLink {
+          color: @brand-text;
+        }
+      }
+
+    }
+  }
+
+  a.smad-logout {
+    color: @brand-text;
+    font-size: 14px;
+    text-decoration: none;
+
+    &:focus, &:hover {
+      color: @brand-text;
+      text-decoration: none;
+    }
+  }
+}
+
+/** Menu */
+#smad-menu-section {
+
+  .smad-heder-title {
+    color: @brand-text;
+    font-weight: 700;
+  }
+
+  .menu-items {
+    padding-top: 20px;
+    padding-bottom: 20px;
+
+    .menu-item {
+      display: inline-block;
+    }
+    ul {
+      list-style-type: none;
+      display: inline-block;
+
+      li {
+        padding: 5px 7px;
+        display: inline-block;
+      }
+    }
+  }
+
+}
+
+
+/* Menu form */
+#smad-menu-form-section {
+
+  .smad-border-col {
+    border-right: 2px solid @brand-grey;
+
+    @media screen and (max-width : @screen-md ) {
+      border-right: 0;
+      border-bottom: 2px solid @brand-grey;
+    }
+  }
+
+  .menu-items {
+    padding-top: 45px;
+    padding-bottom: 20px;
+
+    .menu-item {
+      padding-top: 25px;
+      padding-bottom: 65px;
+      display: inline-block;
+
+      a {
+        color: @brand-text;
+        text-decoration: none;
+        font-weight: 700;
+
+        &:focus, &:hover {
+          color: @brand-text;
+          text-decoration: none;
+          font-weight: 700;
+        }
+      }
+
+      input {
+        width: 80px;
+      }
+    }
+  }
+
+  .menu-form-input {
+    padding-top: 25px;
+    padding-bottom: 25px;
+
+    .menu-item {
+
+      display: inline-block;
+
+      a {
+        color: @brand-text;
+        text-decoration: none;
+        font-weight: 700;
+
+        &:focus, &:hover {
+          color: @brand-text;
+          text-decoration: none;
+          font-weight: 700;
+        }
+      }
+
+      input {
+        width: 80px;
+      }
+    }
+  }
+
+}
+
+#smad-generate-link {
+  padding: 60px 60px;
+}
+
+/** Footer */
+footer {
+  height: 75px;
+  bottom: 0;
+  width: 100%;
+}
+
+#smad-footer-section {
+  padding: 28px 0 10px 0;
+  background-color: @brand-secondary;
+  text-align: center;
+
+  ul {
+    text-align: center;
+    list-style-type: none;
+
+    li {
+      padding: 0 30px;
+      display: inline-block;
+
+      @media screen and (max-width : @screen-md ) {
+        padding: 0 10px;
+      }
+      @media screen and (max-width : @screen-xs ) {
+        text-align: center;
+        padding: 0 10px;
+        display: block;
+      }
+
+      a {
+        text-decoration: none;
+        color: @brand-text;
+        text-decoration: none;
+
+        &:focus, &:hover {
+          color: @brand-text;
+          text-decoration: underline;
+        }
+      }
+    }
+  }
+}
+
+
+
+/**
+ * Employees
+ */
+#smad-reaport-section {
+
+}
+
+/**
+ * Employees
+ */
+#smad-employees-section, #smad-reaport-section  {
+  /*Form Wizard*/
+  .smad-wizard {
+    margin-top: 0px;
+  }
+  .smad-wizard {
+    border-bottom: solid 1px #e0e0e0;
+    padding: 0 0 10px 0;
+  }
+  .smad-wizard > .smad-wizard-step {
+    padding: 0;
+    position: relative;
+  }
+  .smad-wizard > .smad-wizard-step + .smad-wizard-step {
+  }
+  .smad-wizard > .smad-wizard-step .smad-wizard-stepnum {
+    color: #595959;
+    font-size: 16px;
+    margin-bottom: 5px;
+  }
+  .smad-wizard-info {
+    color: #999;
+    font-size: 14px;
+
+    .step-item {
+
+      a {
+        color: @brand-primary;
+        &:focus, &:hover {
+          color: @brand-primary;
+        }
+      }
+
+      .step-title {
+        color: @brand-text-light;
+      }
+    }
+  }
+
+  .smad-wizard-step.complete {
+    .step-item {
+      color: @brand-primary;
+      a {
+        color: @brand-primary;
+        &:focus, &:hover {
+          color: @brand-primary;
+        }
+      }
+    }
+
+    .step-title {
+      color: @brand-text;
+    }
+  }
+
+  .smad-wizard > .smad-wizard-step > .smad-wizard-dot {
+    position: absolute;
+    width: 30px;
+    height: 30px;
+    display: block;
+    background: none;
+    top: 48px;
+    left: 50%;
+    margin-top: -15px;
+    margin-left: -15px;
+    border-radius: 50%;
+  }
+  .smad-wizard > .smad-wizard-step > .smad-wizard-dot:after {
+    content: ' ';
+    width: 14px;
+    height: 14px;
+    background: @brand-white;
+    border-radius: 50px;
+    position: absolute;
+    top: 8px;
+    left: 8px;
+    border: 2px solid @brand-primary;
+  }
+  .smad-wizard > .smad-wizard-step > .progress {
+    position: relative;
+    border-radius: 0px;
+    height: 3px;
+    box-shadow: none;
+    margin: 20px 0;
+    background: @brand-grey-light;
+  }
+  .smad-wizard > .smad-wizard-step > .progress > .progress-bar {
+    width: 0px;
+    box-shadow: none;
+    background: @brand-grey;
+  }
+  .smad-wizard > .smad-wizard-step.complete > .progress > .progress-bar {
+    width: 100%;
+  }
+  .smad-wizard > .smad-wizard-step.active > .progress > .progress-bar {
+    width: 50%;
+  }
+  .smad-wizard > .smad-wizard-step:first-child.active > .progress > .progress-bar {
+    width: 0%;
+  }
+  .smad-wizard > .smad-wizard-step:last-child.active > .progress > .progress-bar {
+    width: 100%;
+  }
+  .smad-wizard > .smad-wizard-step.disabled > .smad-wizard-dot {
+    background-color: @brand-grey;
+  }
+  .smad-wizard > .smad-wizard-step.disabled > .smad-wizard-dot:after {
+    opacity: 0;
+  }
+  .smad-wizard > .smad-wizard-step:first-child > .progress {
+    left: 50%;
+    width: 50%;
+  }
+  .smad-wizard > .smad-wizard-step:last-child > .progress {
+    width: 50%;
+  }
+  .smad-wizard > .smad-wizard-step.disabled a.smad-wizard-dot {
+    pointer-events: none;
+  }
+  /*END Form Wizard*/
+  /** Form employes */
+  .smad-employees-form-section {
+
+    .menu-items {
+      padding-top: 20px;
+      padding-bottom: 20px;
+
+      .btn {
+        margin: 5px 0;
+      }
+
+      .menu-item {
+        display: inline-block;
+      }
+      ul {
+        list-style-type: none;
+        display: inline-block;
+
+        li {
+          padding: 10px 10px;
+          display: inline-block;
+        }
+      }
+    }
+
+    .form-input {
+      padding-top: 35px;
+      padding-bottom: 25px;
+
+      @media screen and (max-width : @screen-md ) {
+        border-top: 1px solid @brand-grey;
+      }
+
+      .form-item {
+        display: inline-block;
+      }
+      .smad-heder-title {
+        padding-top: 3px;
+        font-size: 14px;
+      }
+    }
+
+    .smad-depth, .smad-depth-kontrahenci {
+      width: 80px;
+      text-align: center;
+    }
+  }
+
+  /** form list employes */
+  .smad-employees-list-head, .smad-form-list-head {
+    padding: 15px 0px;
+    background-color: @brand-grey-light;
+    display: flex;
+
+    .title {
+
+    }
+    .desc {
+      font-size: 15px;
+      line-height: 20px;
+    }
+
+    .menu-items {
+      padding-top: 30px;
+      padding-bottom: 20px;
+      float: right;
+
+      .menu-item {
+        display: inline-block;
+      }
+      ul {
+        list-style-type: none;
+        display: inline-block;
+
+        li {
+          padding: 0 10px;
+          display: inline-block;
+        }
+      }
+    }
+  }
+
+  .smad-employees-bottom-navigation {
+    padding-top: 30px;
+    padding-bottom: 30px;
+  }
+}
+
+/**
+ * Section button generate reaport
+ */
+.smad-generate-reaport {
+  padding: 50px 0;
+
+  .smad-generate-reaport-button {
+    padding: 20px 45px;
+    font-size: 20px;
+    font-weight: 900;
+  }
+  .smad-generate-reaport-info {
+    padding: 10px 0;
+  }
+}
+
+/**
+ * Login
+ */
+#smad-login-section {
+  .main {
+    padding-top: 50px;
+
+    .title-system {
+      padding: 20px 0;
+      color: @brand-text-light;
+      line-height: 20px;
+    }
+
+    .header-title {
+      h4 {
+        padding: 40px 0  30px 0;
+      }
+    }
+
+    .login-button {
+      margin: 20px 0 ;
+      padding: 10px 90px;
+    }
+
+    .first-input {
+      float: right;
+
+      @media (max-width: @screen-md) {
+        float: none;
+      }
+    }
+  }
+}
+
+
+/**
+ * Graph
+ */
+.smad-pracownicy-graph-view {
+  .node rect {
+    cursor: move;
+    fill-opacity: .9;
+    shape-rendering: crispEdges;
+  }
+
+  .node text {
+    pointer-events: none;
+    text-shadow: 0 1px 0 #fff;
+  }
+
+  .link {
+    fill: #000;
+    stroke: #000;
+    stroke-opacity: .2;
+    fill-opacity: .2;
+  }
+
+  .link:hover {
+    stroke-opacity: .5;
+  }
+  #chart {
+    height: calc(100vh - 32px);
+  }
+
+}
+#smad-menu-main{border-bottom: 1px solid #d7142d;}

+ 53 - 0
theme/assets/less/variables.less

@@ -0,0 +1,53 @@
+// Google Fonts
+@import url("https://fonts.googleapis.com/css?family=Roboto:400,500,500i,700");
+
+@font-primary: 'Roboto', sans-serif;
+
+@brand-primary: #d7142d;
+@brand-secondary: #a9a9a9;
+
+@brand-white: #fff;
+@brand-grey: @brand-secondary;
+@brand-grey-light: #efefef;
+@brand-dark: #000000;
+
+@brand-error: #ff8585;
+@brand-success: #69b705;
+@brand-link: @brand-secondary;
+@brand-link-active: @brand-primary;
+@brand-link-text: @brand-dark;
+@brand-link-text-active: @brand-white;
+@brand-text: @brand-dark;
+@brand-text-light: #b1b1b1;
+
+
+
+// Extra small screen / phone
+//** Deprecated `@screen-xs` as of v3.0.1
+@screen-xs:                  480px;
+@screen-xxs:                  415px;
+//** Deprecated `@screen-xs-min` as of v3.2.0
+@screen-xs-min:              @screen-xs;
+//** Deprecated `@screen-phone` as of v3.0.1
+@screen-phone:               @screen-xs-min;
+
+// Small screen / tablet
+//** Deprecated `@screen-sm` as of v3.0.1
+@screen-sm:                  768px;
+@screen-sm-min:              @screen-sm;
+//** Deprecated `@screen-tablet` as of v3.0.1
+@screen-tablet:              @screen-sm-min;
+
+// Medium screen / desktop
+//** Deprecated `@screen-md` as of v3.0.1
+@screen-md:                  992px;
+@screen-md-min:              @screen-md;
+//** Deprecated `@screen-desktop` as of v3.0.1
+@screen-desktop:             @screen-md-min;
+
+// Large screen / wide desktop
+//** Deprecated `@screen-lg` as of v3.0.1
+@screen-lg:                  1200px;
+@screen-lg-min:              @screen-lg;
+//** Deprecated `@screen-lg-desktop` as of v3.0.1
+@screen-lg-desktop:          @screen-lg-min;

+ 22 - 0
theme/view/footer.php

@@ -0,0 +1,22 @@
+<?php
+  if (!User::logged()) {
+    return;
+  }
+?>
+<footer>
+ <div id="smad-footer-section" class="container-fluid padding-0">
+	 <div class="container">
+		 <div class="row">
+			  <div class="col-lg-12">
+					<ul class="menu-bottom">
+						<li><a href="index.php?_route=UrlAction_Anton1&_task=about" title="O Programie">O Programie</a></li>
+            <li><a href="index.php?_route=UrlAction_Anton1&_task=training" title="Szkolenia">Szkolenia</a></li>
+            <li><a href="index.php?_route=UrlAction_Anton1&_task=offer" title="Szkolenia">Oferta</a></li>
+						<li><a href="index.php?_route=UrlAction_Anton1&_task=helpForm" title="Pomoc">Pomoc</a></li>
+            <li><a href="index.php?_route=ViewTableAjax&namespace=default_db/QUALITY_NOTICES#CREATE" title="Zgł. błędów." class="btn btn-success">Zgł. błędów.</a>
+					</ul>
+				</div>
+			</div>
+		</div>
+	</div>
+</footer>

+ 212 - 0
theme/view/home-old.php

@@ -0,0 +1,212 @@
+<!-- start: home -->
+<!--
+<ul class="nav nav-tabs" style="margin-bottom: 20px">
+  <li class="nav-item">
+    <a id="oip" class="nav-link active" href="#">OSOBY I PODMIOTY</a>
+  </li>
+  <li class="nav-item">
+    <a id="obz" class="nav-link" href="#">OPER. BAZA ZGŁOSZEŃ</a>
+  </li>
+</ul>
+-->
+<div id="smad-page-home" class="container-fluid">
+    <div>
+        <div>
+            <div id="smad-menu-form-section">
+              <div id="OIP">
+                <div class="col-md-6 padding-lr-0 smad-border-col">
+                    <div class="menu-items text-center">
+                        <div class="menu-item">
+                            <a href="index.php?_route=UrlAction_Anton1#PRACOWNICY" title="Pracownicy">
+                                <div>Pracownicy</div>
+                                <img src="<?= $this->asset("assets/images/button-red.png"); ?>"
+                                  alt="Pracownicy"
+                                  onmouseover="this.src='<?= $this->asset("assets/images/button-red-border.png"); ?>'"
+                                  onmouseout="this.src='<?= $this->asset("assets/images/button-red.png"); ?>'" />
+                            </a>
+                        </div>
+                    </div>
+                </div>
+                <div class="col-md-6 padding-lr-0">
+                    <div class="menu-items text-center">
+                        <div class="menu-item">
+                            <a href="index.php?_route=UrlAction_Anton1#KONTRAHENCI" title="Kontrahenci">
+                                <div>Kontrahenci</div>
+                                <img src="<?= $this->asset("assets/images/button-red.png"); ?>"
+                                  alt="Kontrahenci"
+                                  onmouseover="this.src='<?= $this->asset("assets/images/button-red-border.png"); ?>'"
+                                  onmouseout="this.src='<?= $this->asset("assets/images/button-red.png"); ?>'" />
+                            </a>
+                        </div>
+                    </div>
+                </div>
+                </div>
+                <div id="OBZ" style="display:none">
+                    <div id="smad-menu-form-section">
+                        <div class="col-md-12 padding-lr-0 smad-border-col">
+                            <div class="menu-items text-center">
+                                <div class="container-fluid">
+                                    <ul class="breadcrumb">
+                                      <li>
+                                        <a href="#" onclick="">Operacyjna baza zgłoszeń</a>
+                                      </li>
+                                      <li>
+                                        <a href="index.php?_route=UrlAction_Anton1#KONTRAHENCI">
+                                          <span class="glyphicon glyphicon-plus"></span>
+                                          Dodaj nowy rekord
+                                        </a>
+                                      </li>
+                                    </ul>
+                                    <div class="padding-0 smad-employees-obz-head" style="background-color:lightgrey;">
+                                      <div class "col-md-6">
+                                        <h2 class="title" style="padding: 30px"> Operacyjna baza zgłoszeń</h2>
+                                      </div>
+                                      <div class="container-fluid">
+                                        <div class="table-responsive padding-0" id="smad-table-obz">
+                                          <table class="table table-responsive table-bordered table-hover table-striped" height="5">
+                                            <thead>
+                                            </thead>
+                                          </table>
+                                        </div>
+                                      </div>
+                                    </div>
+
+                                </div>
+                            </div>
+                        </div>
+                      </div>
+                    </div>
+                <div class="col-md-12 border-top-grey border-bottom-grey">
+                    <div class="menu-form-input text-center">
+                        <div class="menu-item smad-heder-title">głębokość powiązań:</div>
+                        <div class="menu-item">
+                            <input type="text" class="form-control smad-depth" placeholder="1-16" value="6" />
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>
+
+<div id="smad-generate-link" class="container-fluid">
+    <div>
+        <div class="text-center">
+          <?php //todo: ukrycie przycisku generownia raportów powiazan ?>
+          <!--  <a href="#" title="GENERUJ RAPORT POWIĄZAŃ" class="btn btn-primary font-weight-700">GENERUJ RAPORT POWIĄZAŃ</a> -->
+        </div>
+    </div>
+</div>
+
+<script type="text/javascript">
+
+if (localStorage.getItem("Anton1.biAuditForm.depth") === null) {
+  localStorage.setItem('Anton1.biAuditForm.depth', 6);
+}
+
+$(document).ready(function() {
+    clearBIAuditFormLocalStorage();
+    loadCurrentDepthInInput('.smad-depth');
+    updateLocalStorageBiAuditDepth('.smad-depth');
+    setItemLocalStorage('Anton1.biAuditForm.smadReaportTitle', 'Nazwa raportu');
+    $("#oip").click(function(){
+      $("#OIP").show();
+      $("#OBZ").hide();
+    });
+    $("#obz").click(function(){
+      $("#OBZ").show();
+      $("#OIP").hide();
+    });
+});
+
+/**
+ * Load data default title reaport in storage
+ */
+function loadCurrentReaportTitleInInput(idInput) {
+  var reaportTitleValue = getItemLocalStorage("Anton1.biAuditForm.smadReaportTitle");
+
+  if ( getItemLocalStorage('Anton1.biAuditForm.smadReaportTitle') === null ) {
+    reaportTitleValue = setItemLocalStorage('Anton1.biAuditForm.smadReaportTitle', 'Nazwa raportu');
+  }
+
+  $(idInput).val(function() {
+     return reaportTitleValue;
+  });
+}
+
+/**
+ * Load data default depth in storage
+ */
+function loadCurrentDepthInInput(idInput) {
+  var depthValue = getItemLocalStorage("Anton1.biAuditForm.depth");
+
+  if ( getItemLocalStorage('Anton1.biAuditForm.depth') === null ) {
+    depthValue = setItemLocalStorage('Anton1.biAuditForm.depth', 6);
+  }
+
+  $(idInput).val(function() {
+     return depthValue;
+  });
+}
+
+/**
+ * Update data default depth in storage
+ */
+function updateLocalStorageBiAuditDepth(idInput) {
+  $(idInput).keyup(function() {
+    delayUpdate(function(){
+      var newValue = $(idInput).val();
+      var responseValue = validateValueDepth(parseInt(newValue));
+      setItemLocalStorage('Anton1.biAuditForm.depth', responseValue);
+      loadCurrentDepthInInput('.smad-depth');
+    }, 1000 );
+  });
+}
+
+function validateValueDepth(newValue) {
+  var value = null;
+  value = newValue;
+
+  if (parseInt(newValue) < 0) {
+      value = 1;
+  }
+
+  if (parseInt(newValue) > 16) {
+    value = 16;
+  }
+
+  return value;
+}
+
+
+var delayUpdate = (function() {
+  var timer = 0;
+  return function(callback, ms) {
+  clearTimeout (timer);
+  timer = setTimeout(callback, ms);
+ };
+})();
+
+// Local storage
+function setItemLocalStorage(key, array) {
+	localStorage.setItem(key, JSON.stringify(array));
+}
+function getItemLocalStorage(key) {
+	var retrievedData = localStorage.getItem(key);
+	var response = JSON.parse(retrievedData);
+
+	return response;
+}
+
+function clearBIAuditFormLocalStorage() {
+  var arrayValue = [];
+  setItemLocalStorage('Anton1.biAuditForm.pracownicyIds', arrayValue);
+  setItemLocalStorage('Anton1.biAuditForm.kontrahenciIds', arrayValue);
+  setItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup', 0);
+  setItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup', 0);
+  setItemLocalStorage('Anton1.biAuditForm.analizaOnlyTargets', 'y');
+
+}
+window.delayUpdate = delayUpdate;
+</script>
+<!-- end:home -->

+ 38 - 0
theme/view/home.php

@@ -0,0 +1,38 @@
+<div id="smad-page-home" class="container-fluid">
+    <a class="btn btn-primary" id="p5-anton1-btn-new-report" href="index.php?_route=UrlAction_Anton1#PRACOWNICY" title="Nowy raport">
+        <div>NOWY RAPORT</div>
+        <img class="p5-anton1-btn-new-report__img_default" src="<?= $this->asset("assets/images/button-red.png"); ?>"/>
+        <img class="p5-anton1-btn-new-report__img_hover" src="<?= $this->asset("assets/images/button-red-border.png"); ?>"/>
+    </a>
+</div>
+<style type="text/css">
+#smad-page-home { padding-bottom:128px; padding-top:128px; text-align:center }
+
+#p5-anton1-btn-new-report { padding: 18px 110px; font-size: 18px; font-weight: 900; border-width:2px; border-color:#d7142d }
+#p5-anton1-btn-new-report div { padding-bottom:8px; font-size:24px }
+#p5-anton1-btn-new-report,
+#p5-anton1-btn-new-report div { background-color:#fff; color:#d7142d }
+/* #p5-anton1-btn-new-report div { background-color:#d7142d; color:#fff; } */
+#p5-anton1-btn-new-report .p5-anton1-btn-new-report__img_default { display:inline }
+#p5-anton1-btn-new-report .p5-anton1-btn-new-report__img_hover { display:none }
+#p5-anton1-btn-new-report:hover,
+#p5-anton1-btn-new-report:hover div { background-color:#fff; color:#d7142d }
+#p5-anton1-btn-new-report:hover .p5-anton1-btn-new-report__img_default { display:none }
+#p5-anton1-btn-new-report:hover .p5-anton1-btn-new-report__img_hover { display:inline }
+</style>
+
+<?= UI::h('script', ['src'=>"static/vendor.js?v=71baa97d", 'type'=>"text/javascript"]); ?>
+<?php Router::getRoute('UrlAction_Anton1')->viewIncludeStoreJs($storeName = 'anton1RaportStore'); ?>
+<script type="text/javascript">
+var globalRaportStore;
+$(document).ready(function() {
+  if (!window['anton1RaportStore']) throw "Missing store";
+  var globalRaportStore = window['anton1RaportStore'];
+  globalRaportStore.dispatch({ type: 'CLEAR_ALL' });
+  <?php
+  // var unsubscribe = globalRaportStore.subscribe(function () {
+  //   var state = globalRaportStore.getState();
+  // })
+  ?>
+});
+</script>

+ 75 - 0
theme/view/login.php

@@ -0,0 +1,75 @@
+
+<div id="smad-login-section" class="container-fluid">
+    <div class="container">
+        <div class="row">
+
+            <div class="main">
+                <div class="text-center">
+                    <a href="/" title="AUTONOMICZNE LABORATORIUM ANALITYCZNE"><img src="<?= $this->asset("assets/images/logo-anton1-big.png"); ?>" alt="AUTONOMICZNE LABORATORIUM ANALITYCZNE" /></a>
+                    <div class="title-system">
+                        AUTONOMICZNE <br/>
+                        LABORATORIUM ANALITYCZNE
+                    </div>
+                </div>
+
+                <div class="smad-form-login">
+                    <div class="header-title text-center">
+                        <header>
+                            <h4>ZALOGUJĘ SIĘ</h4>
+                        </header>
+                    </div>
+
+										<form name="LOGIN" action="" method="post" class="form-horizontal" role="form text-center" >
+                        <div class="col-sm-6 col-lg-6">
+                            <div class="form-group col-md-8 col-lg-8 first-input">
+                                <input type="text" name="ADM_ACCOUNT" value="" id="username" class="form-control" placeholder="e-mail">
+                            </div>
+                        </div>
+                        <div class="col-sm-6 col-lg-6">
+                            <div class="form-group col-md-8 col-lg-8 ">
+															<input type="password" name="ADM_PASSWD" class="form-control" placeholder="password">
+                            </div>
+                        </div>
+												<?php if (!empty($errors)) : ?>
+													<div class="form-group">
+														<div class="col-sm-9">
+															<div class="alert alert-danger"><?php echo implode('<br>', $errors); ?></div>
+														</div>
+													</div>
+												<?php endif; ?>
+                        <div class="col-sm-12 col-md-12 col-lg-12 text-center form-group">
+														<input name="LOGIN" type="SUBMIT" value="LOGIN" class="btn btn btn-primary login-button">
+                        </div>
+                        <!-- <div class="col-sm-12 col-md-12 col-lg-12 text-center">
+                            <a href="/" class="text-grey" title="forgot password?">forgot password?</a>
+                        </div> -->
+                    </form>
+                </div>
+                <div class="smad-form-forgot-pass" style="display: none;">
+                    <form role="form text-center">
+                        <div class="col-sm-12 col-lg-12 text-center">
+                            <div class="form-group col-md-6 col-lg-5 col-centered  ">
+                                <input type="text" class="form-control" placeholder="e-mail" id="inputUsernameEmailForgotPass">
+                            </div>
+                        </div>
+                        <div class="col-sm-12 col-md-12 col-lg-12 text-center">
+                            <button type="submit" class="btn btn btn-default login-button">
+                                WYŚLIJ
+                            </button>
+                        </div>
+                        <div class="col-sm-12 col-md-12 col-lg-12 text-center">
+                            <a href="index.php" class="text-grey" title="Zaloguj">zaloguj</a>
+                        </div>
+                    </form>
+                </div>
+            </div>
+        </div>
+    </div>
+    <!-- end sm-page -->
+</div>
+<!-- end:sm-wrapper -->
+<script>
+	jQuery(document).ready(function(){
+		document.getElementById('username').focus();
+	});
+</script>

+ 41 - 0
theme/view/logout.php

@@ -0,0 +1,41 @@
+
+
+ <div id="smad-login-section" class="container-fluid">
+    <div class="container">
+        <div class="row">
+
+            <div class="main">
+                <div class="text-center">
+                    <a href="/" title="AUTONOMICZNE LABORATORIUM ANALITYCZNE"><img src="<?= $this->asset("assets/images/logo-anton1-big.png"); ?>" alt="AUTONOMICZNE LABORATORIUM ANALITYCZNE" /></a>
+                    <div class="title-system">
+                        AUTONOMICZNE <br/>
+                        LABORATORIUM ANALITYCZNE
+                    </div>
+                </div>
+
+                <div class="smad-form-forgot-pass text-center">
+                    <?php if (!empty($errors)) : ?>
+                			<?php foreach ($errors as $errMsg) : ?>
+                				<div class="alert alert-danger" style="max-width: 500px; margin: 12px auto; text-align: center"><?php echo $errMsg; ?></div>
+                			<?php endforeach; ?>
+                		<?php else : ?>
+                			<div class="alert alert-info" style="max-width: 500px; margin: 12px auto; text-align: center">
+                				Zostałeś wylogowany
+                			</div>
+                		<?php endif; ?>
+                    <div style="padding:24px auto; text-align:center">
+                      <a  class="btn btn-primary" href="index.php"> zaloguj się </a>
+                    </div>
+                </div>
+            </div>
+
+						<script>
+							jQuery(document).ready(function(){
+								document.getElementById('username').focus();
+							});
+						</script>
+        </div>
+    </div>
+    <!-- end sm-page -->
+</div>
+<!-- end:sm-wrapper -->

+ 251 - 0
theme/view/top.php

@@ -0,0 +1,251 @@
+<div id="smad-header-section" class="container-fluid">
+	<div class="row">
+		<div class="col-xs-12 col-sm-2 col-md-2 col-lg-1 brand-logo">
+			<a href="./" title=""><img src="<?= $this->asset("assets/images/logo-anton1.png"); ?>" alt="Anton1" /></a>
+		</div>
+		<div class="col-xs-12 col-sm-10 col-md-10 col-lg-11">
+			<div class="smad-top-first">
+				<ul>
+					<li><div class="smad-header-title">zalogowany jako:</div></li>
+					<li><div class="smad-desc">
+
+						<div class="btn-group">
+							<button id="ProcesMenuLoginDropdownLink" type="button" class="btn btn-link dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><?php echo User::getFullName(); ?> <span class="caret"></span></button>
+							<ul class="dropdown-menu pull-right smad-top-drop-down-menu" role="menu">
+																<li><a href="/webcal" target="_blank"><i class="glyphicon glyphicon-calendar"></i> Kalendarz</a></li>
+																		<li>
+											<a href="/webmail">
+												<form action="https://<?= V::get('HTTP_HOST', '', $_SERVER); ?>/webmail/loginFromSE.php" method="post" target="_blank">
+													<input type="hidden" name="_timezone" value="Europe/Berlin">
+													<input type="hidden" name="_token" value="">
+													<input type="hidden" name="_action" value="login">
+													<input type="hidden" name="_task" value="login">
+													<input type="hidden" name="_url" value="">
+													<input type="hidden" name="_user" value="diradmin">
+													<input type="hidden" name="_pass" value="CP6uSYikF/GWFeRPKFHYsA==">
+													<input type="hidden" name="EMAIL_IMAP_IMPORT_USERNAME" value="">
+													<input type="hidden" name="EMAIL_IMAP_IMPORT_HOST" value="">
+													<input type="hidden" name="EMAIL_IMAP_IMPORT_PASSWD_HASH" value="">
+													<input type="hidden" name="loginFromSE" value="1">
+													<!-- <input type="submit" class="btn" value="P"> -->
+													<button type="submit" class="btn btn-link" style="width:100%;padding:0;text-align:left;color:#333;"><i class="glyphicon glyphicon-envelope"></i> Poczta</button>
+												</form>
+											</a>
+										</li>
+																	<li><a href="/changepassword" target="_blank"><i class="glyphicon glyphicon-lock"></i> Zmień hasło</a></li>
+									<li><a href="/profilemanager" target="_blank"><i class="glyphicon glyphicon-user"></i> Apple Profile Manager</a></li>
+									<li class="divider"></li>
+
+								<li><a href="procesy5.php?task=USER" title="diradmin"><i class="glyphicon glyphicon-user"></i> Profil</a></li>
+								<li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=UrlAction_Calendar"><i class="glyphicon glyphicon-calendar"></i> Grafik pracy</a></li>
+								<li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=UserMsgs" title="Wiadomości systemowe"><i class="glyphicon glyphicon-envelope"></i> Wiadomości</a></li>
+								<li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=Notify" title="Powiadomienia"><i class="glyphicon glyphicon-bell"></i> Powiadomienia</a></li>
+								<li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=Users&amp;_task=reloadPerms" title="Przeładuj uprawnienia"><i class="glyphicon glyphicon-refresh"></i> Przeładuj uprawnienia</a></li>
+<!--
+<?php if(0) : ?>
+								<li class="divider"></li>
+								<li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=Status" title="Status systemu"><i class="glyphicon glyphicon-cog"></i> Status systemu</a></li>
+								<li><p class="text-muted" style="padding:3px 20px;"><nobr>Pokaż testy pracownika:</nobr></p>
+									<form action="<?php echo Request::getPathUri(); ?>index.php" method="POST">
+										<input type="hidden" name="FUNCTION_INIT" value="MENU_SELECT_PROCES">
+										<input type="hidden" name="_action" value="showMyTests">
+										<div class="typepsecial"><select id="ts-_user_id" placeholder="Szukaj..." name="_user_id" tabindex="-1" class="selectized" style="display: none;"><option value="" selected="selected"></option></select><div class="selectize-control single"><div class="selectize-input items not-full"><input type="text" autocomplete="off" tabindex="" placeholder="Szukaj..." style="width: 67px; opacity: 1; position: relative; left: 0px;"></div><div class="selectize-dropdown single" style="display: none;"><div class="selectize-dropdown-content"></div></div></div></div><script>
+						jQuery(document).ready(function(){
+							var fldNode=jQuery('#_user_id'), tsNode=jQuery('#ts-_user_id');
+							if (!fldNode && !tsNode) {
+								return;
+							}
+
+							fldNode.attr('name', '');
+							fldNode.hide();
+							if (fldNode.parent().hasClass('show-last-value')) {
+								fldNode.parent().hide();
+							}
+							tsNode.attr('name', '_user_id');
+							tsNode.attr('tabindex', fldNode.attr('tabindex'));
+
+
+							tsNode.selectize({
+								theme: 'typespecial',
+								valueField: 'id',
+								labelField: 'id',
+								searchField: 'name',
+								sortField: 'name',
+								create: false,
+								delimiter: ';',
+								dataAttr: 'typespecial',
+								preload: false,
+								options: null,
+								render: {
+									item: function(item, escape) {
+										//console.log('item', item);
+										//var name = formatName(item);
+										return '<div>' +
+											'<span class="name">' + escape(item.name || item.id) + '</span>' +
+										'</div>';
+									},
+									option: function(item, escape) {
+						//console.log('--- render.option item(',item,') this:',this);
+										return '<div>' +
+											'<span class="title">' +
+												escape(item.name || item.id) +
+											'</span>' +
+										'</div>';
+									}
+								},
+								onItemAdd: function(value, item) {// Invoked when an item is selected.
+									var curSel = this.options[value] || null, fieldExport;
+						//console.log('--- onItemAdd val(',value,'/',item.data('name'),'/',item,') this:curSel:',curSel);
+									if (curSel && curSel.exports) {
+										for (var i in curSel.exports) {
+											fieldExport = jQuery('#ts-f' + i);
+											if (fieldExport.length) {
+						//console.log('--- onItemAdd fieldExport.selectize(',fieldExport.selectize,')', fieldExport);
+												if (fieldExport.get(0).selectize) {
+													fieldExport.get(0).selectize.addOption({id:curSel.exports[i], name:curSel.exports[i]});
+													fieldExport.get(0).selectize.setValue(curSel.exports[i]);
+												} else {
+													//jQuery('#f' + i).val(curSel.exports[i]);
+												}
+											} else {
+						//console.log('--- onItemAdd jQuery(#f' + i + ').val(', curSel.exports[i], '): fieldExport.is(input:',fieldExport.is('input'),'/select:',fieldExport.is('select'),')', fieldExport);
+												fieldExport = jQuery('#f' + i);
+												if (fieldExport.is('input')) {
+													jQuery('#f' + i).val(curSel.exports[i]);
+												} else if (fieldExport.is('select')) {
+													//TODO: add option and select //jQuery('#f' + i).val(curSel.exports[i]);
+												}
+											}
+										}
+									}
+								},
+								score: function(search) {
+									var score = this.getScoreFunction(search);
+									return function(item) {
+										//console.log('score:item:', item, ', score:', score(item));
+										if (search && search == item.id) {
+											return 1;
+										} else {
+											return score(item);// score(item) * (1 + Math.min(item.watchers / 100, 1));
+										}
+									};
+								},
+								load: function(query, callback) {
+									if (!query.length) return callback();
+									$.ajax({
+										url: 'index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=TYPESPECIAL&fld=_user_id',
+										data: 'q=' + encodeURIComponent(query),
+										type: 'POST',
+										error: function() {
+											callback();
+										},
+										success: function(res) {
+											for (var i in res) {
+												if (!res[i].name || res[i].id != res[i].name) {
+													res[i].name = res[i].id + ': ' + res[i].name;
+												}
+											}
+											callback(res);
+										}
+									});
+								}
+							});
+
+						});
+		</script><input class="btn btn-xs btn-warning" type="submit" value="Wybierz">
+<?php endif; ?>
+-->
+		<script>
+						jQuery(document).ready(function() {
+							jQuery('#ProcesMenuLoginDropdownLink')
+								.next('.dropdown-menu')
+								.find('.selectize-input')
+								.on('click', function(e) {
+									return false;
+								});
+							jQuery('#ProcesMenuLoginDropdownLink').on('click', function(e) {
+								setTimeout(function(){
+									jQuery('#ts-_user_id')
+										.next('.selectize-control')
+										.find('input:first')
+										.focus();
+								}, 200);
+							});
+						});
+											</script>
+										</form>
+									</li>
+									<li class="divider"></li>
+									<li><a href="<?php echo Request::getPathUri(); ?>index.php?LOGIN=LOGOUT"><i class="glyphicon glyphicon-off"></i> Wyloguj</a></li>
+				</ul>
+			</div>
+
+
+					</div></li>
+					<li> <span class="smad-line-grey">|</span>	<a href="<?php echo Request::getPathUri(); ?>index.php?LOGIN=LOGOUT" title="Wyloguj" class="smad-logout"><img src="<?= $this->asset("assets/images/logout.png"); ?>" alt="Wyloguj" /> Wyloguj</a></li>
+				</ul>
+				</div>
+			<div class="smad-top-second">
+				 <ul>
+					 <li><div class="smad-header-title">koniec sesji za:</div></li>
+					 <li><div class="smad-desc"><code id="session-timer" style="padding:2px 5px;font-weight:normal;color:#000;" title="Czas sesji">52:40</code></div></li>
+				 </ul>
+			</div>
+		</div>
+	</div>
+</div>
+<!-- end:top -->
+<!--  start:menu -->
+<div id="smad-menu-main" class="container-fluid">
+    <div>
+        <div>
+            <div id="smad-menu-section">
+                <div class="col-md-6 padding-lr-0">
+                    <div class="menu-items">
+                        <div class="smad-heder-title menu-item"><span class="smad-line-red">|</span> RAPORTY</div>
+                        <div class="menu-item">
+                            <ul>
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA" title="zobacz raporty" class="btn btn-success btn-xs">zobacz raporty</a></li>
+	                            <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_operational_raport_note/BI_audit_operational_raport_note" title="Baza zgłoszeń operacyjnych i notatek" class="btn btn-success btn-xs">Operac. Baza zgł.</a></li>
+	                            <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=Menu" title="Menu silnika procesy5" class="btn btn-success btn-xs">Menu</a></li>
+                            </ul>
+                        </div>
+                        <br><div class="smad-heder-title menu-item" style="vertical-align:top"><span class="smad-line-red">|</span> OSTATNI RAPORT:</div>
+                        <div class="menu-item" id="last-raport-state"></div>
+                    </div>
+                </div>
+                <div class="col-md-6 padding-lr-0">
+                    <div class="menu-items">
+                        <div class="menu-item smad-heder-title"><span class="smad-line-red">|</span> BAZY DANYCH</div>
+                        <div class="menu-item">
+                            <ul style="padding:0">
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_KRS/BI_audit_KRS" title="KRS - Firmy" class="btn btn-success btn-xs">KRS</a></li>
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_KRS_person/BI_audit_KRS_person" title="KRS - Osoby" class="btn btn-success btn-xs">KRS/p</a></li>
+
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_MSIG/BI_audit_MSIG" title="MSIG - Firmy" class="btn btn-success btn-xs">MSIG</a></li>
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_MSIG_person/BI_audit_MSIG_person" title="KRS - Osoby" class="btn btn-success btn-xs">MSIG/p</a></li>
+
+
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_taxpayer/BI_audit_taxpayer" title="VAT - Aktywni płatnicy" class="btn btn-success btn-xs">VATp</a></li>
+
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_CEIDG/BI_audit_CEIDG" title="CIDG" class="btn btn-success btn-xs">CEIDG</a></li>
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_ENERGA_RUM_UMOWY/BI_audit_ENERGA_RUM_UMOWY" title="RUM Umowy" class="btn btn-success btn-xs">RUM/u</a></li>
+
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI" title="RUM Kontrahenci" class="btn btn-success btn-xs">RUM/k</a></li>
+
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_ENERGA_FAKTURY/BI_audit_ENERGA_FAKTURY" title="Faktury - do imoportowania" class="btn btn-success btn-xs">Faktury</a></li>
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=UrlAction_Anton1#PRACOWNICY" title="Pracownicy" class="btn btn-success btn-xs">Pracownicy</a></li>
+                                <li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=UrlAction_Anton1#KONTRAHENCI" title="Kontrahenci" class="btn btn-success btn-xs">Kontrahenci</a></li>
+
+																<li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_BENFORD/BI_audit_BENFORD" title="RUM Umowy" class="btn btn-success btn-xs">Benford</a></li>
+																<li><a href="<?php echo Request::getPathUri(); ?>index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_VALIDATE/BI_audit_VALIDATE" title="RUM Umowy" class="btn btn-success btn-xs">Analiza błędów</a></li>
+                                <!--<li><a href="#" title="KSIĘGOWOŚĆ" class="btn btn-success">KSIĘGOWOŚĆ</a></li> -->
+                            </ul>
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>
+<!-- end:menu -->

+ 3352 - 0
tools/Anton1.php

@@ -0,0 +1,3352 @@
+<?php
+
+Lib::loadClass('RouteToolBase');
+Lib::loadClass('UI');
+Lib::loadClass('Response');
+Lib::loadClass('Request');
+
+// index.php?_route=UrlAction_Anton1  - uruchamia defaultAction
+class RouteTool_Anton1 extends RouteToolBase {
+
+public static $helpEmailTo = 'biuro@bialnet.com.pl'; // todo:email na który zostanie wysłane zapytanie z formularza POMOCY
+
+	public static $FIELD_LIST_PRACOWNICY = [
+		'ID',
+		'imiona',
+		'nazwisko',
+		'nip',
+		'pesel',
+		'regon',
+		'source',
+		'jednostka_organizacyjna',
+		'A_STATUS',
+		'A_STATUS_INFO',
+		'L_APPOITMENT_USER',
+		// 'Adresy' // 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy/*'
+	];
+	public static $FIELD_LIST_KONTRAHENCI = [
+		'ID',
+		'Nazwa_grupy_kapitalowej',
+		'Pelna_nazwa_kontrahenta',
+		'Numer_kontrahenta',
+		'Skrocona_Nazwa_Kontrahenta',
+		'Typ_kontrahenta',
+		'NIP',
+		'KRS',
+		'REGON',
+		'PESEL',
+		'Forma_prawna_dzialalnosci',
+		'Ulica',
+		'Numer_budynku',
+		'Numer_mieszkania_lokalu',
+		'Miejscowosc',
+		'Kod_pocztowy',
+		'Kraj',
+		'Telefon',
+		'Fax',
+		'Mail',
+		'A_ADM_COMPANY',
+		'A_CLASSIFIED',
+		'Dodano',
+		'Podmiot_dominujacy',
+		'Tytul_dokumentu',
+		'ownCompany',
+		'uwagi',
+	];
+
+	function aboutAction() { $this->sendPageView('page-about.view.php'); }
+	function trainingAction() { $this->sendPageView('page-training.view.php'); }
+	function offerAction() { $this->sendPageView('page-offer.view.php'); }
+	function helpFormAction() { $this->sendPageView('page-help.view.php', [ $this, '_helpFormBeforeViewTrigger' ]); }
+	function _helpFormBeforeViewTrigger($args) {
+		$messageValidate = array();
+		if ( V::get('button_send', 0, $args) == 1 ) {
+			// fields form
+			$helpName    		= htmlentities(V::get('help_name', 0, $args));
+	    $helpEmail    		= htmlentities(V::get('help_email', 0, $args));
+	    $helpDescription  = htmlentities(V::get('help_description', 0, $args));
+
+			if ( empty($helpDescription) && !filter_var($helpEmail, FILTER_VALIDATE_EMAIL)) {
+				$messageValidate['error'] = 1;
+			}
+
+			$noticeRequest = 'Email: ' . $helpEmail . "; Treść zgłoszenia: " . $helpDescription;
+
+			// data for create insert in DB
+			$idQualityNotice = DB::getPDO()->insert('QUALITY_NOTICES', [
+				'NOTICE_INITIAL_TYPE'	=> 'BAD_PROCESS',
+				'ID_PROCES' => '1', //todo: ustalić ID procesu - ustawiłem defaultowo 1!!!!!
+				'NOTICE_REQUEST' => $noticeRequest,
+				'NOTICE_REPLY' => '',
+				'NOTICE_REPLY_TYPE' => 'BAD_PROCESS',
+				'L_APPOITMENT_DATE' => 'NOW()',
+				'L_APPOITMENT_USER' => User::getLogin(),
+				'ADM_ACCOUNT' => User::getLogin(),
+				'THIS_SINGLE_WASTE_COST' => '',
+				'WASTE_COST_COMMENT' => '',
+				'THIS_SINGLE_FIX_COST' => '',
+				'YEAR_COST_FOREACST_OF_SUCH_PROBLEM_WITH_FIXING' => '',
+				'FIX_COST_COMMENT' => '',
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()'
+			]);
+
+			if( $idQualityNotice > 0 ) {
+					$messageValidate['success'] = 'send';
+			} else {
+				$messageValidate['error'] = 2;
+			}
+
+			/*
+			TODO: dodać możliwość wysyłania maila używajac mail()
+				// Data fpr create mail
+		    $to      = self::$helpEmailTo; // uzupełnić mail
+		    $subject = 'Anton1 - formularz pomocy';
+		    $message = "Zgłaszający: " . $helpName . " \r\n  E-mail: " . $helpEmail . ". \r\n Treść wiadomości:\r\n " . $helpDescription;
+		    $headers = 'From: '. self::$helpEmailTo . "\r\n" .
+		        'Reply-To: '. self::$helpEmailTo . "\r\n" .
+		        'X-Mailer: PHP/' . phpversion();
+
+		    $sendMail = mail($to, $subject, $message, $headers);
+
+				if( $sendMailResponse == true ) {
+						$responseSendMail = true;
+						$messageValidate['success'] = 'send';
+
+				} else {
+					$messageValidate['error'] = 2;
+				}
+			*/
+		}
+		return [
+			'messageValidate' => $messageValidate,
+		];
+	}
+	function sendPageView($templateFile, $beforeViewTrigger = null) {
+		UI::gora();
+		echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
+		echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
+		Theme::top();
+		$tmplPath = __FILE__ . '.' . $templateFile;
+		if (!file_exists($tmplPath)) throw new Exception("Template file not exists '{$templateFile}'");
+
+		if ($beforeViewTrigger && is_callable($beforeViewTrigger)) {
+			$data = $beforeViewTrigger($_POST);
+			if (is_array($data) && !empty($data)) {
+				extract($data);
+			}
+		}
+		include($tmplPath);
+		UI::dol();
+	}
+
+	function graphTestAction() { include __FILE__ . '.graphTest.php'; }
+
+	function viewIncludeStoreJs($storeName = 'anton1RaportStore') {
+		UI::inlineJS(__FILE__ . '.store.js', [
+			'DBG' => V::get('DBG', 0, $_GET),
+			'STORE_NAME' => $storeName,
+			'CURRENT_DATE' => date("j.n.Y"),
+		]);
+	}
+
+	function defaultAction() {
+		UI::gora();
+		echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
+		echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
+		Theme::top();
+		//echo '<div id="smad-wrapper">'; // todo: sprawdzi  czy można usunać
+		echo '<div id="bi_audit_header"></div>' . "\n";
+		echo '<div class="container-bi_audit_form_pracownicy_raport" style="display: none;"></div>' . "\n";
+		echo '<div class="container-bi_audit_form_kontrahenci_raport" style="display: none;"></div>' . "\n";
+		echo '<div class="container-bi-audit_form_operacyjna_baza_zgloszen" style="display:none;"></div>' . "\n";
+		//	echo '<div class="container-bi_audit_form_raport_data" style="display: none;"></div>';
+
+		echo UI::h('script', ['src'=>"static/vendor.js?v=71baa97d", 'type'=>"text/javascript"]);
+		$this->viewIncludeStoreJs($storeName = "anton1RaportStore");
+		$aclOd = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
+		$exportFieldsOd = Core_AclHelper::getExportFieldList($aclOd);
+		$exportFieldLabelsOd = array_map(function ($fieldName) use ($aclOd) {
+			return [ 'name' => $fieldName, 'label' => $aclOd->getFieldLabel($fieldName) ];
+		}, $exportFieldsOd);
+
+		$aclDo = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
+		$exportFieldsDo = Core_AclHelper::getExportFieldList($aclDo);
+		$exportFieldLabelsDo = array_map(function ($fieldName) use ($aclDo) {
+			return [ 'name' => $fieldName, 'label' => $aclDo->getFieldLabel($fieldName) ];
+		}, $exportFieldsDo);
+		// $exportFieldLabelsDo = [ // TODO: RMME TEST DEV
+		// 	[ 'name' => 'ID', 'label' => 'Nr' ],
+		// 	[ 'name' => 'NIP', 'label' => 'NIP' ],
+		// ];
+
+		UI::inlineJS(__FILE__ . '.view.js', [
+			'BASE_URLS' => Request::getPathUri(),
+			'URL_FETCH_KONTRAHENCI_POWIAZANIA' => $this->getLink('fetchEnergaRumKontrahenciPowiazaniaAjax'),
+			'URL_FETCH_TEST_KRS' => $this->getLink('fetchTestKrsAjax'),
+			'URL_FETCH_TEST_CEIDG' => $this->getLink('fetchTestCeidgAjax'),
+			'URL_FETCH_PRACOWNICY' => $this->getLink('fetchPracownicyAjax'),
+			'URL_FETCH_KONTRAHENCI' => $this->getLink('fetchKontrahenciAjax'),
+			'URL_FETCH_PRACOWNICY_IDS_AJAX' => $this->getLink('fetchPracownicyIdsAjax'),
+			'URL_FETCH_KONTRAHENCI_IDS_AJAX' => $this->getLink('fetchKontrahenciIdsAjax'),
+			'URL_FETCH_LAST_REPORTS_AJAX' => $this->getLink('fetchLastReportsAjax'),
+			'URL_FETCH_PRACOWNICY_IDS_BY_REPORT_AJAX' => $this->getLink('fetchPracownicyIdsByReportAjax'),
+			'URL_FETCH_KONTRAHENCI_IDS_BY_REPORT_AJAX' => $this->getLink('fetchKontrahenciIdsByReportAjax'),
+			'URL_CREATE_PRACOWNICY_GROUP' => $this->getLink('createPracownicyGroupAjax'),
+			'URL_CREATE_KONTRAHENCI_GROUP' => $this->getLink('createKontrahenciGroupAjax'),
+			'URL_ADD_PRACOWNICY_TO_GROUP' => $this->getLink('addPracownicyToGroupAjax'),
+			'URL_REMOVE_PRACOWNICY_FROM_GROUP' => $this->getLink('removePracownicyFromGroupAjax'),
+			'URL_CREATE_PRACOWNICY' => $this->getLink('createPracownikAjax'),
+			'URL_CREATE_KONTRAHENCI' => $this->getLink('createKontrahentAjax'),
+			'URL_ADD_KONTRAHENCI_TO_GROUP' => $this->getLink('addKontrahenciToGroupAjax'),
+			'URL_REMOVE_KONTRAHENCI_FROM_GROUP' => $this->getLink('removeKontrahenciFromGroupAjax'),
+			'URL_FETCH_GROUP_PRACOWNICY' => $this->getLink('fetchGroupPracownicyAjax'),
+			'URL_FETCH_GROUP_KONTRAHENCI' => $this->getLink('fetchGroupKontrahenciAjax'),
+			'URL_GENERATE_BI_AUDIT_RAPORT_AJAX' => $this->getLink('generateBiAuditRaportAjax'),
+			'DBG' => V::get('DBG', 0, $_GET),
+			'VIEW_KONTRAHENCI' => $this->defaultViewFormBiAudit([], 'KONTRAHENCI'),
+			'VIEW_PRACOWNICY' => $this->defaultViewFormBiAudit([], 'PRACOWNICY'),
+			'VIEW_OPERACYJNA_BAZA_ZGLOSZEN' => $this->defaultViewFormBiAudit([], 'OPERACYJNA_BAZA_ZGLOSZEN'),
+			'URL_FORM_DATA_CSV_FILE_AJAX' => $this->getLink('formDataCsvFileAjax'),
+			'URL_SAVE_FORM_CSV_FILE_AJAX' => $this->getLink('saveFormCsvFileAjax'),
+			'URL_TABLE_POWIAZANIA' => Router::getRoute('ViewTableAjax')->getLink('', [ 'namespace' => "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA" ]),
+			'FIELD_LIST_PRACOWNICY' => array_merge(
+				array_map(function ($fieldName) {
+					return "f_{$fieldName}";
+				}, self::$FIELD_LIST_PRACOWNICY),
+				[
+					'f_Adresy',
+				]
+			),
+			'FIELD_LIST_KONTRAHENCI' => array_map(function ($fieldName) {
+				return "f_{$fieldName}";
+			}, self::$FIELD_LIST_KONTRAHENCI),
+			'EXPORT_FIELDS_OD' => $exportFieldLabelsOd,
+			'EXPORT_FIELDS_DO' => $exportFieldLabelsDo,
+			'CURRENT_DATE' => date("j.n.Y"),
+			'STORE_NAME' => $storeName = "anton1RaportStore",
+		]);
+		UI::inlineJS(__FILE__ . '.addItemToRaport.js', [
+			'URL_FETCH_FROM_BAZA' => $this->getLink('fetchFromBazaAjax'),
+			// 'URL_SAVE_TO_DB' => $this->getLink('saveToPozostaleOdDoAjax'),
+			'DBG' => V::get('DBG', 0, $_GET),
+			'FUNCTION_NAME' => "addPozostaleOdDo",
+			'STORE_NAME' => $storeName = "anton1RaportStore",
+		]);
+		// UI::inlineJS(__FILE__ . '.addItemToRaport.js', [
+		// 	'URL_FETCH_FROM_BAZA' => $this->getLink('fetchFromBazaAjax'),
+		// 	'URL_SAVE_TO_DB' => $this->getLink('saveToPozostaleOdDoAjax'),
+		// 	'DBG' => V::get('DBG', 0, $_GET),
+		// 	'FUNCTION_NAME' => "createPracownikAjax",
+		// ]);
+		// UI::inlineJS(__FILE__ . '.addItemToRaport.js', [
+		// 	'URL_FETCH_FROM_BAZA' => $this->getLink('fetchFromBazaAjax'),
+		// 	'URL_SAVE_TO_DB' => $this->getLink('saveToPozostaleOdDoAjax'),
+		// 	'DBG' => V::get('DBG', 0, $_GET),
+		// 	'FUNCTION_NAME' => "createKontrahentAjax",
+		// ]);
+		UI::inlineJS(__FILE__ . '.graphShowHide.js', [
+			'DBG' => V::get('DBG', 0, $_GET),
+			'FIELD_LIST_PRACOWNICY' => array_merge(
+				array_map(function ($fieldName) {
+					return "f_{$fieldName}";
+				}, self::$FIELD_LIST_PRACOWNICY),
+				[
+					'f_Adresy',
+				]
+			),
+			'FIELD_LIST_KONTRAHENCI' => array_map(function ($fieldName) {
+				return "f_{$fieldName}";
+			}, self::$FIELD_LIST_KONTRAHENCI),
+		]);
+
+		echo '</div>'; // #smad-wrapper
+		UI::dol();
+	}
+
+
+	public function saveToPozostaleOdDoAjaxAction() {
+		 Response::sendTryCatchJson(array($this, 'saveToPozostaleOdDoAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function saveToPozostaleOdDoAjax($args) {
+		DBG::log($args, 'array', "saveToPozostaleOdDoAjax args");
+		$baza = V::get('baza', '', $args); // namespace
+		$item = V::get('item', [], $args); // [ '@primaryKey' => int, ... ]
+		$from = V::get('from', [], $args); // OD | DO
+		if (empty($item)) throw new Exception("Brak danych do zapisania");
+		switch ($baza) {
+			case 'default_db/BI_audit_KRS/BI_audit_KRS':
+			case 'default_db/BI_audit_KRS_person/BI_audit_KRS_person':
+			case 'default_db/BI_audit_MSIG/BI_audit_MSIG':
+			case 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person':
+			case 'default_db/BI_audit_CEIDG/BI_audit_CEIDG':
+			default: throw new Exception("Not implemented ");
+		}
+
+		die("TODO: 500! baza({$baza}) pk({$item['@primaryKey']})");
+	}
+
+	public function saveToPracownicyAjaxAction() {
+		 Response::sendTryCatchJson(array($this, 'saveToPracownicyAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function saveToPracownicyAjax($args) {
+		DBG::log($args, 'array', "saveToPracownicyAjax args");
+		$baza = V::get('baza', '', $args);
+		$item = V::get('item', [], $args);
+		if (empty($item)) throw new Exception("Brak danych do zapisania");
+		switch ($baza) {
+			case 'default_db/BI_audit_KRS/BI_audit_KRS': return $this->saveKRSToPracownicyAjax($item);
+			case 'default_db/BI_audit_KRS_person/BI_audit_KRS_person': return $this->saveKRSPersonToPracownicyAjax($item);
+			case 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI': return $this->saveKontrahentToPracownicyAjax($item);
+			case 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY': return $this->savePracownikToPracownicyAjax($item);
+			case 'default_db/BI_audit_taxpayer/BI_audit_taxpayer': return $this->saveVATpToPracownicyAjax($item);
+			case 'default_db/BI_audit_MSIG/BI_audit_MSIG': return $this->saveMSIGToPracownicyAjax($item);
+			case 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person': return $this->saveMSIGPersonToPracownicyAjax($item);
+			case 'default_db/BI_audit_CEIDG/BI_audit_CEIDG': return $this->saveCEIDGToPracownicyAjax($item);
+		}
+	}
+	function saveKRSToPracownicyAjax($item) {
+		$companyName = V::get('nazwa', '', $item);
+		$companyNip = V::get('nip', '', $item);
+		$comapanyRegon = V::get('regon', '', $item);
+		$comapanyKrs = V::get('krs', '', $item);
+		$companyStreet = V::get('A_ulica', '', $item);
+		$companyHomeNumber = V::get('A_nrDomu', '', $item);
+		$companyNumber = V::get('A_nrLokalu', '', $item);
+		$companyPostCode = V::get('A_kod', '', $item);
+		$companyCity = V::get('A_miejscowosc', '', $item);
+
+		// validate
+		//if (!$companyName) throw new Exception("Nie podano nazwy");
+		//if (!$companyNip) throw new Exception("Nie podano nip");
+
+		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
+			'imiona' => $companyName,
+			'nip' => ($companyNip) ? $companyNip : NULL,
+			'regon' => ($comapanyRegon) ? $comapanyRegon : NULL,
+			'krs' => ($comapanyKrs) ? $comapanyKrs : NULL,
+			'ulica' => $companyStreet,
+			'nr' => $companyHomeNumber,
+			'nrLokalu' => $companyNumber,
+			'kodPocztowy' => $companyPostCode,
+			'miejscowosc' => $companyCity,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano podmiot",
+			'type' => "success",
+		];
+	}
+	function saveMSIGToPracownicyAjax($item) {
+		$companyName = V::get('nazwa', '', $item);
+		$companyNip = V::get('nip', '', $item);
+		$comapanyRegon = V::get('regon', '', $item);
+		$comapanyKrs = V::get('krs', '', $item);
+		$companyStreet = V::get('A_ulica', '', $item);
+		$companyHomeNumber = V::get('A_nrDomu', '', $item);
+		$companyNumber = V::get('A_nrLokalu', '', $item);
+		$companyPostCode = V::get('A_kod', '', $item);
+		$companyCity = V::get('A_miejscowosc', '', $item);
+
+		// validate
+		//if (!$companyName) throw new Exception("Nie podano nazwy");
+		//if (!$companyNip) throw new Exception("Nie podano nip");
+
+		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
+			'imiona' => $companyName,
+			'nip' => ($companyNip) ? $companyNip : NULL,
+			'regon' => ($comapanyRegon) ? $comapanyRegon : NULL,
+			'krs' => ($comapanyKrs) ? $comapanyKrs : NULL,
+			'ulica' => $companyStreet,
+			'nr' => $companyHomeNumber,
+			'nrLokalu' => $companyNumber,
+			'kodPocztowy' => $companyPostCode,
+			'miejscowosc' => $companyCity,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano podmiot",
+			'type' => "success",
+		];
+	}
+	function saveKRSPersonToPracownicyAjax($item) {
+		$personName = V::get('imiona', '', $item);
+		$personSurname = V::get('nazwisko', '', $item);
+		$personPesel = V::get('pesel', '', $item);
+
+		// validate
+		//if (!$personName) throw new Exception("Nie podano imienia");
+		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
+		try{
+			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
+				'imiona' => $personName,
+				'nazwisko' => $personSurname,
+				'pesel' => ($personPesel) ? $personPesel : NULL,
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()',
+			]);
+		} catch( PDOException $e){
+			if($e->errorInfo[1]== 1062){
+				throw new Exception("Ta osoba jest już w bazie danych");
+			}
+			else{
+				throw new Exception("Błąd bazy danych");
+			}
+		}
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+	function saveMSIGPersonToPracownicyAjax($item) {
+		$personName = V::get('imiona', '', $item);
+		$personSurname = V::get('nazwisko', '', $item);
+		$personPesel = V::get('pesel', '', $item);
+
+		// validate
+		//if (!$personName) throw new Exception("Nie podano imienia");
+		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
+		try{
+			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
+				'imiona' => $personName,
+				'nazwisko' => $personSurname,
+				'pesel' => ($personPesel) ? $personPesel : NULL,
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()',
+			]);
+		} catch( PDOException $e){
+			if($e->errorInfo[1]== 1062){
+				throw new Exception("Ta osoba jest już w bazie danych");
+			}
+			else{
+				throw new Exception("Błąd bazy danych");
+			}
+		}
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+	function saveCEIDGToPracownicyAjax($item) {
+		$personName = V::get('imiona', '', $item);
+		$personSurname = V::get('nazwisko', '', $item);
+		$personEnterprise = V::get('firma','',$item);
+		$personNip = V::get('nip', '', $item);
+		$personRegon = V::get('regon', '', $item);
+		$personLocal = V::get('lokal', '', $item);
+		$personPostalCode = V::get('kodPocztwy', '', $item);
+		$personCity = V::get('miejscowosc', '', $item);
+		$personBuilding = V::get('budynek', '', $item);
+		$personStreet = V::get('ulica', '', $item);
+		$personName.=' ';
+		$personName.=$personEnterprise;
+		$personEnterprise.=' ';
+		$personEnterprise.=$personSurname;
+
+		// validate
+		//if (!$personName) throw new Exception("Nie podano imienia");
+		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
+
+		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
+			'imie' => $personName,
+			'nazwisko' => $personEnterprise,
+			'ulica' => $personStreet,
+			'nr' => $personBuilding,
+			'nrLokalu' => $personLocal,
+			'kodPocztowy' => $personPostalCode,
+			'miejscowosc' => $personCity,
+			'regon' => ($personRegon) ? $personRegon : NULL,
+			'nip' => ($personNip) ? $personNip : NULL,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+	function saveVATpToPracownicyAjax($item) {
+		$personName = V::get('imiona', '', $item);
+		$personSurname = V::get('nazwisko', '', $item);
+		$personNip = V::get('nip', '', $item);
+		$personRegon = V::get('regon', '', $item);
+
+		// validate
+		//if (!$personName) throw new Exception("Nie podano imienia");
+		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
+
+		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
+			'imie' => $personName,
+			'nazwisko' => $personSurname,
+			'regon' => ($personRegon) ? $personRegon : NULL,
+			'nip' => ($personNip) ? $personNip : NULL,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+	function saveKontrahentToPracownicyAjax($item) {
+		// companyName: document.getElementById('companyName').value,
+		// companyNip: document.getElementById('companyNip').value,
+		// comapanyRegon: document.getElementById('comapanyRegon').value,
+		DBG::log($item, 'array', "argumenty do wpisania");
+		$companyName = V::get('companyName', '', $item);
+		$companyNip = V::get('companyNip', '', $item);
+		$companyRegon = V::get('companyRegon', '', $item);
+		$companyPesel = V::get('companyPesel', '', $item);
+		$companyStreet = V::get('companyStreet', '', $item);
+		$companyNumber = V::get('companyNumber', '', $item);
+		$companyNumberLocal = V::get('companyNumberLocal', '', $item);
+		$companyPostCode = V::get('companyPostCode', '', $item);
+		$companyCity = V::get('companyCity', '', $item);
+		$companyKrs = V::get('companyKrs', '', $item);
+
+		// validate
+		if (!$companyName) throw new Exception("Nie wpisano nazwy");
+		if (!$companyNip) throw new Exception("Nie wpisano nip");
+		try{
+			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
+				'nazwisko' => $companyName,
+				'nip' => ($companyNip) ? $companyNip : NULL,
+				'regon' => ($companyRegon) ? $companyRegon : NULL,
+				'pesel' => $companyPesel,
+				'ulica' => $companyStreet,
+				'nr' => $companyNumber,
+				'nrLokalu' => $companyNumberLocal,
+				'kodPocztowy' => $companyPostCode,
+				'miejscowosc' => $companyCity,
+				'krs' => $companyKrs,
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()',
+			]);
+		} catch( PDOException $e){
+			if($e->errorInfo[1]== 1062){
+				throw new Exception("Ta osoba jest już w bazie danych");
+			}
+			else{
+				throw new Exception("Błąd bazy danych");
+			}
+		}
+		return [
+			'msg' => "Dodano podmiot",
+			'type' => "success",
+		];
+	}
+	function savePracownikToPracownicyAjax($item) {
+		$personName = V::get('personName', '', $item);
+		$personSurname = V::get('personSurname', '', $item);
+		$personNip = V::get('personNip', '', $item);
+		$personPesel = V::get('personPesel', '', $item);
+
+		// validate
+		if (!$personName) throw new Exception("Nie wpisano imienia");
+		if (!$personSurname) throw new Exception("Nie wpisano  nazwiska");
+		try{
+			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
+				'imiona' => $personName,
+				'nazwisko' => $personSurname,
+				'nip' => ($personNip) ? $personNip : NULL,
+				'pesel' => ($personPesel) ? $personPesel : NULL,
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()',
+			]);
+		} catch( PDOException $e){
+			if($e->errorInfo[1]== 1062){
+				throw new Exception("Ta osoba jest już w bazie danych");
+			}
+			else{
+				throw new Exception("Błąd bazy danych");
+			}
+		}
+
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+
+	public function saveToKontrahenciAjaxAction() {
+		 Response::sendTryCatchJson(array($this, 'saveToKontrahenciAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function saveToKontrahenciAjax($args) {
+		DBG::log($args, 'array', "saveToKontrahenciAjaxActionAjax args");
+		// $baza + $item['@primaryKey']
+		$baza = V::get('baza', '', $args);
+		$item = V::get('item', [], $args);
+		if (empty($item)) throw new Exception("Brak danych do zapisania");
+		switch ($baza) {
+			case 'default_db/BI_audit_KRS/BI_audit_KRS': return $this->saveKRSToKontrahenciAjax($item);
+			case 'default_db/BI_audit_KRS_person/BI_audit_KRS_person': return $this->saveKRSPersonToKontrahenciAjax($item);
+			case 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI': return $this->saveKontrahentToKontrahenciAjax($item);
+			case 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY': return $this->savePracownikToKontrahenciAjax($item);
+			case 'default_db/BI_audit_taxpayer/BI_audit_taxpayer': return $this->saveVATpToKontrahenciAjax($item);
+			case 'default_db/BI_audit_MSIG/BI_audit_MSIG': return $this->saveMSIGToKontrahenciAjax($item);
+			case 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person': return $this->saveMSIGPersonToKontrahenciAjax($item);
+			case 'default_db/BI_audit_CEIDG/BI_audit_CEIDG': return $this->saveCEIDGToKontrahenciAjax($item);
+		}
+	}
+
+	function saveKRSToKontrahenciAjax($item) {
+		$companyName = V::get('nazwa', '', $item);
+		$companyNip = V::get('nip', '', $item);
+		$companyRegon = V::get('regon', '', $item);
+		$companyKrs = V::get('krs', '', $item);
+		$companyStreet = V::get('A_ulica', '', $item);
+		$companyNumberBuilding = V::get('A_nrDomu', '', $item);
+		$companyNumberLocal = V::get('A_nrLokalu', '', $item);
+		$companyPostCode = V::get('A_kod', '', $item);
+		$companyCountry = V::get('A_kraj', '', $item);
+		$companyCity = V::get('A_miejscowosc', '', $item);
+
+		// validate
+		//if (!$companyName) throw new Exception("Nie podano nazwy");
+		//if (!$companyNip) throw new Exception("Nie podano nip");
+
+		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
+			'Pelna_nazwa_kontrahenta' => $companyName,
+			'NIP' => ($companyNip) ? $companyNip : NULL,
+			'REGON' => ($companyRegon) ? $companyRegon : NULL,
+			'KRS' => ($companyKrs) ? $companyKrs : NULL,
+			'Ulica' => $companyStreet,
+			'Numer_mieszkania_lokalu' => $companyNumberLocal,
+			'Numer_budynku' => $companyNumberBuilding,
+			'Kod_pocztowy' => $companyPostCode,
+			'Miejscowosc' => $companyCity,
+			'Kraj' => $companyCountry,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano podmiot",
+			'type' => "success",
+		];
+	}
+	function saveMSIGToKontrahenciAjax($item) {
+		$companyName = V::get('nazwa', '', $item);
+		$companyNip = V::get('nip', '', $item);
+		$comapanyRegon = V::get('regon', '', $item);
+		$comapanyKrs = V::get('krs', '', $item);
+		$companyStreet = V::get('A_ulica', '', $item);
+		$companyNumberBuilding = V::get('A_nrDomu', '', $item);
+		$companyNumberLocal = V::get('A_nrLokalu', '', $item);
+		$companyPostCode = V::get('A_kod', '', $item);
+		$companyCountry = V::get('A_kraj', '', $item);
+		$companyCity = V::get('A_miejscowosc', '', $item);
+
+		// validate
+		//if (!$companyName) throw new Exception("Nie podano nazwy");
+		//if (!$companyNip) throw new Exception("Nie podano nip");
+
+		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
+			'Pelna_nazwa_kontrahenta' => $companyName,
+			'NIP' => ($companyNip) ? $companyNip : NULL,
+			'REGON' => ($comapanyRegon) ? $comapanyRegon : NULL,
+			'KRS' => ($comapanyKrs) ? $comapanyKrs : NULL,
+			'Ulica' => $companyStreet,
+			'Numer_mieszkania_lokalu' => $companyNumberLocal,
+			'Numer_budynku' => $companyNumberBuilding,
+			'Kod_pocztowy' => $companyPostCode,
+			'Miejscowosc' => $companyCity,
+			'Kraj' => $companyCountry,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano podmiot",
+			'type' => "success",
+		];
+	}
+	function saveCEIDGToKontrahenciAjax($item) {
+		$personFirstName = V::get('imie', '', $item);
+		$personLastName = V::get('nazwisko', '', $item);
+		$personNip = V::get('nip', '', $item);
+		$personEnterprise = V::get('firma', '', $item);
+		$personStreet = V::get('ulica', '', $item);
+		$personNumber = V::get('budynek', '', $item);
+		$personNumberLocal = V::get('lokal', '', $item);
+		$personPostalCode = V::get('kodPocztowy', '', $item);
+		$personCity = V::get('miejscowosc', '', $item);
+		$personCountry = V::get('kraj', '', $item);
+		$personFirstName .= ' ';
+		$personFirstName .= $personEnterprise;
+		$personEnterprise .= ' ';
+		$personEnterprise .= $personLastName;
+
+
+		// validate
+		//if (!$personFirstName) throw new Exception("Nie podano nazwy");
+		//if (!$personNip) throw new Exception("Nie podano nip");
+
+		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
+			'Pelna_nazwa_kontrahenta' => $personEnterprise,
+			//'Skrocona_Nazwa_Kontrahenta' => $personFirstName,
+			'NIP' => ($personNip) ? $personNip : NULL,
+			'REGON' => ($personRegon) ? $personRegon : NULL,
+			'Ulica' => $personStreet,
+			'Numer_mieszkania_lokalu' => $personNumber,
+			'Numer_budynku' => $personNumber,
+			'Kod_pocztowy' => $personPostalCode,
+			'Miejscowosc' => $personCity,
+			'Kraj' => $personCountry,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano podmiot",
+			'type' => "success",
+		];
+	}
+	function saveKRSPersonToKontrahenciAjax($item) {
+		$personName = V::get('imiona', '', $item);
+		$personSurname = V::get('nazwisko', '', $item);
+		$personPesel = V::get('pesel', '', $item);
+
+		// validate
+		//if (!$personName) throw new Exception("Nie podano imienia");
+		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
+		try{
+			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
+				//'Skrocona_Nazwa_Kontrahenta' => $personName,
+				'Pelna_nazwa_kontrahenta' => $personSurname,
+				'PESEL' => ($personPesel) ? $personPesel : NULL,
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()',
+			]);
+		} catch( PDOException $e){
+			if($e->errorInfo[1]== 1062){
+				throw new Exception("Ta osoba jest już w bazie danych");
+			}
+			else{
+				throw new Exception("Błąd bazy danych");
+			}
+		}
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+	function saveMSIGPersonToKontrahenciAjax($item) {
+		$personName = V::get('imiona', '', $item);
+		$personSurname = V::get('nazwisko', '', $item);
+		$personPesel = V::get('pesel', '', $item);
+
+		// validate
+		//if (!$personName) throw new Exception("Nie podano imienia");
+		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
+		try{
+			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
+				//'Skrocona_Nazwa_Kontrahenta' => $personName,
+				'Pelna_nazwa_kontrahenta' => $personSurname,
+				'PESEL' => ($personPesel) ? $personPesel : NULL,
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()',
+			]);
+		} catch( PDOException $e){
+			if($e->errorInfo[1]== 1062){
+				throw new Exception("Ta osoba jest już w bazie danych");
+			}
+			else{
+				throw new Exception("Błąd bazy danych");
+			}
+		}
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+	function saveVATpToKontrahenciAjax($item) {
+		$personName = V::get('imiona', '', $item);
+		$personSurname = V::get('nazwisko', '', $item);
+		$personPesel = V::get('pesel', '', $item);
+
+		// validate
+		//if (!$personName) throw new Exception("Nie podano imienia");
+		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
+
+		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
+			//'Skrocona_Nazwa_Kontrahenta' => $personName,
+			'Pelna_nazwa_kontrahenta' => $personSurname,
+			'PESEL' => ($personPesel) ? $personPesel : NULL,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+	function saveKontrahentToKontrahenciAjax($item) {
+		// companyName: document.getElementById('companyName').value,
+		// companyNip: document.getElementById('companyNip').value,
+		// comapanyRegon: document.getElementById('comapanyRegon').value,
+
+		$companyName = V::get('companyName', '', $item);
+		$companyNip = V::get('companyNip', '', $item);
+		$companyRegon = V::get('companyRegon', '', $item);
+		$companyPesel = V::get('companyPesel', '', $item);
+		$companyStreet = V::get('companyStreet', '', $item);
+		$companyNumber = V::get('companyNumber', '', $item);
+		$companyNumberLocal = V::get('companyNumberLocal', '', $item);
+		$companyPostCode = V::get('companyPostCode', '', $item);
+		$companyCity = V::get('companyCity', '', $item);
+		$companyKrs = V::get('companyKrs', '', $item);
+
+		// validate
+		if (!$companyName) throw new Exception("Nie wpisano nazwy");
+		if (!$companyNip) throw new Exception("Nie wpisano nip");
+		try{
+			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
+				'Pelna_nazwa_kontrahenta' => $companyName,
+				'NIP' => ($companyNip) ? $companyNip : NULL,
+				'REGON' => ($comapanyRegon) ? $comapanyRegon : NULL,
+				'PESEL' => ($companyPesel) ? $companyPesel : NULL,
+				'Ulica' => ($companyStreet) ? $companyStreet : NULL,
+				'Numer_budynku' => ($companyNumber) ? $companyNumber : NULL,
+				'Numer_mieszkania_lokalu' => ($companyNumberLocal) ? $companyNumberLocal : NULL,
+				'Kod_pocztowy' => ($companyPostCode) ? $companyPostCode : NULL,
+				'Miejscowosc' => ($companyCity) ? $companyCity : NULL,
+				'KRS' => ($companyKrs) ? $companyKrs : NULL,
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()',
+			]);
+		} catch( PDOException $e){
+			if($e->errorInfo[1]== 1062){
+				throw new Exception("Ta osoba jest już w bazie danych");
+			}
+			else{
+				throw new Exception("Błąd bazy danych");
+			}
+		}
+		return [
+			'msg' => "Dodano podmiot",
+			'type' => "success",
+		];
+	}
+	function savePracownikToKontrahenciAjax($item) {
+		$personName = V::get('personName', '', $item);
+		$personSurname = V::get('personSurname', '', $item);
+		$personNip = V::get('personNip', '', $item);
+		$personPesel = V::get('personPesel', '', $item);
+
+		// validate
+		if (!$personName) throw new Exception("Nie wpisano imienia");
+		if (!$personSurname) throw new Exception("Nie wpisano  nazwiska");
+		try{
+			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
+				//'Skrocona_Nazwa_Kontrahenta' => $personName,
+				'Pelna_nazwa_kontrahenta' => $personSurname,
+				'NIP' => ($personNip) ? $personNip : NULL,
+				'PESEL' => ($personPesel) ? $personPesel : NULL,
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()',
+			]);
+		} catch( PDOException $e){
+			if($e->errorInfo[1]== 1062){
+				throw new Exception("Ta osoba jest już w bazie danych");
+			}
+			else{
+				throw new Exception("Błąd bazy danych");
+			}
+		}
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+
+
+	/**
+	*  Dodanie nowego pracownika
+	*/
+	public function createPracownikAjaxAction() {
+		 Response::sendTryCatchJson(array($this, 'createPracownikAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
+	}
+	public function createPracownikAjax($args) {
+		DBG::log($args, 'array', "args");
+		$personName = V::get('personName', '', $args);
+		$personSurname = V::get('personSurname', '', $args);
+		$personNip = V::get('personNip', '', $args);
+		$personPesel = V::get('personPesel', '', $args);
+		$personRegon = V::get('personRegon', '', $args);
+
+		// validate
+		if (!$personName) throw new Exception("Nie wpisano imienia");
+		if (!$personSurname) throw new Exception("Nie wpisano  nazwiska");
+
+
+		$idPracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
+			'imiona' => $personName,
+			'nazwisko' => $personSurname,
+			'nip' => ($personNip) ? $personNip : NULL,
+			'pesel' => ($personPesel) ? $personPesel : NULL,
+			'regon' => ($personRegon) ? $personRegon : NULL,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano osobę",
+			'type' => "success",
+		];
+	}
+
+	/**
+	*  Dodanie nowego kontrahenta
+	*/
+	public function createKontrahentAjaxAction() {
+		 Response::sendTryCatchJson(array($this, 'createKontrahentAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
+	}
+	public function createKontrahentAjax($args) {
+		$companyFullName = V::get('companyFullName', '', $args);
+		$companyShortName = V::get('$companyShortName', '', $args);
+		$companyNameGroup = V::get('companyNameGroup', '', $args);
+		$companyKrs = V::get('companyKrs', '', $args);
+		$companyNip = V::get('companyNip', '', $args);
+		$companyPesel = V::get('companyPesel', '', $args);
+		$companyFax = V::get('companyFax', '', $args);
+		$companyTelefon = V::get('companyTelefon', '', $args);
+		$companyMail = V::get('companyMail', '', $args);
+		$companyStreet = V::get('companyStreet', '', $args);
+		$companyNumberBuilding = V::get('companyNumberBuilding', '', $args);
+		$companyNumberLocal = V::get('companyNumberLocal', '', $args);
+		$companyPostCode = V::get('companyPostCode', '', $args);
+		$companyPlace = V::get('companyPlace', '', $args);
+		$companyCountry = V::get('companyCountry', '', $args);
+		$companyTypeCompany = V::get('companyTypeCompany', '', $args);
+		$companyTitleDocument = V::get('companyTitleDocument', '', $args);
+		$companyDesc = V::get('companyDesc', '', $args);
+
+		// validate
+		if (!$companyFullName) throw new Exception("Nie wpisano pełnej nazwy kontrahenta");
+
+
+		$idKontrahent = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
+			'Pelna_nazwa_kontrahenta' => $companyFullName,
+			'Skrocona_Nazwa_Kontrahenta' => ($companyShortName) ? $companyShortName : null,
+			'Nazwa_grupy_kapitalowej' => ($companyNameGroup) ? $companyNameGroup : null,
+			'KRS' => ($companyKrs) ? $companyKrs : null,
+			'NIP' => ($companyNip) ? $companyNip : null,
+			'PESEL' => ($companyPesel) ? $companyPesel : null,
+			'Fax' => ($companyFax) ? $companyFax : null,
+			'Telefon' => ($companyTelefon) ? $companyTelefon : null,
+			'Mail' => ($companyMail) ? $companyMail : null,
+			'Ulica' => ($companyStreet) ? $companyStreet : null,
+			'Numer_budynku' => ($companyNumberBuilding) ? $companyNumberBuilding : null,
+			'Numer_mieszkania_lokalu' => ($companyNumberLocal) ? $companyNumberLocal : null,
+			'Kod_pocztowy' => ($companyPostCode) ? $companyPostCode : null,
+			'Miejscowosc' => ($companyPlace) ? $companyPlace : null,
+			'Kraj' => ($companyCountry) ? $companyCountry : null,
+			'Typ_kontrahenta' => ($companyTypeCompany) ? $companyTypeCompany : null,
+			'Tytul_dokumentu' => ($companyTitleDocument) ? $companyTitleDocument : null,
+			'uwagi' => ($companyDesc) ? $companyDesc  : null,
+
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+		]);
+
+		return [
+			'msg' => "Dodano podmiot/kontrahenta",
+			'type' => "success",
+		];
+	}
+
+
+/**
+ * Funkcja ajax do odebrania danych z przesłanego pliku CSV do parsowania
+ */
+	public function formDataCsvFileAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'formDataCsvFileAjax'));
+	}
+
+/**
+ * Funkcja parsuje dane wgrywanego plku csv i zwraca dane w inputach
+ */
+public function formDataCsvFileAjax() {
+
+	if (!file_exists($_FILES['file']['tmp_name'])) throw new Exception("Wybierz plik do przesłania.");
+
+	$file = file($_FILES['file']['tmp_name']);
+	//$showCheckbox = V::get('showCheckbox', '', $args);
+	$showCheckbox = V::get('showCheckbox', 0, $_REQUEST, 'string');
+
+	// parsujemy csv to tablicy
+	$arrayDataCsv = $this->csvToArray($file, ';', '"', '\n\r');
+
+
+		$i = 0;
+		// tworzymy rekordy
+		foreach ( $arrayDataCsv as $line ) {
+
+			$viewFormCol .= '<tr>';
+			foreach ( $line as $keyData => $rowData ) {
+								// utworzenie nagłówków tabeli
+								if( $i == 0)  { $header .= '<td style="min-width:160px">' . $keyData . '</td>'; }
+								// utworzenie inputa do edycji
+								$viewFormCol .= '<td style="min-width:160px"><input type="text" name="item['.$i.']['.$keyData.']" value="'.$rowData .'" class="form-control input-lg" /></td>';
+
+			 }
+			 $viewFormCol .= '</tr>';
+
+			 $i++;
+
+		}
+
+		// pokaz checkbox jeśli ma status showCheckbox
+		if ( $showCheckbox == 'yes' ) {
+			$viewFormCol .= '<div style="margin: 10px 0"><input type="checkbox" name="override" value="1" /> Nadpisz wszystkie rekordy w bazie danych</div';
+		}
+		$viewFormHtml = '<div id="smad-window-modal" style="overflow-x: scroll;">
+		<div class="table-responsive padding-0" >
+		<form method="POST" id="formDataFromCsv" class="form-horizontal"><table class="table table-bordered table-hover table-striped" height="5"><thead><tr>'. $header .'</tr></thead><tbody id="smad-csv-data">'. $viewFormCol .'</tbody></table></form></div>
+		</div>';
+
+		//return $viewFormHtml;
+		return [
+			'type' => 'success',
+			'msg' => 'OK',
+			'__req_args' => $_REQUEST,
+			'__args' => $args,
+			'body' => [
+				'view' => $viewFormHtml,
+			]
+		];
+
+	}
+
+
+	/**
+	 * Funkcja ajax do odebrania danych z przesłanego formularza z parsowanego CSV
+	 */
+	public function saveFormCsvFileAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'saveFormCsvFileAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+		//Response::sendTryCatchJson(array($this, 'saveFormCsvFileAjax'));
+	}
+
+
+/**
+ * Funkcja ajax do zapisania danych z przesłanego formularza z parsowanego CSV
+ */
+	public function saveFormCsvFileAjax($args) {
+		//dane z formularza
+		$formData = V::get('formData', '', $args);
+		$enumType = V::get('enumType', '', $args);
+
+		$override = false; // false - nie nadpisujemy danych
+		$arrayInfo = array();
+		$arrayInfo['insert'] = 0;
+		$arrayInfo['update'] = 0;
+		$arrayInfo['error'] = 0;
+
+		// pobranie nazwy tabeli z db
+		$table = $this->getNameTableByEnum( strtoupper($enumType) );
+
+		if ( $table == null ) throw new Exception('Błąd zapisu. Tabela w db nie istnieje');
+		// unserialize data from serialize in javascript
+		parse_str($formData, $resultArrayFormdata);
+
+		if ( count($resultArrayFormdata['item']) == 0) {
+			throw new Exception("Wystapił problem podczas przesyłania danych - brak przesłanych danych.");
+		}
+
+		// ustawienie true jeśli wyrabno nadpisanie danych
+		if ( isset($resultArrayFormdata['override']) ) { $override = true; }  // aktualizuj rekordy/nadpisz istniejace
+
+
+		// dodanie/aktualizacjia wpisu
+		foreach ( $resultArrayFormdata['item'] as $line ) {
+
+				$response = $this->saveDataToDb($table, $line, $override);
+
+			 // tworzymy listę informacji o liczbie nowych/zaktualizowanych/z błedami rekordów
+			 $arrayInfo = $this->responseCountListInfoAboutSaveData($response, $arrayInfo);
+		}
+
+		// utworzenie komunikatów
+		if ( isset($arrayInfo['insert']) ) { $textInsert = "Liczba nowych rekordów: (" . $arrayInfo['insert'] . ");"; }
+		if ( isset($arrayInfo['error']) ) { $textError = "Liczba nie zapisanych rekordów (" . $arrayInfo['insert'] . ");"; }
+
+		return [
+			'msg' => "Zapisano dane. " . $textInsert . " " . $textError ,
+			'type' => "success",
+		];
+
+	}
+
+	/**
+	 * Count list
+	 */
+	public function responseCountListInfoAboutSaveData($response, $arrayInfo) {
+
+		if (!is_array($response)) throw new Exception('Wystapił bład podczas zapisu danych');
+		$countData = array();
+
+		switch(key($response)) {
+			case 'insert':
+				$countData['insert'] = $arrayInfo['insert'] + 1;
+				break;
+			case 'error':
+				$countData['error'] = $arrayInfo['insert'] + 1;
+				break;
+		}
+
+		return $countData;
+	}
+
+	/**
+	 * Function parse csv to array
+	 * @param $filename - file data from FILE
+	 * @param $delimiter - delimiter
+	 * @param $enclosure -
+	 * @param $escape -
+	 */
+	function csvToArray($filedata , $delimiter=';', $enclosure='"', $escape = '\\') {
+	  if(!$filedata || empty($filedata)) return false;
+
+	  $header = null;
+	  $data = array();
+
+	  foreach( $filedata as $line) {
+	    $values = str_getcsv( $line, $delimiter, $enclosure, $escape );
+	    if(!$header) $header = $values;
+	    else $data[] = array_combine( $header, $values );
+	  }
+
+	  return $data;
+	}
+
+	/**
+	 *  Save data in database
+	 */
+	public function saveDataToDb( $table, $arrayData, $override = false ) {
+		$response = array();
+
+		try {
+			if ($override) {
+				DB::getPDO()->insertOrUpdate($table, array_merge($arrayData, [
+					'@insert' => [
+						'A_RECORD_CREATE_DATE' => 'NOW()',
+						'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+					],
+					'@update' => array_merge($arrayData, [
+						'A_RECORD_UPDATE_DATE' => 'NOW()',
+						'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
+					]),
+				]));
+			} else {
+				$responseInsert = DB::getPDO()->insert($table, array_merge($arrayData, [
+					'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+					'A_RECORD_CREATE_DATE' => 'NOW()',
+				]));
+			}
+
+				$response['insert'] = 1;
+
+		} catch (Exception $e) {
+					DBG::log($e);
+					$response['error'] = 1;
+		}
+
+		return $response;
+	}
+
+
+	/**
+	 * Get name table by enum
+	 */
+	public function getNameTableByEnum($type) {
+
+		$nameTable = null;
+			switch ($type) {
+					case 'KONTRAHENCI':
+						$nameTable = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
+					break;
+					case 'PRACOWNICY':
+						$nameTable = 'BI_audit_ENERGA_PRACOWNICY';
+					break;
+			}
+
+			return $nameTable;
+	}
+
+
+
+	public function fetchEnergaRumKontrahenciPowiazaniaAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchEnergaRumKontrahenciPowiazaniaAjax')); // , $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function fetchEnergaRumKontrahenciPowiazaniaAjax($args) {
+		$id = V::get('ID', 26, $_REQUEST, 'int');
+
+		$items = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA')->buildQuery([
+			'cols' => [ // TODO:? propertyName = []
+				'ID',
+				'A_ADM_COMPANY',
+				'L_APPOITMENT_USER',
+				'A_CLASSIFIED',
+				'A_STATUS',
+				'A_STATUS_INFO',
+				'BI_analiza_maxDepth',
+				'BI_analiza_minDepth',
+				'BI_analiza_onlyTargets',
+				'BI_analiza_reloadCache',
+				'FILE_STATUS',
+				'FILE_STATUS_info',
+				'L_APPOITMENT_USER',
+				'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+				'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+				'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
+				'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person',
+			],
+			'f_ID' => "{$id}",
+		])->getItems([
+			'limit' => 10
+		]);
+
+		// $items = [
+		// 	[ 'ID' => 1, 'L_APPOITMENT_INFO' => 'x', 'BI_analiza_depth' => 'a', 'FILE_STATUS' => 1, 'FILE_STATUS_info' => 'test1'],
+		// 	[ 'ID' => 2, 'L_APPOITMENT_INFO' => 'y', 'BI_analiza_depth' => 'b', 'FILE_STATUS' => 0, 'FILE_STATUS_info' => 'test2'],
+		// 	[ 'ID' => 3, 'L_APPOITMENT_INFO' => 'z',  'BI_analiza_depth' => 'c', 'FILE_STATUS' => 1, 'FILE_STATUS_info' => 'test3'],
+		// ];
+
+		return [
+			'type' => 'success',
+			'msg' => 'OK',
+			'__req_args' => $_REQUEST,
+			'__args' => $args,
+			'body' => [
+				'items' => $items,
+				'view' => $this->showPowiazaniaEnergaRumKontrahenciPowiazania($items),
+			]
+		];
+	}
+
+
+public function showPowiazaniaEnergaRumKontrahenciPowiazania($items) {
+
+	$view = '<form class="form-horizontal" method="post">
+						<table class="table table-bordered table-hover table-striped" height=5>
+									 <thead>
+										 <tr style="">
+										 		<td width=1><input type="checkbox" name="checkAll" id="checkAll" /></td>
+											 <td width=1>ID</td>
+											 <td>Adnotacje</td>
+											 <td>Głębokość analizy</td>
+											 <td>Status raportu</td>
+											 <td>Status raportu - informacje</td>
+										 </tr>
+									 </thead>
+									 <tbody>
+					';
+
+		foreach ($items as $key => $row) {
+				$view .= '<tr>
+				<td><input type="checkbox" name="prID[]" value="'.$row['ID'].'" onClick="checkAll()"/></td>
+								<td align="right">'.$row["ID"].'</td>
+								<td align="right">'.$row["L_APPOITMENT_INFO"].'</td>
+								<td align="right">'.$row["BI_analiza_depth"].'</td>
+								<td align="right">'.$row["FILE_STATUS"].'</td>
+								<td align="right">'.$row["FILE_STATUS_info"].'</td>';
+		}
+		$view .= '</tbody></table></form>';
+
+
+		return $view;
+}
+
+
+
+
+	public function fetchTestKrsAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchTestKrsAjax')); // , $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function fetchTestKrsAjax($args) {
+		$id = V::get('ID', 1, $_REQUEST, 'int');
+		$items = ACL::getAclByNamespace('default_db/BI_audit_KRS/BI_audit_KRS')->buildQuery([
+			'cols' => [ // TODO:? propertyName = []
+				'A_kod',
+				'A_kraj',
+				'A_miejscowosc',
+				'A_nrDomu',
+				'A_nrLokalu',
+				'A_poczta',
+				'A_ulica',
+				'ID',
+				'S_gmina',
+				'S_kraj',
+				'S_miejscowosc',
+				'S_powiat',
+				'S_wojewodztwo',
+				'dataDokumentu',
+				'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
+				'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
+				'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
+				'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
+				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
+				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
+				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
+				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
+				'krs',
+				'nazwa',
+				'nip',
+				'regon',
+			],
+			'f_ID' => "{$id}",
+		])->getItems([
+			'limit' => 10
+		]);
+
+		return [
+			'type' => 'success',
+			'msg' => 'KRS',
+			'__req_args' => $_REQUEST,
+			'__args' => $args,
+			'body' => [
+				'items' => $items,
+			]
+		];
+	}
+
+	public function fetchTestCeidgAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchTestCeidgAjax')); // , $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function fetchTestCeidgAjax($args) {
+		$id = V::get('ID', 0, $_REQUEST, 'int');
+		$items = ACL::getAclByNamespace('default_db/BI_audit_CEIDG/BI_audit_CEIDG')->buildQuery([
+			'cols' => [ // TODO:? propertyName = []
+				'ID',
+				'budynek',
+				'firma',
+				'gmina',
+				'identyfikatorWpisu',
+				'imie',
+				'kodPocztowy',
+				'kraj',
+				'lokal',
+				'miejscowosc',
+				'nazwisko',
+				'nip',
+				'poczta',
+				'powiat',
+				'regon',
+				'ulica',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/ID',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/budynek',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/gmina',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/kodPocztowy',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/lokal',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/miejscowosc',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/nazwa',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/nip',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/poczta',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/powiat',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/ulica',
+				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/wojewodztwo',
+				'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/ID',
+				'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/nip',
+				'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/regon',
+			],
+			// 'f_ID' => $id,
+		])->getItems([
+			'limit' => 10
+		]);
+
+		return [
+			'type' => 'success',
+			'msg' => 'CEIDG',
+			'__req_args' => $_REQUEST,
+			'__args' => $args,
+			'body' => [
+				'items' => $items,
+			]
+		];
+	}
+
+	function fetchLastReportsAjaxAction() { Response::sendTryCatchJson([ $this, 'fetchLastReportsAjax' ], $args = 'JSON_FROM_REQUEST_BODY'); }
+	function fetchLastReportsAjax() {
+		$refRaportToPracownicyConfig = ACL::getRefConfig(
+			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY'
+		);
+		$refRaportToKontrahenciConfig = ACL::getRefConfig(
+			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI'
+		);
+		$refRaportToPzostaleOdConfig = ACL::getRefConfig(
+			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			$fieldTypeName = 'default_db__x3A__BI_audit_POWIAZANIA_OD:BI_audit_POWIAZANIA_OD'
+		);
+		$refRaportToPzostaleDoConfig = ACL::getRefConfig(
+			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			$fieldTypeName = 'default_db__x3A__BI_audit_POWIAZANIA_DO:BI_audit_POWIAZANIA_DO'
+		);
+		$items = DB::getPDO()->fetchAll("
+			select r.ID as id
+				, r.L_APPOITMENT_INFO as adnotacje
+				, (select count(1) from `{$refRaportToPracownicyConfig->tableName}`  as prRef  where prRef.PRIMARY_KEY  = r.ID and prRef.A_STATUS  not in ('DELETED')) as totalPracownicy
+				, (select count(1) from `{$refRaportToKontrahenciConfig->tableName}` as comRef where comRef.PRIMARY_KEY = r.ID and comRef.A_STATUS not in ('DELETED')) as totalKontrahenci
+				, (select count(1) from `{$refRaportToPzostaleOdConfig->tableName}`  as odRef  where odRef.PRIMARY_KEY  = r.ID and odRef.A_STATUS  not in ('DELETED')) as totalPozostaleOd
+				, (select count(1) from `{$refRaportToPzostaleDoConfig->tableName}`  as doRef  where doRef.PRIMARY_KEY  = r.ID and doRef.A_STATUS  not in ('DELETED')) as totalPozostaleDo
+			from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` as r
+			order by r.ID DESC
+			limit 10
+		");
+		return [
+			'type' => 'success',
+			'msg' => 'ostatnie raporty',
+			'body' => [
+				'items' => $items,
+			],
+		];
+	}
+	function fetchPracownicyIdsByReportAjaxAction() { Response::sendTryCatchJson([ $this, 'fetchPracownicyIdsByReportAjax' ], $args = 'JSON_FROM_REQUEST_BODY'); }
+	function fetchPracownicyIdsByReportAjax($args) {
+		$id = V::get('id', 0, $args);
+		if ($id <= 0) throw new HttpException("Missing id", 400);
+		$refConf = ACL::getRefConfig(
+			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY'
+		);
+		$items = DB::getPDO()->fetchAll("
+			select REMOTE_PRIMARY_KEY
+			from `{$refConf->tableName}`
+			where PRIMARY_KEY = :id
+				and A_STATUS not in ('DELETED')
+		", [ ':id' => $id ]);
+		return [
+			'type' => 'success',
+			'msg' => 'kontrahenci ids',
+			'body' => [
+				'ids' => array_map( V::makePick('REMOTE_PRIMARY_KEY'), $items ),
+			],
+		];
+	}
+	function fetchKontrahenciIdsByReportAjaxAction() { Response::sendTryCatchJson([ $this, 'fetchKontrahenciIdsByReportAjax' ], $args = 'JSON_FROM_REQUEST_BODY'); }
+	function fetchKontrahenciIdsByReportAjax($args) {
+		$id = V::get('id', 0, $args);
+		if ($id <= 0) throw new HttpException("Missing id", 400);
+		$refConf = ACL::getRefConfig(
+			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI'
+		);
+		$items = DB::getPDO()->fetchAll("
+			select REMOTE_PRIMARY_KEY
+			from `{$refConf->tableName}`
+			where PRIMARY_KEY = :id
+				and A_STATUS not in ('DELETED')
+		", [ ':id' => $id ]);
+		return [
+			'type' => 'success',
+			'msg' => 'kontrahenci ids',
+			'body' => [
+				'ids' => array_map( V::makePick('REMOTE_PRIMARY_KEY'), $items ),
+			],
+		];
+	}
+
+
+	public function fetchKontrahenciIdsAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchKontrahenciIdsAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function fetchKontrahenciIdsAjax($args) {
+		$idGroup = V::get('filter_idGroup', 0, $args, 'int');
+		if ($idGroup < 0) $idGroup = 0;
+		$backRefFilter = [];
+		if ($idGroup > 0) {
+			$backRefFilter['__backRef'] = [
+				'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+				'primaryKey' => $idGroup,
+				'fieldName' => 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+			];
+		}
+
+		$searchParams = []; // TODO: ???
+
+		$filtersParams = [];
+		$fieldFilterKeys = array_filter(array_keys($args), function ($key) {
+			return ('f_' === substr($key, 0, 2));
+		});
+		foreach ($fieldFilterKeys as $key) {
+			$filtersParams[ $key ] = '%' . $args[ $key ] . '%';
+		}
+
+		$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
+		$query = $acl->buildQuery(array_merge([
+			'cols' => [
+				'ID',
+			],
+			//'f_ID' => $id,
+			'limit' => 0,
+			// 'limitstart' => $limitstart, // offset
+			// 'order_by' => 'ID', // sortowanie po kolumnie
+			// 'order_dir' => 'DESC', // kierunek sortowania
+			// 'f_nip' = "=12345", // szukamy dokładnie tej wartości - mysql: where nip = "12345"
+			// 'f_nip' = "12345", // szukamy dokładnie tej wartości - mysql: where nip like "%12345%"
+			// 'f_nip' = "12345%", // szukamy dokładnie tej wartości - mysql: where nip like "12345%"
+			// 'f_ID' = "=12345", // szukamy dokładnie tej wartości - mysql: where ID = "12345"
+		], $searchParams, $filtersParams, $backRefFilter));
+		// $total = $query->getTotal();
+		$items = $query->getItems();
+
+		return [
+			'type' => 'success',
+			'msg' => 'kontrahenci ids',
+			'body' => [
+				'ids' => array_map( V::makePick('ID'), $items ),
+			],
+			'__DBG_args' => $args,
+			'__DBG_$idGroup' => $idGroup,
+			'__DBG_$filtersParams' => $filtersParams,
+			'__DBG_$backRefFilter' => $backRefFilter,
+		];
+	}
+	/**
+	 * KONTRAHENCI
+	 */
+	public function fetchKontrahenciAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchKontrahenciAjax'), $args = $_REQUEST);
+	}
+	public function fetchKontrahenciAjax($args) {
+		$idGroup = V::get('filterIdGroup', 0, $args, 'int'); // TODO: dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
+		if ($idGroup < 0) $idGroup = 0;
+
+		$limit = 20;
+
+		$limitstart = V::get('limitstart', 0, $args, 'int');
+		if ($limitstart < 0) $limitstart = 0;
+
+		$page = V::get('page', 0, $args, 'int');
+		$limitstart = ($page - 1) * $limit;
+
+		$search = V::get('search', '', $args);
+		$searchParams = [];
+		if (!empty($search)) {
+			$ogcSearch = "*{$search}*"; // wildCard="*" -> mysql '%'
+			$searchParams['ogc:Filter'] = '
+				<ogc:Filter>
+			    <ogc:Or>
+			      <ogc:PropertyIsLike wildCard="" singleChar="%23" escapeChar="!">
+			        <ogc:PropertyName>NIP</ogc:PropertyName>
+			        <ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+			      </ogc:PropertyIsLike>
+			      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+			        <ogc:PropertyName>Nazwa_grupy_kapitalowej</ogc:PropertyName>
+							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+			      </ogc:PropertyIsLike>
+			      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+			        <ogc:PropertyName>Pelna_nazwa_kontrahenta</ogc:PropertyName>
+							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+			      </ogc:PropertyIsLike>
+			    </ogc:Or>
+			  </ogc:Filter>
+			';
+		}
+// ogc filter w środku ogcand potem ogcnot potem PropertyIsEqualTo
+		$backRefFilter = [];
+		if ($idGroup > 0) {
+			$backRefFilter['__backRef'] = [
+				'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+				'primaryKey' => $idGroup,
+				'fieldName' => 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+			];
+			// - ID
+			// - ID_USER - id usera który stworzył grupę (tylko dla niego będzie widoczna)
+			// - NAZWA - nazwa grupy
+			// - 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_KONTRAHENCI' minOccurs="0" maxOccurs="unbounded"
+		}
+
+		$filtersParams = [];
+		$fieldFilterKeys = array_filter(array_keys($args), function ($key) {
+			return ('f_' === substr($key, 0, 2));
+		});
+		foreach ($fieldFilterKeys as $key) {
+			$filtersParams[ $key ] = '%' . $args[ $key ] . '%';
+		}
+		DBG::log($filtersParams, 'Kontrahenci $filtersParams');
+		$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
+		$query = $acl->buildQuery(array_merge([
+			'cols' => [ // TODO:? propertyName = []
+								'ID',
+								'Nazwa_grupy_kapitalowej',
+								'Pelna_nazwa_kontrahenta',
+								'Numer_kontrahenta',
+								'Skrocona_Nazwa_Kontrahenta',
+								'Typ_kontrahenta',
+								'NIP',
+								'KRS',
+								'REGON',
+								'PESEL',
+					 			'Forma_prawna_dzialalnosci',
+					 			'Ulica',
+					 			'Numer_budynku',
+					 			'Numer_mieszkania_lokalu',
+					 			'Miejscowosc',
+								'Kod_pocztowy',
+								'Kraj',
+								'Telefon',
+								'Fax',
+								'Mail',
+								'A_ADM_COMPANY',
+								'A_CLASSIFIED',
+								'Dodano',
+								'Podmiot_dominujacy',
+								'Tytul_dokumentu',
+								'ownCompany',
+								'uwagi',
+			],
+			//'f_ID' => $id,
+			'limit' => $limit,
+			'limitstart' => $limitstart, // offset
+			'order_by' => 'ID', // sortowanie po kolumnie
+			'order_dir' => 'DESC', // kierunek sortowania
+		], $searchParams, $filtersParams, $backRefFilter));
+		$total = $query->getTotal();
+		$items = $query->getItems();
+
+		$pagination = array();
+		$pagination['total_items'] = $total;
+		$pagination['size'] = ceil($total/$limit); // pages size
+		$pagination['current'] = $page;
+		$pagination['limit'] = $limit;
+		if ($idGroup > 0) $pagination['filter_idGroup'] = $idGroup;
+
+		return [
+			'type' => 'success',
+			'msg' => 'showKontrajenci',
+			'body' => [
+				'items' => $items,
+				//'view' => $this->htmlViewFormBiAudit($items, 'KONTRAHENCI'),
+				'pagination' => $pagination
+			],
+			'__DBG_args' => $args,
+			'__DBG_$idGroup' => $idGroup,
+			'__DBG_$filtersParams' => $filtersParams,
+			'__DBG_$backRefFilter' => $backRefFilter,
+		];
+	}
+
+
+	public function fetchFromBazaAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchFromBazaAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function fetchFromBazaAjax($args) {
+		$baza = V::get('baza', '', $args);
+		$query = V::get('query', '', $args);
+		$query = trim(trim($query), '0');
+		if (strlen($query) < 3) throw new Exception("Query must be more then 2 chars");
+
+		$wordsQuery = [];
+		if (false !== strpos($query, ' ')) {
+			$words = explode(' ', $query);
+			DBG::log($words, 'array', "\$words from \$query({$query}) - 1");
+			$words = array_map(function ($word) {
+				return trim(trim($word), '0');
+			}, $words);
+			DBG::log($words, 'array', "\$words from \$query({$query}) - 2");
+			$words = array_filter($words, function ($word) {
+				return (strlen($word) > 2);
+			});
+			DBG::log($words, 'array', "\$words from \$query({$query}) - 3");
+			if (empty($words)) throw new Exception("Query words must be more then 2 chars");
+			$wordsQuery = $words;
+		} else {
+			$wordsQuery[] = $query;
+		}
+
+		switch ($baza) {
+			case 'default_db/BI_audit_KRS/BI_audit_KRS': return $this->fetchFromKRS($wordsQuery);
+			case 'default_db/BI_audit_KRS_person/BI_audit_KRS_person': return $this->fetchFromKRSPerson($wordsQuery);
+			case 'default_db/BI_audit_MSIG/BI_audit_MSIG': return $this->fetchFromMSIG($wordsQuery);
+			case 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person': return $this->fetchFromMSIGPerson($wordsQuery);
+			case 'default_db/BI_audit_taxpayer/BI_audit_taxpayer': return $this->fetchFromVATp($wordsQuery);
+			case 'default_db/BI_audit_CEIDG/BI_audit_CEIDG': return $this->fetchFromCEIDG($wordsQuery);
+			default: throw new Exception("Unsupported database");
+		}
+	}
+	function generateOgcFilterFromWords($wordsQuery, $searchableFields) {
+		return '<ogc:Filter><ogc:And>' .
+			implode("\n", array_map(function ($word) use ($searchableFields) {
+				return '<ogc:Or>' . implode("\n", array_map(function ($fieldName) use ($word) {
+					return '<ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+						<ogc:PropertyName>' . $fieldName . '</ogc:PropertyName>
+						<ogc:Literal>' . "*{$word}*" . '</ogc:Literal>
+					</ogc:PropertyIsLike>';
+				}, $searchableFields)) . '</ogc:Or>';
+			}, $wordsQuery)) .
+		'</ogc:And></ogc:Filter>';
+	}
+	function fetchFromKRS($wordsQuery) {
+		$query = implode(" ", $wordsQuery);
+		if (empty($wordsQuery)) throw new Exception("Empty search");
+		$searchableFields = [];
+		$searchableFields[] = 'nazwa';
+		$searchableFields[] = 'nip';
+		$searchableFields[] = 'krs';
+		$searchableFields[] = 'regon';
+		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
+		$items = ACL::getAclByNamespace('default_db/BI_audit_KRS/BI_audit_KRS')->buildQuery(array_merge([
+			'cols' => [ // TODO:? propertyName = []
+				'A_kod',
+				'A_kraj',
+				'A_miejscowosc',
+				'A_nrDomu',
+				'A_nrLokalu',
+				'A_poczta',
+				'A_ulica',
+				'ID',
+				// 'S_gmina',
+				'S_kraj',
+				'S_miejscowosc',
+				// 'S_powiat',
+				'S_wojewodztwo',
+				// 'dataDokumentu',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
+				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
+				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
+				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
+				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
+				'krs',
+				'nazwa',
+				'nip',
+				'regon',
+			],
+			// 'f_ID' => "{$id}",
+		], $searchParams))->getItems([
+			'limit' => 10
+		]);
+		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");
+
+		return [
+			'type' => 'success',
+			'msg' => 'KRS',
+			'__args' => $args,
+			'body' => [
+				'items' => array_map(function ($item) {
+					$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
+					$nazwa = str_replace("SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ", "Sp. z o.o.", $nazwa);
+					$item['nazwa'] = $nazwa;
+					$item['label'] = "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}";
+					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+
+					return $item;
+
+					// return [
+					// 	'ID' => $item['ID'],
+					// 	'nazwa' => $shortNazwa,
+					// 	'nip' => $item['nip'],
+					// 	'krs' => $item['krs'],
+					// 	'regon' => $item['regon'],
+					// 	'S_miejscowosc' => $item['S_miejscowosc'],
+					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+					// ];
+				}, $items),
+			]
+		];
+	}
+
+	function fetchFromKRSPerson($wordsQuery) {
+		$query = implode(" ", $wordsQuery);
+		if (empty($wordsQuery)) throw new Exception("Empty search");
+		$searchableFields = [];
+		$searchableFields[] = 'nazwisko';
+		$searchableFields[] = 'imiona';
+		$searchableFields[] = 'pesel';
+		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
+		$items = ACL::getAclByNamespace('default_db/BI_audit_KRS_person/BI_audit_KRS_person')->buildQuery(array_merge([
+			'cols' => [ // TODO:? propertyName = []
+				'nazwisko',
+				'imiona',
+				'pesel',
+				'ID',
+				// 'dataDokumentu',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
+				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
+				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
+				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
+				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
+			],
+			// 'f_ID' => "{$id}",
+		], $searchParams))->getItems([
+			'limit' => 10
+		]);
+		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");
+
+		return [
+			'type' => 'success',
+			'msg' => 'KRS person',
+			'__args' => $args,
+			'body' => [
+				'items' => array_map(function ($item) {
+					//$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
+					//$nazwa = $item['nazwisko'];
+					//$item['nazwa'] = $nazwa;
+					$item['label'] = "{$item['nazwisko']}, {$item['imiona']}, {$item['pesel']}";
+					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+
+					return $item;
+
+					// return [
+					// 	'ID' => $item['ID'],
+					// 	'nazwa' => $shortNazwa,
+					// 	'nip' => $item['nip'],
+					// 	'krs' => $item['krs'],
+					// 	'regon' => $item['regon'],
+					// 	'S_miejscowosc' => $item['S_miejscowosc'],
+					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+					// ];
+				}, $items),
+			]
+		];
+	}
+
+	function fetchFromVATp($query){
+			$ogcSearch = "*{$query}*";
+			$searchParams = [];
+			$searchParams['ogc:Filter'] = '
+				<ogc:Filter>
+					<ogc:Or>
+						<ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+							<ogc:PropertyName>nazwisko</ogc:PropertyName>
+							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+						</ogc:PropertyIsLike>
+						<ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+							<ogc:PropertyName>imiona</ogc:PropertyName>
+							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+						</ogc:PropertyIsLike>
+						<ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+							<ogc:PropertyName>pesel</ogc:PropertyName>
+							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+						</ogc:PropertyIsLike>
+					</ogc:Or>
+				</ogc:Filter>
+			';
+			$items = ACL::getAclByNamespace('default_db/BI_audit_taxpayer/BI_audit_taxpayer')->buildQuery(array_merge([
+				'cols' => [ // TODO:? propertyName = []
+					'nip',
+					'ID',
+					// 'dataDokumentu',
+					// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
+					// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
+					// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
+					// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
+					// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
+					// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
+					// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
+					// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
+				],
+				// 'f_ID' => "{$id}",
+			], $searchParams))->getItems([
+				'limit' => 10
+			]);
+			DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");
+
+			return [
+				'type' => 'success',
+				'msg' => 'KRS person',
+				'__args' => $args,
+				'body' => [
+					'items' => array_map(function ($item) {
+						//$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
+						//$nazwa = $item['nazwisko'];
+						//$item['nazwa'] = $nazwa;
+						$item['label'] = "{$item['nip']}";
+						// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+
+						return $item;
+
+						// return [
+						// 	'ID' => $item['ID'],
+						// 	'nazwa' => $shortNazwa,
+						// 	'nip' => $item['nip'],
+						// 	'krs' => $item['krs'],
+						// 	'regon' => $item['regon'],
+						// 	'S_miejscowosc' => $item['S_miejscowosc'],
+						// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+						// ];
+					}, $items),
+				]
+			];
+		}
+
+	function fetchFromMSIG($wordsQuery) {
+		$query = implode(" ", $wordsQuery);
+		if (empty($wordsQuery)) throw new Exception("Empty search");
+		$searchableFields = [];
+		$searchableFields[] = 'nazwa';
+		$searchableFields[] = 'krs';
+		$searchableFields[] = 'nip';
+		$searchableFields[] = 'regon';
+		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
+		$items = ACL::getAclByNamespace('default_db/BI_audit_MSIG/BI_audit_MSIG')->buildQuery(array_merge([
+			'cols' => [ // TODO:? propertyName = []
+				'A_kod',
+				'A_kraj',
+				'A_miejscowosc',
+				'A_nrDomu',
+				'A_nrLokalu',
+				'A_poczta',
+				'A_ulica',
+				'ID',
+				// 'S_gmina',
+				'S_kraj',
+				'S_miejscowosc',
+				// 'S_powiat',
+				'S_wojewodztwo',
+				// 'dataDokumentu',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
+				'default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person/ID',
+				'default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person/imiona',
+				'default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person/nazwisko',
+				'default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person/pesel',
+				'krs',
+				'nazwa',
+				'nip',
+				'regon',
+			],
+			// 'f_ID' => "{$id}",
+		], $searchParams))->getItems([
+			'limit' => 10
+		]);
+		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");
+
+		return [
+			'type' => 'success',
+			'msg' => 'MSIG',
+			'__args' => $args,
+			'body' => [
+				'items' => array_map(function ($item) {
+					$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
+					$nazwa = str_replace([ '„', '”' ], '', $item['nazwa']);
+					$nazwa = str_replace("SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ", " Sp. z o.o.", $nazwa);
+					$item['nazwa'] = $nazwa;
+					$item['label'] = "{$nazwa}, " . implode(", ", array_filter([
+						$item['A_miejscowosc'],
+						$item['krs'],
+						$item['nip'],
+						$item['regon']
+					], [ 'V', 'filterNotEmpty' ]));
+					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+
+					return $item;
+
+					// return [
+					// 	'ID' => $item['ID'],
+					// 	'nazwa' => $shortNazwa,
+					// 	'nip' => $item['nip'],
+					// 	'krs' => $item['krs'],
+					// 	'regon' => $item['regon'],
+					// 	'S_miejscowosc' => $item['S_miejscowosc'],
+					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+					// ];
+				}, $items),
+			]
+		];
+	}
+
+	function fetchFromMSIGPerson($wordsQuery) {
+		$query = implode(" ", $wordsQuery);
+		if (empty($wordsQuery)) throw new Exception("Empty search");
+		$searchableFields = [];
+		$searchableFields[] = 'nazwisko';
+		$searchableFields[] = 'imiona';
+		$searchableFields[] = 'pesel';
+		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
+		$items = ACL::getAclByNamespace('default_db/BI_audit_MSIG_person/BI_audit_MSIG_person')->buildQuery(array_merge([
+			'cols' => [ // TODO:? propertyName = []
+				'nazwisko',
+				'imiona',
+				'pesel',
+				'ID',
+				// 'dataDokumentu',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
+				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
+				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
+				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
+				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
+				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
+			],
+			// 'f_ID' => "{$id}",
+		], $searchParams))->getItems([
+			'limit' => 10
+		]);
+		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");
+
+		return [
+			'type' => 'success',
+			'msg' => 'MSIG',
+			'__args' => $args,
+			'body' => [
+				'items' => array_map(function ($item) {
+					//$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
+					//$nazwa = str_replace("SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ", "Sp. z o.o.", $nazwa);
+					//$item['nazwa'] = $nazwa;
+					$item['label'] = "{$item['nazwisko']}, {$item['imiona']}, {$item['pesel']}";
+					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+
+					return $item;
+
+					// return [
+					// 	'ID' => $item['ID'],
+					// 	'nazwa' => $shortNazwa,
+					// 	'nip' => $item['nip'],
+					// 	'krs' => $item['krs'],
+					// 	'regon' => $item['regon'],
+					// 	'S_miejscowosc' => $item['S_miejscowosc'],
+					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+					// ];
+				}, $items),
+			]
+		];
+	}
+
+	function fetchFromCEIDG($wordsQuery) {
+		$query = implode(" ", $wordsQuery);
+		if (empty($wordsQuery)) throw new Exception("Empty search");
+		$searchableFields = [];
+		$searchableFields[] = 'firma';
+		$searchableFields[] = 'nazwisko';
+		$searchableFields[] = 'imie';
+		$searchableFields[] = 'nip';
+		$searchableFields[] = 'regon';
+		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
+		$items = ACL::getAclByNamespace('default_db/BI_audit_CEIDG/BI_audit_CEIDG')->buildQuery(array_merge([
+			'cols' => [ // TODO:? propertyName = []
+				'ID',
+				'budynek',
+				'firma',
+				'gmina',
+				'identyfikatorWpisu',
+				'imie',
+				'kodPocztowy',
+				'kraj',
+				'lokal',
+				'miejscowosc',
+				'nazwisko',
+				'nip',
+				'poczta',
+				'powiat',
+				'regon',
+				'ulica',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/ID',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/budynek',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/gmina',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/kodPocztowy',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/lokal',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/miejscowosc',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/nazwa',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/nip',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/poczta',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/powiat',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/ulica',
+				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/wojewodztwo',
+				// 'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/ID',
+				// 'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/nip',
+				// 'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/regon',
+			],
+			// 'f_ID' => "{$id}",
+		], $searchParams))->getItems([
+			'limit' => 10
+		]);
+		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");
+
+		return [
+			'type' => 'success',
+			'msg' => 'CEIDG',
+			'__args' => $args,
+			'body' => [
+				'items' => array_map(function ($item) {
+					//$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
+					//$nazwa = str_replace("SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ", "Sp. z o.o.", $nazwa);
+					//$item['nazwa'] = $nazwa;
+					$item['label'] = "{$item['firma']} {$item['imie']} {$item['nazwisko']}, {$item['miejscowosc']}, {$item['nip']}, {$item['regon']}";
+					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+
+					return $item;
+
+					// return [
+					// 	'ID' => $item['ID'],
+					// 	'nazwa' => $shortNazwa,
+					// 	'nip' => $item['nip'],
+					// 	'krs' => $item['krs'],
+					// 	'regon' => $item['regon'],
+					// 	'S_miejscowosc' => $item['S_miejscowosc'],
+					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
+					// ];
+				}, $items),
+			]
+		];
+	}
+
+
+	public function showTableKontrahenci($labels = []) {
+		// TODO: use self::$FIELD_LIST_KONTRAHENCI
+		$view = '<form class="form-horizontal" method="post">
+						<table class="table table-bordered table-hover table-striped" height=5>
+									 <thead>
+										 <tr>
+												<td width=1><input type="checkbox" name="checkAll" id="checkAll-KONTRAHENCI" /></td>
+												<td width=1>' . V::get('ID', 'ID', $labels) . '</td>
+												<td>' . V::get('Nazwa_grupy_kapitalowej', 'Nazwa grupy kapitalowej', $labels) . '</td>
+												<td>' . V::get('Pelna_nazwa_kontrahenta', 'Pelna nazwa kontrahenta', $labels) . '</td>
+												<td>' . V::get('Numer_kontrahenta', 'Numer kontrahenta', $labels) . '</td>
+												<td>' . V::get('Skrocona_Nazwa_Kontrahenta', 'Skrócona nazwa kontrahenta', $labels) . '</td>
+												<td>' . V::get('Typ_kontrahenta', 'Typ_kontrahenta', $labels) . '</td>
+												<td>' . V::get('NIP', 'NIP', $labels) . '</td>
+												<td>' . V::get('KRS', 'KRS', $labels) . '</td>
+												<td>' . V::get('REGON', 'Regon', $labels) . '</td>
+												<td>' . V::get('PESEL', 'PESEL', $labels) . '</td>
+												<td>' . V::get('Forma_prawna_dzialalnosci', 'Forma prawna działalności', $labels) . '</td>
+												<td>' . V::get('Ulica', 'Ulica', $labels) . '</td>
+												<td>' . V::get('Numer_budynku', 'Numer budynku', $labels) . '</td>
+												<td>' . V::get('Numer_mieszkania_lokalu', 'Numer mieszkania lokalu', $labels) . '</td>
+												<td>' . V::get('Miejscowosc', 'Miejscowosc', $labels) . '</td>
+												<td>' . V::get('Kod_pocztowy', 'Kod pocztowy', $labels) . '</td>
+												<td>' . V::get('Kraj', 'Kraj', $labels) . '</td>
+												<td>' . V::get('Telefon', 'Telefon', $labels) . '</td>
+												<td>' . V::get('Fax', 'Fax', $labels) . '</td>
+												<td>' . V::get('Mail', 'Mail', $labels) . '</td>
+												<td>' . V::get('A_ADM_COMPANY', 'A_ADM_COMPANY', $labels) . '</td>
+												<td>' . V::get('A_CLASSIFIED', 'A_CLASSIFIED', $labels) . '</td>
+												<td>' . V::get('Dodano', 'Dodano', $labels) . '</td>
+												<td>' . V::get('Podmiot_dominujacy', 'Podmiot dominujacy', $labels) . '</td>
+												<td>' . V::get('Tytul_dokumentu', 'Tytul dokumentu', $labels) . '</td>
+												<td>' . V::get('ownCompany', 'ownCompany', $labels) . '</td>
+												<td>' . V::get('uwagi', 'uwagi', $labels) . '</td>
+										 </tr>
+										 <tr>
+											<td style="padding:0" width=1><button style="padding:5px" id="filtersFieldRemoveBtn-KONTRAHENCI" onClick="return removeFiltersKontrahenci(event, this)" title="Kasuj filtry" class="btn btn-xs btn-link glyphicon glyphicon-remove"></button></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:80px" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_ID" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Nazwa_grupy_kapitalowej" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Pelna_nazwa_kontrahenta" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Numer_kontrahenta" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Skrocona_Nazwa_Kontrahenta" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Typ_kontrahenta" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_NIP" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_KRS" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_REGON" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_PESEL" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Forma_prawna_dzialalnosci" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Ulica" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Numer_budynku" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Numer_mieszkania_lokalu" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Miejscowosc" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Kod_pocztowy" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Kraj" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Telefon" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Fax" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Mail" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_A_ADM_COMPANY" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_A_CLASSIFIED" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Dodano" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Podmiot_dominujacy" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Tytul_dokumentu" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_ownCompany" value="" placeholder="%"></td>
+											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_uwagi" value="" placeholder="%"></td>
+										 </tr>
+										 </thead>
+										 <tbody id="body-kontrahenci">
+										 </tbody></table>
+										 </form>
+					';
+
+		return $view;
+	}
+
+	// tworzenie grupy kontrahentów
+	public function createKontrahenciGroupAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'createKontrahenciGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
+	}
+
+	public function createKontrahenciGroupAjax($args) {
+		$nazwa = V::get('NAZWA', '', $args);
+		// TODO: vlaidacja nazwy - sprawdzenie czy już nie występuje
+
+
+		$idGroup = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY_group', [
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+			'NAZWA' => $nazwa,
+			'ID_USER' => User::getID()
+		]);
+
+		return [
+			'msg' => "Utworzona grupę {$idGroup}",
+			'type' => "success",
+			'body' => [
+				'id' => $idGroup,
+				'nazwa' => $nazwa
+			]
+		];
+	}
+
+
+	// Dodanie do grupy filtra kontrahentów
+	public function addKontrahenciToGroupAjaxAction() {
+		 Response::sendTryCatchJson(array($this, 'addKontrahenciToGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
+	}
+	public function addKontrahenciToGroupAjax($args) {
+		$idGroup = V::get('idGroup', '', $args);
+		$type = V::get('type', 'ids', $args);
+		$kontrahenciIds = V::get('kontrahenciIds', '', $args);
+		$filter = V::get('filter', '', $args);
+
+		// validate
+		if (!$idGroup) throw new Exception("Nie wybrano grupa");
+		switch ($type) {
+			case 'ids': {
+				if (!$kontrahenciIds || count($kontrahenciIds) == 0) throw new Exception("Proszę wybrać kontrahentów");
+			} break;
+			case 'filter': {
+				if (!isset($args['filter'])) throw new Exception("Proszę wybrać kontrahentów");
+			} break;
+			default: throw new Exception("Missing type");
+		}
+		$group = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
+			'cols' => [ // TODO:? propertyName = []
+				'ID',
+				'ID_USER',
+				'NAZWA',
+			],
+			// 'f_ID_USER' => User::getID()
+		])->getItem($idGroup);
+		if (!$group) throw new Exception("Grupa nie istnieje");
+		if (User::getID() != $group['ID_USER']) throw new Exception("Brak uprawnień do grupy");
+
+		if ('filter' === $type) {
+			$args__idGroup = V::get('filterIdGroup', 0, $args['filter'], 'int'); // dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
+			if ($args__idGroup < 0) $args__idGroup = 0;
+			$search = V::get('search', '', $args['filter']);
+			$searchParams = [];
+			if (!empty($search)) {
+				$ogcSearch = "*{$search}*"; // wildCard="*" -> mysql '%'
+				$searchParams['ogc:Filter'] = '
+					<ogc:Filter>
+				    <ogc:Or>
+				      <ogc:PropertyIsLike wildCard="" singleChar="%23" escapeChar="!">
+				        <ogc:PropertyName>NIP</ogc:PropertyName>
+				        <ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+				      </ogc:PropertyIsLike>
+				      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+				        <ogc:PropertyName>Nazwa_grupy_kapitalowej</ogc:PropertyName>
+								<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+				      </ogc:PropertyIsLike>
+				      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+				        <ogc:PropertyName>Pelna_nazwa_kontrahenta</ogc:PropertyName>
+								<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+				      </ogc:PropertyIsLike>
+				    </ogc:Or>
+				  </ogc:Filter>
+				';
+			}
+
+			$backRefFilter = [];
+			if ($args__idGroup > 0) {
+				$backRefFilter['__backRef'] = [
+					'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+					'primaryKey' => $args__idGroup,
+					'fieldName' => 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+				];
+			}
+
+			$filtersParams = [];
+			$fieldFilterKeys = array_filter(array_keys($args['filter']), function ($key) {
+				return ('f_' === substr($key, 0, 2));
+			});
+			foreach ($fieldFilterKeys as $key) {
+				$filtersParams[ $key ] = '%' . $args['filter'][ $key ] . '%';
+			}
+
+			$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
+			$query = $acl->buildQuery(array_merge([
+				'cols' => ['ID'],
+			], $searchParams, $filtersParams, $backRefFilter, [
+				'limit' => 0
+			]));
+			$items = $query->getItems();
+
+			$kontrahenciIds = array_map(function ($row) {
+				return $row['ID'];
+			}, $items);
+		}
+
+		ACL::addListRef(
+			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+			$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+			$refPrimaryKey = $idGroup,
+			$refListRemotePrimaryKey = $kontrahenciIds
+		);
+
+		return [
+			'msg' => "Powiązano kontrahentów z grupą {$idGroup}",
+			'type' => "success",
+		];
+	}
+
+	public function removePracownicyFromGroupAjaxAction(){
+		Response::sendTryCatchJson(array($this, 'removePracownicyFromGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
+	}
+	public function removePracownicyFromGroupAjax($args){
+		$idGroup = V::get('idGroup', 0, $args, "int");
+		$pracownicyIds = V::get('pracownicyIds', [], $args, 'array');
+		if ($idGroup === 0){
+			foreach ($pracownicyIds as $pracownikIds) {
+				//TO DO Błąd do naprawienia
+				//TO DO sprawdzanie czy już DELETED
+				$affected = DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $pracownikIds, [
+					'A_STATUS' => 'DELETED',
+					'A_RECORD_UPDATE_DATE' => 'NOW()',
+				  'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
+				]);
+			}
+			return [
+				'msg' => "Usunięto osoby z systemu",
+				'type' => "success",
+			];
+		} else {
+			$group = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
+				'cols' => [ // TODO:? propertyName = []
+					'ID',
+					'ID_USER',
+					'NAZWA',
+				],
+				// 'f_ID_USER' => User::getID()
+			])->getItem($idGroup);
+			if (!$group) throw new Exception("Grupa nie istnieje");
+			if (User::getID() != $group['ID_USER']) throw new Exception("Brak uprawnień do grupy");
+
+			ACL::removeListRef(
+				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+				$refPrimaryKey = $idGroup,
+				$refListRemotePrimaryKey = $pracownicyIds
+			);
+
+			return [
+				'msg' => "Usunięto osoby z grupy {$idGroup}",
+				'type' => "success",
+			];
+		}
+	}
+
+
+	public function removeKontrahenciFromGroupAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'removeKontrahenciFromGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
+	}
+	public function removeKontrahenciFromGroupAjax($args) {
+		$idGroup = V::get('idGroup', 0, $args, "int");
+		$kontrahenciIds = V::get('kontrahenciIds', [], $args, 'array');
+		if ($idGroup === 0) {
+			foreach ($kontrahenciIds as $kontrahentIds) {
+				$affected = DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI', 'ID', $kontrahentIds, [
+					'A_STATUS' => 'DELETED',
+					'A_RECORD_UPDATE_DATE' => 'NOW()',
+				  'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
+				]);
+			}
+			return [
+				'msg' => "Usunięto kontrahentów z systemu",
+				'type' => "success",
+			];
+		} else {
+			$group = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
+				'cols' => [ // TODO:? propertyName = []
+					'ID',
+					'ID_USER',
+					'NAZWA',
+				],
+				// 'f_ID_USER' => User::getID()
+			])->getItem($idGroup);
+			if (!$group) throw new Exception("Grupa nie istnieje");
+			if (User::getID() != $group['ID_USER']) throw new Exception("Brak uprawnień do grupy");
+
+			ACL::removeListRef(
+				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+				$refPrimaryKey = $idGroup,
+				$refListRemotePrimaryKey = $kontrahenciIds
+			);
+
+			return [
+				'msg' => "Usunięto kontrahentów z grupy {$idGroup}",
+				'type' => "success",
+			];
+		}
+	}
+
+
+	public function fetchGroupKontrahenciAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchGroupKontrahenciAjax'));
+	}
+	public function fetchGroupKontrahenciAjax() {
+		$query = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
+			'cols' => [ // TODO:? propertyName = []
+				'ID',
+				'ID_USER',
+				'NAZWA',
+			],
+			'f_ID_USER' => "=" . User::getID(),
+			'f_A_STATUS' => "!DELETED",
+		]);
+		$itemsKontrahenci = $query->getItems();
+		if (empty($itemsKontrahenci)) throw new AlertWarningException("Grupy nie istnieją");
+
+		$arrayGroupKontrahenci = array();
+		foreach ($itemsKontrahenci as $item) {
+			// if (User::getID() != $item['ID_USER']) throw new Exception("Brak uprawnień do grupy");
+			$arrayGroupKontrahenci[] = [
+				'NAZWA' => $item['NAZWA'],
+				'ID' => $item['ID'],
+			];
+		}
+
+		return [
+			'type' => 'success',
+			'msg' => 'fetchGroupKontrahenciAjax',
+			'__req_args' => $_REQUEST,
+			'__args' => $args,
+			'body' => [
+				'itemsGroupKontrahenci' => $arrayGroupKontrahenci
+			]
+		];
+	}
+
+
+	public function fetchPracownicyIdsAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchPracownicyIdsAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+ 	public function fetchPracownicyIdsAjax($args) {
+		$idGroup = V::get('filter_idGroup', 0, $args, 'int');
+		if ($idGroup < 0) $idGroup = 0;
+		$backRefFilter = [];
+		if ($idGroup > 0) {
+			$backRefFilter['__backRef'] = [
+				'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+				'primaryKey' => $idGroup,
+				'fieldName' => 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+			];
+		}
+
+		$searchParams = []; // TODO: ???
+
+		$filtersParams = [];
+		$fieldFilterKeys = array_filter(array_keys($args), function ($key) {
+			return ('f_' === substr($key, 0, 2));
+		});
+		foreach ($fieldFilterKeys as $key) {
+			$filtersParams[ $key ] = '%' . $args[ $key ] . '%';
+		}
+
+		$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
+		$query = $acl->buildQuery(array_merge([
+			'cols' => [
+				'ID',
+			],
+			//'f_ID' => $id,
+			'limit' => 0,
+			// 'limitstart' => $limitstart, // offset
+			// 'order_by' => 'ID', // sortowanie po kolumnie
+			// 'order_dir' => 'DESC', // kierunek sortowania
+			// 'f_nip' = "=12345", // szukamy dokładnie tej wartości - mysql: where nip = "12345"
+			// 'f_nip' = "12345", // szukamy dokładnie tej wartości - mysql: where nip like "%12345%"
+			// 'f_nip' = "12345%", // szukamy dokładnie tej wartości - mysql: where nip like "12345%"
+			// 'f_ID' = "=12345", // szukamy dokładnie tej wartości - mysql: where ID = "12345"
+		], $searchParams, $filtersParams, $backRefFilter));
+		// $total = $query->getTotal();
+		$items = $query->getItems();
+
+		return [
+			'type' => 'success',
+			'msg' => 'pracownicy ids',
+			'body' => [
+				'ids' => array_map( V::makePick('ID'), $items ),
+			],
+			'__args' => $args,
+			'__DBG_$idGroup' => $idGroup,
+			'__DBG_$filtersParams' => $filtersParams,
+			'__DBG_$backRefFilter' => $backRefFilter,
+		];
+	}
+	/*
+	 * PRACOWNICY
+	 */
+	public function fetchPracownicyAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchPracownicyAjax'), $args = $_REQUEST);
+	}
+	public function fetchPracownicyAjax($args) {
+
+		$idGroup = V::get('filterIdGroup', 0, $args, 'int'); // dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
+		if ($idGroup < 0) $idGroup = 0;
+
+		$limit = 20;
+
+		$page = V::get('page', 0, $args, 'int');
+		$limitstart = ($page - 1) * $limit;
+
+		$search = V::get('search', '', $args);
+		$searchParams = [];
+		if (!empty($search)) {
+			$ogcSearch = "*{$search}*"; // wildCard="*" -> mysql '%'
+			$searchParams['ogc:Filter'] = '
+				<ogc:Filter>
+			    <ogc:Or>
+			      <ogc:PropertyIsLike wildCard="" singleChar="%23" escapeChar="!">
+			        <ogc:PropertyName>nip</ogc:PropertyName>
+			        <ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+			      </ogc:PropertyIsLike>
+			      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+			        <ogc:PropertyName>nazwisko</ogc:PropertyName>
+							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+			      </ogc:PropertyIsLike>
+			    </ogc:Or>
+			  </ogc:Filter>
+			';
+		}
+
+		$backRefFilter = [];
+		if ($idGroup > 0) {
+			$backRefFilter['__backRef'] = [
+				'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+				'primaryKey' => $idGroup,
+				'fieldName' => 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+			];
+		}
+
+		$filtersParams = [];
+		$fieldFilterKeys = array_filter(array_keys($args), function ($key) {
+			return ('f_' === substr($key, 0, 2));
+		});
+		foreach ($fieldFilterKeys as $key) {
+			if ('f_ID' === $key) $filtersParams[ $key ] = '=' . $args[ $key ];
+			else $filtersParams[ $key ] = '%' . $args[ $key ] . '%';
+		}
+
+		$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
+		$query = $acl->buildQuery(array_merge([
+			'cols' => array_merge(self::$FIELD_LIST_PRACOWNICY, [
+				'default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy/*'
+			]),
+			//'f_ID' => $id,
+			'limit' => $limit,
+			'limitstart' => $limitstart, // offset
+			'order_by' => 'ID', // sortowanie po kolumnie
+			'order_dir' => 'DESC', // kierunek sortowania
+			// 'f_nip' = "=12345", // szukamy dokładnie tej wartości - mysql: where nip = "12345"
+			// 'f_nip' = "12345", // szukamy dokładnie tej wartości - mysql: where nip like "%12345%"
+			// 'f_nip' = "12345%", // szukamy dokładnie tej wartości - mysql: where nip like "12345%"
+			// 'f_ID' = "=12345", // szukamy dokładnie tej wartości - mysql: where ID = "12345"
+		], $searchParams, $filtersParams, $backRefFilter));
+		$total = $query->getTotal();
+		$items = $query->getItems();
+
+		$pagination = array();
+		$pagination['total_items'] = $total;
+		$pagination['size'] = ceil($total/$limit); // pages size
+		$pagination['current'] = $page;
+		$pagination['limit'] = $limit;
+		// $idGroup = V::get('filterIdGroup', 0, $_REQUEST, 'int'); // TODO: dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
+		if ($idGroup > 0) $pagination['filter_idGroup'] = $idGroup;
+
+		// { // tworzenie własnego zapytanie mysql
+		// 	$rootTableName = $acl->getRootTableName();
+		// 	DB::getPDO()->fetchAll("
+		// 		select t.*
+		// 		from {$rootTableName} t
+		// 		where t.ID in (
+		// 			select x.ID
+		// 			from ... x
+		// 			where
+		// 		)
+		// 	");
+		// }
+
+		return [
+			'type' => 'success',
+			'msg' => 'showPracownicy',
+			'body' => [
+				'items' => $items,
+				//'view' => $this->htmlViewFormBiAudit($items, 'PRACOWNICY'),
+				'pagination' => $pagination
+			],
+			'__DBG_$idGroup' => $idGroup,
+			'__DBG_$filtersParams' => $filtersParams,
+			'__DBG_$backRefFilter' => $backRefFilter,
+		];
+	}
+
+
+
+	public function showTablePracownicy($labels = []) {
+		// TODO: use self::$FIELD_LIST_PRACOWNICY
+			$view = '<form class="form-horizontal" method="post">
+							<table class="table table-responsive table-bordered table-hover table-striped" height=5>
+										 <thead>
+											 <tr>
+											 		<td width=1><input type="checkbox" name="checkAll" id="checkAll-PRACOWNICY" /></td>
+													<td width=1>' . V::get('ID', 'ID', $labels) . '</td>
+													<td>' . V::get('imiona', 'Imię/Imiona', $labels) . '</td>
+													<td>' . V::get('nazwisko', 'Nazwisko', $labels) . '</td>
+													<td>' . V::get('nip', 'NIP', $labels) . '</td>
+													<td>' . V::get('pesel', 'Pesel', $labels) . '</td>
+													<td>' . V::get('regon', 'Regon', $labels) . '</td>
+													<td>' . V::get('source', 'source', $labels) . '</td>
+													<td>' . V::get('jednostka_organizacyjna', 'jednostka_organizacyjna', $labels) . '</td>
+													<td>' . V::get('A_STATUS', 'A_STATUS', $labels) . '</td>
+													<td>' . V::get('A_STATUS_INFO', 'A_STATUS_INFO', $labels) . '</td>
+													<td>' . V::get('L_APPOITMENT_USER', 'L_APPOITMENT_USER', $labels) . '</td>
+													<td>' . V::get('Adresy', 'Adresy', $labels) . '</td>
+											 </tr>
+											 <tr>
+												<td style="padding:0" width=1><button style="padding:5px" id="filtersFieldRemoveBtn-PRACOWNICY" onClick="return removeFiltersPracownicy(event, this)" title="Kasuj filtry" class="btn btn-xs btn-link glyphicon glyphicon-remove"></button></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:80px" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_ID" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_imiona" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_nazwisko" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_nip" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_pesel" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_regon" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_source" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_jednostka_organizacyjna" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_A_STATUS" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_A_STATUS_INFO" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_L_APPOITMENT_USER" value="" placeholder="%"></td>
+												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_Adresy" value="" placeholder="%"></td>
+											 </tr>
+										 </thead>
+										 <tbody id="body-pracownicy">
+										 </tbody></table>
+										 </form>';
+						return $view;
+
+	}
+
+
+	// tworzenie grupy pracowników
+	public function createPracownicyGroupAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'createPracownicyGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
+	}
+	public function createPracownicyGroupAjax($args) {
+		$nazwa = V::get('NAZWA', '', $args);
+
+		// validate
+		if (!$nazwa) throw new Exception("Nie wybrano grupa");
+
+		$idGroup = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY_group', [
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+			'NAZWA' => $nazwa,
+			'ID_USER' => User::getID()
+		]);
+
+		return [
+			'msg' => "Utworzona grupę {$nazwa}",
+			'type' => "success",
+			'body' => [
+				'id' => $idGroup,
+				'nazwa' => $nazwa
+			]
+		];
+	}
+
+	// Dodanie do grupy filtra pracowników
+	public function addPracownicyToGroupAjaxAction() {
+		 Response::sendTryCatchJson(array($this, 'addPracownicyToGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
+	}
+	public function addPracownicyToGroupAjax($args) {
+		$idGroup = V::get('idGroup', '', $args);
+		$type = V::get('type', 'ids', $args);
+		$pracownicyIds = V::get('pracownicyIds', '', $args);
+		$filter = V::get('filter', '', $args);
+
+		// validate
+		if (!$idGroup) throw new Exception("Nie wybrano grupa");
+		switch ($type) {
+			case 'ids': {
+				if (!$pracownicyIds || count($pracownicyIds) == 0) throw new Exception("Proszę wybrać pracowników");
+			} break;
+			case 'filter': {
+				if (empty($filter)) throw new Exception("Proszę wybrać pracowników");
+			} break;
+			default: throw new Exception("Missing type");
+		}
+
+		// TODO: SPRWADZENIE  CZY NIE DODANOU JUZ PRACOWNIKAS
+		// default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group
+		// default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY
+
+		$group = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
+			'cols' => [ // TODO:? propertyName = []
+				'ID',
+				'ID_USER',
+				'NAZWA',
+			],
+			// 'f_ID_USER' => User::getID()
+		])->getItem($idGroup);
+		if (!$group) throw new Exception("Grupa nie istnieje");
+		if (User::getID() != $group['ID_USER']) throw new Exception("Brak uprawnień do grupy");
+
+		if ('filter' === $type) {
+			$args__idGroup = V::get('filterIdGroup', 0, $filter, 'int'); // dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
+			if ($args__idGroup < 0) $args__idGroup = 0;
+			$search = V::get('search', '', $filter);
+			$searchParams = [];
+			if (!empty($search)) {
+				$ogcSearch = "*{$search}*"; // wildCard="*" -> mysql '%'
+				$searchParams['ogc:Filter'] = '
+					<ogc:Filter>
+				    <ogc:Or>
+				      <ogc:PropertyIsLike wildCard="" singleChar="%23" escapeChar="!">
+				        <ogc:PropertyName>nip</ogc:PropertyName>
+				        <ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+				      </ogc:PropertyIsLike>
+				      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+				        <ogc:PropertyName>nazwisko</ogc:PropertyName>
+								<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
+				      </ogc:PropertyIsLike>
+				    </ogc:Or>
+				  </ogc:Filter>
+				';
+			}
+
+			$backRefFilter = [];
+			if ($args__idGroup > 0) {
+				$backRefFilter['__backRef'] = [
+					'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+					'primaryKey' => $args__idGroup,
+					'fieldName' => 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+				];
+			}
+
+			$filtersParams = [];
+			$fieldFilterKeys = array_filter(array_keys($filter), function ($key) {
+				return ('f_' === substr($key, 0, 2));
+			});
+			foreach ($fieldFilterKeys as $key) {
+				$filtersParams[ $key ] = '%' . $filter[ $key ] . '%';
+			}
+
+			$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
+			$query = $acl->buildQuery(array_merge([
+				'cols' => ['ID'],
+			], $searchParams, $filtersParams, $backRefFilter, [
+				'limit' => 0
+			]));
+			$items = $query->getItems();
+
+			$pracownicyIds = array_map(function ($row) {
+				return $row['ID'];
+			}, $items);
+		}
+
+		ACL::addListRef(
+			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+			$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+			$refPrimaryKey = $idGroup,
+			$refListRemotePrimaryKey = $pracownicyIds
+		);
+
+		return [
+			'msg' => "Powiązano pracowników z grupą {$idGroup}",
+			'type' => "success",
+		];
+	}
+
+
+	public function fetchGroupPracownicyAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'fetchGroupPracownicyAjax'));
+	}
+	public function fetchGroupPracownicyAjax() {
+		$query = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
+			'cols' => [ // TODO:? propertyName = []
+				'ID',
+				'ID_USER',
+				'NAZWA',
+			],
+			'f_ID_USER' => "=" . User::getID(), // szukamy dokładnie tej wartości - mysql: where ID_USER = "1"
+			'f_A_STATUS' => "!DELETED", // `A_STATUS` != 'DELETED'
+		]);
+		$items = $query->getItems();
+		DBG::log($items,'array',"grupy");
+		if (empty($items)) throw new AlertWarningException("Grupy nie istnieją");
+
+		$arrayGroupPracownicy = array();
+		foreach ($items as $item) {
+			// if (User::getID() != $item['ID_USER']) throw new Exception("Brak uprawnień do grupy"); // or skip - continue;
+			$arrayGroupPracownicy[] = [
+				'ID' => $item['ID'],
+				'NAZWA' => $item['NAZWA'],
+			];
+ 		}
+
+		return [
+			'type' => 'success',
+			'msg' => 'fetchGroupPracownicyAjax',
+			'__req_args' => $_REQUEST,
+			'__args' => $args,
+			'body' => [
+				'itmesGroupPracownicy' => $arrayGroupPracownicy
+			]
+		];
+	}
+
+
+	function mapShortNs($shortNs) {
+		switch ($shortNs) {
+			case 'KRS': return 'default_db/BI_audit_KRS/BI_audit_KRS';
+			case 'KRS/p': return 'default_db/BI_audit_KRS_person/BI_audit_KRS_person';
+			case 'MSIG': return 'default_db/BI_audit_MSIG/BI_audit_MSIG';
+			case 'MSIG/p': return 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person';
+			case 'CEIDG': return 'default_db/BI_audit_CEIDG/BI_audit_CEIDG';
+			default: throw new Exception("Not implemented short Ns '{$shortNs}'");
+		}
+	}
+
+
+	public function generateBiAuditRaportAjaxAction() {
+		Response::sendTryCatchJson(array($this, 'generateBiAuditRaportAjax'), $args = 'JSON_FROM_REQUEST_BODY');
+	}
+	public function generateBiAuditRaportAjax($args) {
+		$depthValue = V::get('depthValue', '', $args);
+		if (!$depthValue) {
+			throw new Exception("Nie podano wartości dla głębokości powiązań");
+		}
+
+		$smadReaportTitle = V::get('smadReaportTitle', '', $args);
+		if (!$smadReaportTitle) {
+			throw new Exception("Nie podano tytułu raportu");
+		}
+
+		$analizaOnlyTargets = V::get('analizaOnlyTargets', '', $args);
+		if (!$analizaOnlyTargets) {
+			throw new Exception("Nie podano wartości czy zwracać wyniki tylko z obiektami docelowymi");
+		}
+
+		$pracownicyIds = V::get('pracownicyIds', [], $args, 'uint_array'); // array of int > 0
+		$kontrahenciIds = V::get('kontrahenciIds', [], $args, 'uint_array'); // array of int > 0
+		$pozostaleOd = V::get('pozostaleOd', [], $args, 'array');
+		$pozostaleDo = V::get('pozostaleDo', [], $args, 'array');
+		$allOdLength = count($pracownicyIds) + count($pozostaleOd);
+		$allDoLength = count($kontrahenciIds) + count($pozostaleDo);
+
+		// walidacja listy kontrahentów i pracowników
+		if ( !$allOdLength && !$allDoLength ) {
+			throw new Exception("Nie wybrano pozycji do analizy. Wybierz pracowników/kontrahentów.");
+		}
+		// TODO: analizaOnlyTargets = ( 'y' | 'n' ) - allDoLength should depend of analizaOnlyTargets?
+
+		// Tworzenie rekrodu w bazie - Raport -
+		$idRaport = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', [
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+			'L_APPOITMENT_INFO' => $smadReaportTitle,
+			'FILE_STATUS' => "TO_GENERATE",
+			'A_STATUS' => "NORMAL",
+			'BI_analiza_minDepth' => 1,
+			'BI_analiza_maxDepth' => $depthValue,
+			'BI_analiza_onlyTargets' => $analizaOnlyTargets
+		]);
+		if ($idRaport <= 0) throw new Exception("Nie udało się dodać nowego raportu");
+
+		DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_HIST', [
+			'ID_USERS2' => $idRaport,
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => 'NOW()',
+			'L_APPOITMENT_INFO' => $smadReaportTitle,
+			'FILE_STATUS' => "TO_GENERATE",
+			'A_STATUS' => "NORMAL",
+			'BI_analiza_minDepth' => 1,
+			'BI_analiza_maxDepth' => $depthValue,
+			'BI_analiza_onlyTargets' => $analizaOnlyTargets
+		]);
+
+		if (!empty($pracownicyIds)) {
+			ACL::addListRef(
+				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+				$refPrimaryKey = $idRaport,
+				$refListRemotePrimaryKey = $pracownicyIds
+			);
+		}
+
+		if (!empty($kontrahenciIds)) {
+			ACL::addListRef(
+				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+				$refPrimaryKey = $idRaport,
+				$refListRemotePrimaryKey = $kontrahenciIds
+			);
+		}
+
+		if (!empty($pozostaleOd)) {
+			foreach ($pozostaleOd as $featureKey) {
+				$idOd = DB::getPDO()->insert('BI_audit_POWIAZANIA_OD', [
+					'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+					'A_RECORD_CREATE_DATE' => 'NOW()',
+				]);
+				// TODO: ? add OD_HIST
+				ACL::addRef(
+					$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+					$fieldTypeName = 'default_db__x3A__BI_audit_POWIAZANIA_OD:BI_audit_POWIAZANIA_OD',
+					$refPrimaryKey = $idRaport,
+					$refRemotePrimaryKey = $idOd
+				);
+				list($shortNs, $featurePk) = explode('.', $featureKey);
+				$featureNs = $this->mapShortNs($shortNs);
+				ACL::addRef(
+					$rootObjectNamespace = 'default_db/BI_audit_POWIAZANIA_OD/BI_audit_POWIAZANIA_OD',
+					$fieldTypeName = Api_WfsNs::typeName($featureNs),
+					$refPrimaryKey = $idOd,
+					$refRemotePrimaryKey = $featurePk
+				);
+			}
+		}
+
+		if (!empty($pozostaleDo)) {
+			foreach ($pozostaleDo as $featureKey) {
+				$idDo = DB::getPDO()->insert('BI_audit_POWIAZANIA_DO', [
+					'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+					'A_RECORD_CREATE_DATE' => 'NOW()',
+				]);
+				// TODO: ? add DO_HIST
+				ACL::addRef(
+					$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+					$fieldTypeName = 'default_db__x3A__BI_audit_POWIAZANIA_DO:BI_audit_POWIAZANIA_DO',
+					$refPrimaryKey = $idRaport,
+					$refRemotePrimaryKey = $idDo
+				);
+				list($shortNs, $featurePk) = explode('.', $featureKey);
+				$featureNs = $this->mapShortNs($shortNs);
+				ACL::addRef(
+					$rootObjectNamespace = 'default_db/BI_audit_POWIAZANIA_DO/BI_audit_POWIAZANIA_DO',
+					$fieldTypeName = Api_WfsNs::typeName($featureNs),
+					$refPrimaryKey = $idDo,
+					$refRemotePrimaryKey = $featurePk
+				);
+			}
+		}
+
+		return [
+			'msg' => "Zadanie do wygnerowania raportu zostało zapisane.",
+			'type' => "success",
+			'body' => [
+				'id' => $idRaport,
+			]
+		];
+	}
+
+
+	/**
+	* Widok formularza dodawania pracowników i kontrahentów
+	*/
+	public function defaultViewFormBiAudit($items, $type) {
+		$activeFormSteps = '';
+		$fieldLabels = [];
+		$currentDate = date("j.n.Y");
+
+		$btnGrafPowiazan = '';
+		switch ($type) {
+			case 'PRACOWNICY': $btnGrafPowiazan = '<div class="btn-group"><button class="btn btn-primary" onclick="graphShowHide(this, \'pracownicy\')" style="padding:1px 5px">GRAF POWIĄZAŃ</button></div>'; break;
+			case 'KONTRAHENCI': $btnGrafPowiazan = '<div class="btn-group"><button class="btn btn-primary" onclick="graphShowHide(this, \'kontrahenci\')" style="padding:1px 5px">GRAF POWIĄZAŃ</button></div>'; break;
+		}
+
+		$formFilterHeadDesc = '';
+		switch ($type) {
+			case 'PRACOWNICY': $formFilterHeadDesc = 'Liczba pozycji na liście: <span id="smad-filter-desc-pracownicy">0</span>'; break;
+			case 'KONTRAHENCI': $formFilterHeadDesc = 'Liczba pozycji na liście: <span id="smad-filter-desc-kontrahenci">0</span>'; break;
+			case 'OPERACYJNA_BAZA_ZGLOSZEN': $formFilterHeadDesc = 'Liczba pozycji na liście: <span id="smad-filter-desc-kontrahenci">0</span>'; break;
+		}
+
+		$formAddNewData = '';
+		switch($type) {
+				case 'KONTRAHENCI':
+					$formSmadSelectTarget = '<select class="form-control" id="smad-select-target-kontrahenci"><option value="y">tak</option><option value="n">nie</option></select>';
+
+					$formFilterHeadTitle = '<h2 class="title" id="smad-filter-head-title-kontrahenci" style="margin-top:0">Wszyscy</h2>';
+
+					$graphView = '<div class="smad-kontrahenci-graph-view" id="smad-kontrahenci-graph-view" style="display: none;"></div>';
+
+					$csvExampleKontrahenci = Request::getPathUri() . 'projects/anton1/theme/assets/file_example/kontrahenci_example.zip';
+					// $formAddNewData ='
+					// <li><a title="IMPORT KONTRAHENCI" onClick="showViewUploadFile(event, \'Import podmiotów/kontrahentów\', \'kontrahenci\', \'no\', \''.$csvExampleKontrahenci.'\' )" class="btn btn-info">IMPORT KONTRAHENCI</a></li>
+					// <li><a title="DODAJ KONTRAHENCI" onClick="createKontrahentAjax(event)" class="btn btn-info">+ DODAJ PODMIOT</a></li>'; //todo: dodać obsługe doddawania kontrahentow
+					$pagination_form = '<div id="pagination-kontrahenci"></div>';
+
+					$acl = ACL::getAclByNamespace("default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI");
+					$fieldList = $acl->getRealFieldList();
+					$fieldLabels = array_combine(
+						$fieldList,
+						array_map(function ($fieldName) use ($acl) {
+							return $acl->getFieldLabel($fieldName);
+						}, $fieldList)
+					);
+					DBG::log($fieldLabels, 'array', "fieldLabels (KONTRAHENCI)");
+				break;
+
+				case 'OPERACYJNA_BAZA_ZGLOSZEN':
+					$formSmadSelectTarget = '<select class="form-control" id="smad-select-target-kontrahenci"><option value="y">tak</option><option value="n">nie</option></select>';
+
+					$formFilterHeadTitle = '<h2 class="title" id="smad-filter-head-title-kontrahenci" style="margin-top:0">Wszyscy</h2>';
+
+					$graphView = '<div class="smad-kontrahenci-graph-view" style="display: none;"></div>';
+
+					$csvExampleKontrahenci = Request::getPathUri() . 'projects/anton1/theme/assets/file_example/kontrahenci_example.zip';
+					// $formAddNewData ='
+					// <li><a title="IMPORT KONTRAHENCI" onClick="showViewUploadFile(event, \'Import podmiotów/kontrahentów\', \'kontrahenci\', \'no\', \''.$csvExampleKontrahenci.'\' )" class="btn btn-info">IMPORT KONTRAHENCI</a></li>
+					// <li><a title="DODAJ KONTRAHENCI" onClick="createKontrahentAjax(event)" class="btn btn-info">+ DODAJ PODMIOT</a></li>'; //todo: dodać obsługe doddawania kontrahentow
+
+					$pagination_form = '<div id="pagination-kontrahenci"></div>';
+
+					$acl = ACL::getAclByNamespace("default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI");
+					$fieldList = $acl->getRealFieldList();
+					$fieldLabels = array_combine(
+						$fieldList,
+						array_map(function ($fieldName) use ($acl) {
+							return $acl->getFieldLabel($fieldName);
+						}, $fieldList)
+					);
+					DBG::log($fieldLabels, 'array', "fieldLabels (KONTRAHENCI)");
+				break;
+
+				case 'PRACOWNICY':
+					$formSmadSelectTarget = '<select class="form-control" id="smad-select-target"><option value="y">tak</option><option value="n">nie</option></select>';
+
+					$formFilterHeadTitle = '<h2 class="title" id="smad-filter-head-title-pracownicy" style="margin-top:0">Wszyscy</h2>';
+
+					$graphView = '<div class="smad-pracownicy-graph-view" id="smad-pracownicy-graph-view" style="display: none;"></div>';
+
+					$csvExamplePracownicy = Request::getPathUri() . 'projects/anton1/theme/assets/file_example/pracownicy_example.zip';
+					// $formAddNewData ='
+					// <li><a title="IMPORT PRACOWNIKÓW" onClick="showViewUploadFile(event, \'Import osób\', \'pracownicy\', \'yes\', \''.$csvExamplePracownicy.'\'  )" class="btn btn-info">IMPORT PRACOWNIKÓW</a></li>
+					// <li><a title="DODAJ PRACOWNIKÓW" onClick="createPracownikAjax(event)" class="btn btn-info" >+ DODAJ OSOBĘ</a></li>'; //todo: dodać obsługe doddawania pracownikow
+
+					$pagination_form = '<div id="pagination-pracownicy"></div>';
+
+					$acl = ACL::getAclByNamespace("default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY");
+					$fieldList = $acl->getRealFieldList();
+					$fieldLabels = array_combine(
+						$fieldList,
+						array_map(function ($fieldName) use ($acl) {
+							return $acl->getFieldLabel($fieldName);
+						}, $fieldList)
+					);
+					DBG::log($fieldLabels, 'array', "fieldLabels (PRACOWNICY)");
+				break;
+		}
+
+
+		$outLinkOD = $this->getLink() . "#PRACOWNICY";
+		$outLinkDO = $this->getLink() . "#KONTRAHENCI";
+		$outStepOdCompleted = 'complete';
+		$outStepDoCompleted = '';
+		switch ($type) {
+			case 'KONTRAHENCI': $outStepDoCompleted = 'complete'; break;
+			case 'OPERACYJNA_BAZA_ZGLOSZEN': $outStepDoCompleted = 'complete'; break;
+		}
+		$outHeaderTitle = '';
+		switch ($type) {
+				case 'KONTRAHENCI': $outHeaderTitle = 'Kontrahenci'; break;
+				case 'OPERACYJNA_BAZA_ZGLOSZEN': $outHeaderTitle = 'KONTRAHENCI/PODMIOTY'; break;
+				case 'PRACOWNICY': $outHeaderTitle = 'Pracownicy'; break;
+		}
+		$groupFilterList = '';
+		switch($type) {
+			case 'PRACOWNICY':
+				$groupFilterList .= '
+					<a href="#" title="STWÓRZ GRUPĘ" class="btn btn-default" onClick="createGroupPracownicy(event)" >+ STWÓRZ GRUPĘ</a>
+					<div id="group-pracownicy" class="btn-group" style="margin-left:12px">
+						<button class="btn btn-default active" title="Wszyscy" data-group-filter="0">Wszyscy</button>
+					</div>
+				';
+				break;
+			case 'KONTRAHENCI':
+				$groupFilterList .= '
+					<a href="#" title="STWÓRZ GRUPĘ" class="btn btn-default" onClick="createGroupKontrahenci(event)" data-color-noactive="">+ STWÓRZ GRUPĘ</a>
+					<div id="group-kontrahenci" class="btn-group" style="margin-left:12px">
+							<button class="btn btn-default active" title="Wszyscy" data-group-filter="0">Wszyscy</button>
+					</div>
+				';
+				break;
+			case 'OPERACYJNA_BAZA_ZGLOSZEN':
+				$groupFilterList .= '
+					<a href="#" title="STWÓRZ GRUPĘ" class="btn btn-default" onClick="createGroupKontrahenci(event)" data-color-noactive="">+ STWÓRZ GRUPĘ</a>
+					<div id="group-kontrahenci" class="btn-group" style="margin-left:12px">
+						<button class="btn btn-default active" title="Wszyscy" data-group-filter="0">Wszyscy</button>
+					</div>
+				';
+				break;
+		}
+		$groupFilterList = '
+			<h4 style="margin-top:0; margin-bottom:24px" class="smad-heder-title menu-item"><span class="smad-line-red">|</span> ' . $outHeaderTitle . ' </h4>
+			<div>
+				'.$groupFilterList.'
+			</div>
+		';
+
+		$buttonMoveToGroup = '';
+		switch($type) {
+			case 'KONTRAHENCI':
+				// $buttonMoveToGroup = '<a title="DODAJ WYBRANE DO GRUPY" onClick="addKontrahenciToGroup(event)" class="btn btn-info">DODAJ WYBRANE DO GRUPY</a>';
+				// $buttonMoveToGroup .= '<a title="DODAJ WSZYSTKIE DO GRUPY" onClick="addKontrahenciAllToGroup(event)" class="btn btn-info" style="margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</a>';
+				// $buttonMoveToGroup .= '<a title="USUN WYBRANE Z GRUPY" onClick="removeKontrahenciFromGroup(event)" class="btn btn-info" style="margin-left:12px">USUŃ WYBRANE Z GRUPY</a>';
+			break;
+			case 'PRACOWNICY':
+				// $buttonMoveToGroup = '<a title="DODAJ WYBRANE DO GRUPY" onClick="addPracownikToGroup(event)" class="btn btn-info">DODAJ WYBRANE DO GRUPY</a>';
+				// $buttonMoveToGroup .= '<a title="DODAJ WSZYSTKIE DO GRUPY" onClick="addPracownikAllToGroup(event)" class="btn btn-info" style="margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</a>';
+				// $buttonMoveToGroup .= '<a title="USUN WYBRANE Z GRUPY" onClick="removePracownikFromGroup(event)" class="btn btn-info" style="margin-left:12px">USUŃ WYBRANE Z GRUPY</a>';
+			break;
+		}
+
+		$countSelectedItem = '';
+		switch($type) {
+				case 'KONTRAHENCI':
+					$countSelectedItem = 'Wybrano: <span id="count-selected-item-kontrahenci">0</span> <span><a title="wyczyść zapamietanych kontrahentów"  class="link-primary" onClick="clearListLocalStorageByType(\'kontrahenci\')"><small>(wyczyść)</small></a></span>';
+				break;
+				case 'OPERACYJNA_BAZA_ZGLOSZEN':
+					$countSelectedItem = 'Wybrano: <span id="count-selected-item-kontrahenci">0</span> <span><a title="wyczyść zapamietanych kontrahentów"  class="link-primary" onClick="clearListLocalStorageByType(\'kontrahenci\')"><small>(wyczyść)</small></a></span>';
+				break;
+				case 'PRACOWNICY':
+					$countSelectedItem = 'Wybrano: <span id="count-selected-item-pracownicy">0</span> <span><a title="wyczyść zapamietanych pracowników" class="link-primary" onClick="clearListLocalStorageByType(\'pracownicy\')"><small>(wyczyść)</small></a></span>';
+				break;
+		}
+		$countSelectedBtns = '';
+		switch($type) {
+				case 'KONTRAHENCI':
+					$countSelectedBtns = '<a title="DODAJ WYBRANE DO GRUPY" onClick="addKontrahenciToGroup(event)" class="btn btn-info btn-xs" style="padding:1px 5px; margin-left:12px">DODAJ WYBRANE DO GRUPY</a>';
+					// 	$countSelectedBtns .= '<a title="DODAJ WSZYSTKIE DO GRUPY" onClick="addKontrahenciAllToGroup(event)" class="btn btn-info btn-xs" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</a>';
+					$countSelectedBtns .= '<a title="USUN WYBRANE Z GRUPY" onClick="removeKontrahenciFromGroup(event)" class="btn btn-info btn-xs" style="padding:1px 5px; margin-left:12px">USUŃ WYBRANE Z GRUPY</a>';
+				break;
+				case 'PRACOWNICY':
+					$countSelectedBtns = '<a title="DODAJ WYBRANE DO GRUPY" onClick="addPracownikToGroup(event)" class="btn btn-info btn-xs" style="padding:1px 5px; margin-left:12px">DODAJ WYBRANE DO GRUPY</a>';
+					// 	$countSelectedBtns .= '<a title="DODAJ WSZYSTKIE DO GRUPY" onClick="addPracownikAllToGroup(event)" class="btn btn-info btn-xs" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</a>';
+					$countSelectedBtns .= '<a title="USUN WYBRANE Z GRUPY" onClick="removePracownikFromGroup(event)" class="btn btn-info btn-xs" style="padding:1px 5px; margin-left:12px">USUŃ WYBRANE Z GRUPY</a>';
+				break;
+		}
+
+
+		$view = '';
+		$view .= '<div id="smad-employees-section" class="smad-form-' . $type . '" >';
+		$view .= '
+				<div class="container-fluid" style="margin-bottom:32px; margin-top:32px">
+					<div class="row">
+						<div class="col-md-12">
+							'.$groupFilterList.'
+						</div>
+					</div>
+				</div>
+
+				<div class="container-fluid">
+					<div class="padding-0 smad-employees-list-head">
+						<div class="col-md-8">
+							<header>
+								'.$formFilterHeadTitle.'
+							</header>
+							<div class="desc">
+								<p style="text-align:left">'.$formFilterHeadDesc.'</p>
+							</div>
+							<div class="countSelectedItem">
+								'.$countSelectedItem.'
+								'.$countSelectedBtns.'
+							</div>
+						</div>
+						<div class="col-md-4">
+							<div class="menu-items">
+								<div class="menu-item">
+									<ul class="padding-0">
+										'.$formAddNewData.'
+									</ul>
+								</div>
+							</div>
+							<div style="position:absolute; bottom:0; right:24px">
+								'.$btnGrafPowiazan.'
+							</div>
+						</div>
+					</div>
+				</div>
+
+				<div class="smad-graph-section">
+					<div class="container-fluid">
+						'.$graphView.'
+					</div>
+				</div>
+
+				<div class="container-fluid">
+					<div class="table-responsive padding-0" id="smad-table-' . $type . '">
+						' . $this->showListDataByType($items, $type, $fieldLabels) . '
+					</div>
+				</div>
+				<div class="container-fluid ">
+					<div>
+						'. $pagination_form .'
+					</div>
+				</div>
+
+				<div class="container-fluid smad-employees-bottom-navigation">
+					<div class="padding-0">
+						<div class="col-md-12">
+								'.$buttonMoveToGroup.'
+						</div>
+					</div>
+				</div>
+			</div>
+		';
+		return $view;
+	}
+
+
+	public function showListDataByType($items, $type='PRACOWNICY', $labels) {
+
+			switch ($type) {
+				case 'PRACOWNICY':
+					return $this->showTablePracownicy($labels);
+					break;
+				case 'KONTRAHENCI':
+					return $this->showTableKontrahenci($labels);
+					break;
+			}
+	}
+
+	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'];
+
+		if ('last' === $ids) {
+			$ids = [
+				DB::getPDO()->fetchValue(" select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA order by ID DESC limit 1 ")
+			];
+		}
+
+		// 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;
+
+				$listDetailsProgress = array_map(function ($detail) {
+					return floatval($detail['progress']);
+				}, $json['details']);
+
+				$relationsProgress = $json['summary']['count'] > 0 ? round(floatval(array_sum($listDetailsProgress)) / floatval($json['summary']['count']), 3) : 0;
+				$reportsCount = V::get('reportsCount', 0, $json['summary'], 'float');
+				$reportsProgress = $reportsCount > 0 ? round(V::get('reportsCreated', 0, $json['summary'], 'float') / $reportsCount, 3) : 0;
+				return round(0.5 * $relationsProgress + 0.5 * $reportsProgress, 3);
+			} 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,
+		] ];
+	}
+
+}

+ 820 - 0
tools/Anton1.php.addItemToRaport.js

@@ -0,0 +1,820 @@
+var createReactClass = window.p5VendorJs.createReactClass;
+var h = window.p5VendorJs.React.createElement;
+var ReactDOM = window.p5VendorJs.ReactDOM;
+var AsyncTypeahead = window.p5VendorJs.AsyncTypeahead;
+var swal = window.swal;
+var STORE_NAME = STORE_NAME || '_anton1RaportStore';
+var DBG = DBG || false;
+var DBG1 = true;
+
+
+function anton1FeatureKey(ns, pk) {
+  switch (ns) {
+    case 'default_db/BI_audit_KRS/BI_audit_KRS': return 'KRS.' + pk;
+    case 'default_db/BI_audit_KRS_person/BI_audit_KRS_person': return 'KRS/p.' + pk;
+    case 'default_db/BI_audit_MSIG/BI_audit_MSIG': return 'MSIG.' + pk;
+    case 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person': return 'MSIG/p.' + pk;
+    case 'default_db/BI_audit_CEIDG/BI_audit_CEIDG': return 'CEIDG.' + pk;
+    default: throw "Not implemented feature key for ns '" + ns + "'";
+  }
+}
+
+function getSelectedListLocalStorageKey(from) { // from: ( OD | DO )
+  switch (from) {
+    case 'OD': return 'Anton1.biAuditForm.odFeatureKeys';
+    case 'DO': return 'Anton1.biAuditForm.doFeatureKeys';
+    default: throw "Not implemented from selected list '" + from + "' - expected 'OD' or 'DO'";
+  }
+}
+function getSelectedListFromLocalStorage(from) {
+  return JSON.parse( localStorage.getItem(getSelectedListLocalStorageKey(from)) || '[]' );
+}
+function saveToSelectedListInLocalStorage(from, featureKey) {
+  DBG && console.log("DBG::saveToSelectedListInLocalStorage(from, featureKey)", {from, featureKey}, {added: getSelectedListFromLocalStorage(from).concat(featureKey)});
+  localStorage.setItem(getSelectedListLocalStorageKey(from), JSON.stringify(
+    getSelectedListFromLocalStorage(from).concat(featureKey)
+  ))
+}
+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 );
+    })
+  ))
+}
+
+
+function convertXlinkToObjects(items) {
+  var _childCache = {}; // fieldName => { pk => child }
+  items.forEach(function (item) {
+    var refFields = Object.keys(item).filter(function (fieldName) {
+      return (-1 !== fieldName.indexOf(':') && item[fieldName]);
+    });
+    refFields.forEach(function (fieldName) {
+      item[fieldName].forEach(function (child) {
+        if (1 === Object.keys(child).length && 'xlink' in child) {
+          // xlink
+        } else if (Object.keys(child).length > 1) {
+          if ('@primaryKey' in child) {
+            if (!(fieldName in _childCache)) _childCache[fieldName] = {};
+            _childCache[fieldName][ child['@primaryKey'] ] = child;
+          }
+        }
+      })
+    })
+    return item;
+  });
+  DBG && console.log('DBG convertXlinkToObjects', { _childCache, items });
+
+  return items.map(function (item) {
+    var refFields = Object.keys(item).filter(function (fieldName) {
+      return (-1 !== fieldName.indexOf(':') && item[fieldName]);
+    });
+    refFields.forEach(function (fieldName) {
+      item[fieldName] = item[fieldName].map(function (child) {
+        if (1 === Object.keys(child).length && 'xlink' in child) {
+          var pk = child['xlink'].split('.').pop();
+          return _childCache[fieldName][pk];
+        } else if ('p5:links' in child && 'p5:next' in child['p5:links']) {
+          return Object.assign({}, child['p5:links']['p5:next'], {
+            type: 'p5:next'
+          });
+          // child.value = "https://.../SE/wfs-data.php/?SERVICE=WFS&VERSION=1.0.0&TYPENAME=default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person&REQUEST=GetFeature&backRefNS=default_db/BI_audit_KRS/BI_audit_KRS&backRefPK=1332604&backRefField=default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person&maxFeatures=10&startIndex=10"
+        }
+        return child;
+      })
+    })
+    return item;
+  })
+}
+
+function filterByHelper(option, node) {
+  var text = (node && node.text) ? node.text : '';
+  var label = option.label.toLowerCase();
+  var words = ( (text.indexOf(' ') > 0)
+    ? text.split(' ')
+    : [ text ]
+  ).map(function (word) { return word.trim().replace(/^[0]+/g, '').toLowerCase(); })
+  .filter(function (word) { return word.length > 2; });
+  var foundWords = words.filter(function (word) {
+    return (label.indexOf(word) > -1);
+  })
+  return (foundWords.length === words.length);
+}
+// function (option, text) {
+//   if (option.ID == 161323) return false;
+//   console.log('TODO: filterBy...', {option, text});
+//   return true;
+// },
+
+var P5UI_AddItemToReport_SelectKrsPerson = createReactClass({
+  // h(SelectKrsPerson, { krs: this.state.selected })
+  // this.props.krs: {
+  //   "@primaryKey": "161323",
+  //   "A_kod": "80-299",
+  //   "A_kraj": "POLSKA",
+  //   "A_miejscowosc": "GDAŃSK",
+  //   "A_nrDomu": "54C",
+  //   "A_nrLokalu": null,
+  //   "A_poczta": "GDAŃSK",
+  //   "A_ulica": "BARNIEWICKA",
+  //   "ID": "161323",
+  //   "S_kraj": "POLSKA",
+  //   "S_miejscowosc": "GDAŃSK",
+  //   "S_wojewodztwo": "POMORSKIE",
+  //   "krs": "0000223476",
+  //   "nazwa": "BIALL Sp. z o.o.",
+  //   "nip": "6040018535",
+  //   "regon": "193106935",
+  //   "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person": [
+  //     {
+  //       "@primaryKey": "747004",
+  //       "ID": "747004",
+  //       "imiona": "ADRIAN RYSZARD",
+  //       "nazwisko": "WIECZORKOWSKI",
+  //       "pesel": "75040301615"
+  //     },
+  //     {
+  //       "@primaryKey": "747003",
+  //       "ID": "747003",
+  //       "imiona": "EWA",
+  //       "nazwisko": "WIECZORKOWSKA",
+  //       "pesel": "75090401549"
+  //     },
+  //    ...
+  //     {
+  //       "@backRefNS: "default_db/BI_audit_KRS/BI_audit_KRS"
+  //       @backRefPK: "1332604"
+  //       @maxFeatures: 10
+  //       @startIndex: 10
+  //       @typeName: "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person"
+  //       type: "p5:next"
+  //       value: "https://biuro.biall-net.pl/dev-pl/se-projects/anton1/SE/wfs-data.php/?SERVICE=WFS&VERSION=1.0.0&TYPENAME=default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person&REQUEST=GetFeature&backRefNS=default_db/BI_audit_KRS/BI_audit_KRS&backRefPK=1332604&backRefField=default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person&maxFeatures=10&startIndex=10"
+  //     }
+  getKrsPersonsFromProps: function () {
+    return (this.props.krs && this.props.krs['default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person'])
+      ? this.props.krs['default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person']
+      : [];
+  },
+  handleFetchMore: function () {
+    this.props.fetchMoreKrsPerson(this.props.krs);
+  },
+  render: function () {
+    var krsPresons = this.getKrsPersonsFromProps();
+    // var _selectPerson = this.props.selectPerson.bind(this)
+    var selectedBaza = 'default_db/BI_audit_KRS_person/BI_audit_KRS_person';
+
+    var handleFetchMore = this.handleFetchMore.bind(this);
+
+    return (krsPresons.length > 0)
+    ? h('ol', { style: { margin: '22px', textAlign: 'left' } }, krsPresons.map(function (person) {
+      var label = (person.imiona || '') + ' ' + (person.nazwisko || '') + ', ' + (person.pesel || '');
+      if ('type' in person && "p5:next" == person['type']) {
+        return h('li', {}, [
+          h('a', { className: "btn btn-link", onClick: handleFetchMore }, "pobierz więcej ...")
+        ]);
+      }
+      return h('li', {}, [
+        h(P5UI_AddItemToReport_Checkbox, { from: 'OD', selectedBaza: selectedBaza, selectedItem: person }),
+        h(P5UI_AddItemToReport_Checkbox, { from: 'DO', selectedBaza: selectedBaza, selectedItem: person }),
+        h('span', { style: { 'margin-left': "6px" } }, label),
+        // h('button', {
+        //   className: "btn btn-primary",
+        //   style: { marginLeft: "8px", padding: "4px 8px", fontSize: "small" },
+        //   onClick: function () { _selectPerson(person) }
+        // }, "Dodaj osobę")
+      ]);
+    }))
+    : null;
+  }
+});
+
+var P5UI_AddItemToReport_SelectMSIGPerson = createReactClass({
+  render: function () { // BI_audit_MSIG_person
+    var msigPresons = (this.props.msig && this.props.msig['default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person'])
+    ? this.props.msig['default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person']
+    : [];
+    var _selectPerson = this.props.selectPerson.bind(this)
+    var selectedBaza = 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person';
+
+    return (msigPresons.length > 0)
+    ? h('ol', { style: { margin: '22px', textAlign: 'left' } }, msigPresons.map(function (person) {
+      var label = (person.imiona || '') + ' ' + (person.nazwisko || '') + ', ' + (person.pesel || '');
+      return h('li', {}, [
+        h(P5UI_AddItemToReport_Checkbox, { from: 'OD', selectedBaza: selectedBaza, selectedItem: person }),
+        h(P5UI_AddItemToReport_Checkbox, { from: 'DO', selectedBaza: selectedBaza, selectedItem: person }),
+        h('span', { style: { 'margin-left': "6px" } }, label),
+        // h('button', {
+        //   className: "btn btn-primary",
+        //   style: { marginLeft: "8px", padding: "4px 8px", fontSize: "small" },
+        //   onClick: function () { _selectPerson(person) }
+        // }, "Dodaj osobę")
+      ]);
+    }))
+    : null;
+  }
+});
+
+var P5UI_AddItemToReport_BazaMenuItem = createReactClass({
+    // this.props: { key: option.ID, baza: selectedBaza, data: option }
+    render: function () {
+        return h('div', {}, this.props.data.label);
+    }
+});
+
+var P5UI_AddItemToReport_Checkbox = createReactClass({
+  _getStore: function () {
+    DBG && console.warn('DBG:: window[STORE_NAME]', { store: window[STORE_NAME], STORE_NAME: STORE_NAME})
+    return window[STORE_NAME] || null;
+  },
+  getStateFromStore: function () {
+    var featureKey = anton1FeatureKey(this.props.selectedBaza, this.props.selectedItem['@primaryKey']);
+    var storeState = this._getStore().getState();
+    return {
+      featureKey: featureKey,
+      isSelected: (-1 !== this.getStoreList(this.props.from).indexOf(featureKey)),
+      // totalOdPracownicy: storeState.totalOdPracownicy,
+      // totalOdPozostale: storeState.totalOdPozostale,
+      // totalDoKontrahenci: storeState.totalDoKontrahenci,
+      // totalDoPozostale: storeState.totalDoPozostale,
+    };
+  },
+  getStoreList: function (from) {
+    var storeState = this._getStore().getState();
+    switch (from) {
+      case 'OD': return storeState.pozostaleOd;
+      case 'DO': return storeState.pozostaleDo;
+      default: throw "Not imeplemented store list from = '" + from + "'";
+    }
+  },
+  getInitialState: function () {
+    return this.getStateFromStore();
+  },
+  componentDidMount: function () {
+    var store = this._getStore()
+    this._unsubscribe = store ? store.subscribe(this.storeUpdated) : function () {};
+  },
+  componentWillUnmount: function () {
+    this._unsubscribe();
+  },
+  storeUpdated: function () {
+		DBG && console.log('DBG::P5UI__Anton1Header::storeUpdated ', this.getStateFromStore());
+		this.setState(this.getStateFromStore())
+	},
+  _handleClick: function () {
+    this.state.isSelected ? this.removeItem() : this.saveItem();
+    // _onSelect(from, selectedBaza, selectedItem);
+  },
+  removeItem: function () {
+    this._getStore().dispatch({ type: 'RM_' + this.props.from, featureKey: this.state.featureKey })
+    // removeFromSelectedListInLocalStorage(this.props.from, this.state.featureKey);
+    // this.setState({ isSelected: false });
+  },
+  saveItem: function () {
+    this._getStore().dispatch({ type: 'ADD_' + this.props.from, featureKey: this.state.featureKey })
+    // saveToSelectedListInLocalStorage(this.props.from, this.state.featureKey);
+    // this.setState({ isSelected: true });
+  },
+  render: function () {
+    var handleClick = this._handleClick.bind(this);
+    // var _onSelect = this.props.onSelect;
+    var isSelected = this.state.isSelected;
+    return h('div', { className: "checkbox", style: { display: "inline-block", 'margin-left': "6px" } }, [
+      h('label', { style: { border: "1px solid " + ( isSelected ? "red" : "#ccc" ), 'border-radius': "4px", padding: "2px 6px 0 6px", 'font-size': "12px" } }, [
+        h('input', {
+          style: { margin: "0 6px 0 0", position: "relative" },
+          type: "checkbox",
+          checked: isSelected,
+          onClick: handleClick,
+        }),
+        h('span', { style: { 'line-height': "20px" } }, this.props.from),
+      ])
+    ]);
+  }
+});
+
+var P5UI_AddItemToReport = createReactClass({
+    getInitialState: function () {
+        // var listOd = getSelectedListFromLocalStorage('OD');
+        // var listDo = getSelectedListFromLocalStorage('DO');
+        return {
+            baza: null,
+            newItemBaza: null,
+            isSearching: false,
+            selected: null,
+        };
+    },
+    _handleSelectBaza: function (baza) {
+        this.setState({ baza: baza, newItemBaza: null, selected: null, isSearching: false });
+    },
+    _handleSelectNewItem: function (baza) {
+        this.setState({ baza: null, newItemBaza: baza, selected: null, isSearching: false });
+    },
+    _handleSelected: function (selected) {
+        this.setState({ selected: (selected.length > 0) ? selected[0] : null });
+    },
+    _fetchMoreKrsPerson: function (krs) {
+      var _addMoreKrsPersons = this._addMoreKrsPersons.bind(this);
+      var pk = krs['@primaryKey']
+      var krsPersons = (krs && krs['default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person'])
+        ? krs['default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person']
+        : [];
+      var lastPerson = krsPersons[ krsPersons.length - 1 ];
+      if (lastPerson && 'type' in lastPerson && "p5:next" == lastPerson['type']) {
+        var fetchNextLink = lastPerson['value'];
+        DBG && console.log("DBG: fetchNextLink", { fetchNextLink });
+        var cols = [ 'ID', 'imiona', 'nazwisko', 'pesel' ];
+        p5WFS_GetFeature(lastPerson['@typeName'], {
+          'p5:next': fetchNextLink.replace('&maxFeatures=10', '&maxFeatures=100') + '&' + 'propertyName=' + cols.join(',')
+        }).then(function (results) {
+          DBG && console.log('DBG: _fetchMoreKrsPerson result', { results });
+          _addMoreKrsPersons(pk, results.map(function (item) { return Object.assign({}, item, { '@primaryKey': item['ID'] }) }));
+        })
+      } else {
+        DBG && console.log("DBG: missing fetch more link");
+        return;
+      }
+    },
+    _addMoreKrsPersons: function (pk, moreKrsPersons) {
+      var newOptions = this.state.options.map(function (item) {
+        if (item['@primaryKey'] === pk) {
+          item['default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person'].pop() // rm last link node - p5:link/p5:next
+          return Object.assign(item, {
+            'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person': item['default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person'].concat(moreKrsPersons)
+          })
+        }
+        return item;
+      });
+      this.setState({
+        options: newOptions
+      })
+    },
+    _handleSearch: function (query) {
+        this.setState({ isSearching: true });
+        var _setState = this.setState.bind(this);
+        var baza = this.state.baza;
+        window.fetch(URL_FETCH_FROM_BAZA, {
+					method: 'POST',
+					header: {
+						'contentType': 'applications/json'
+					},
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						baza: baza,
+            query: query,
+					})
+				})
+        .then(function(response) {
+          return response.text();
+        })
+        .then(function(responseText) {
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+					if (result.type == 'success') {
+						// p5UI__notifyAjaxCallback(result);
+            if (result.body && result.body.items && result.body.items.length > 0) {
+              return result.body.items;
+            } else {
+              p5UI__notifyAjaxCallback({ type: 'warning', msg: "Brak danych pasujących do kryteriów wyszukiwania" });
+              _setState({ isSearching: false, options: [] });
+            }
+					}
+				})
+        .then(function(items) {
+          DBG && console.log('items fetched:', items);
+          _setState({ isSearching: false, options: convertXlinkToObjects(items) });
+        })
+        .catch(function(error) {
+          DBG && console.log('request failed', error);
+        })
+    },
+    componentWillUnmount: function () {
+        DBG && console.log("DBG: conponentDidUnmount...");
+    },
+    renderItemSave__OLD(selectedBaza, selectedItem) {
+      var _onSelect = this.props.onSelect;
+      return h('div', { style: { margin: '22px' } }, [
+          h('button', {
+              className: "btn btn-primary",
+              onClick: function () {
+                  _onSelect(selectedBaza, selectedItem);
+                  // ReactDOM.unmountComponentAtNode(document.getElementById(FUNCTION_NAME + '__searchBaza'));
+                  // swal.close()
+              }
+          }, "XXX Dodaj " + (
+            ( ('default_db/BI_audit_KRS_person/BI_audit_KRS_person' === selectedBaza)
+              || ('default_db/BI_audit_MSIG_person/BI_audit_MSIG_person' === selectedBaza)
+            )
+            ? "osobę"
+            : "firmę"
+          )) // TODO:  |> KRS -> firmę, |> KRS Person -> osobę, ....
+      ]);
+    },
+    renderItemSave(selectedBaza, selectedItem) {
+      return h('div', { style: { margin: '22px', 'font-size': "16px" } }, [
+          "Dodaj jako: ",
+          h(P5UI_AddItemToReport_Checkbox, { from: 'OD', selectedBaza: selectedBaza, selectedItem: selectedItem }),
+          h(P5UI_AddItemToReport_Checkbox, { from: 'DO', selectedBaza: selectedBaza, selectedItem: selectedItem }),
+      ]);
+    },
+    render: function () {
+        var bazaBtns = [];
+        bazaBtns.push({ baza: "default_db/BI_audit_KRS/BI_audit_KRS", title: "KRS - Firmy", label: "KRS" });
+        bazaBtns.push({ baza: "default_db/BI_audit_KRS_person/BI_audit_KRS_person", title: "KRS - Osoby", label: "KRS/p" });
+        bazaBtns.push({ baza: "default_db/BI_audit_MSIG/BI_audit_MSIG", title: "MSIG - Firmy", label: "MSIG" });
+        bazaBtns.push({ baza: "default_db/BI_audit_MSIG_person/BI_audit_MSIG_person", title: "MSIG - Osoby", label: "MSIG/p" });
+        //bazaBtns.push({ baza: "default_db/BI_audit_taxpayer/BI_audit_taxpayer", title: "VAT - Aktywni płatnicy", label: "VATp" });
+        bazaBtns.push({ baza: "default_db/BI_audit_CEIDG/BI_audit_CEIDG", title: "CEIDG", label: "CEIDG" });
+
+        var newItemBtns = [];
+        // newItemBtns.push({ baza: "default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY", title: "Nowa osoba", label: "Nowa osoba" });
+        // newItemBtns.push({ baza: "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI", title: "Nowy podmiot", label: "Nowy podmiot" });
+
+        function generateBazaBtn(btn, opts) {
+            return h('button', {
+                title: btn.title,
+                className: "btn btn-success" + (opts.selected ? " active" : ""),
+                style: { margin: "3px" },
+                onClick: function () {
+                    opts.onClick(btn.baza)
+                },
+            }, btn.label)
+        }
+
+        function generateNewItemBtn(btn, opts) {
+            return h('button', {
+                title: btn.title,
+                className: "btn btn-success" + (opts.selected ? " active" : ""),
+                style: { margin: "3px" },
+                onClick: function () {
+                    opts.onClick(btn.baza)
+                },
+            }, btn.label)
+        }
+
+        var handleSelectBaza = this._handleSelectBaza.bind(this);
+        var handleSelectNewItem = this._handleSelectNewItem.bind(this);
+        var selectedBaza = this.state.baza;
+        var selectedNewItemBaza = this.state.newItemBaza;
+        var selectedItem = this.state.selected;
+        var selectedLabel = '';
+        if (selectedBaza) {
+            var selBazaBtn = bazaBtns.filter(function (btn) { return btn.baza === selectedBaza; })
+            if (selBazaBtn) {
+                selBazaBtn[0].title
+            }
+        }
+        var handleSearch = this._handleSearch.bind(this);
+        var handleSelected = this._handleSelected.bind(this);
+        var _onSelect = this.props.onSelect;
+        var _fetchMoreKrsPerson = this._fetchMoreKrsPerson.bind(this);
+        DBG && console.log('DBG: render this.state.options', this.state.options);
+        return h('div', {}, [
+            h('p', { style: { textAlign: "center" } }, "Wybierz bazę"),
+            h('div', { style: { marginBottom: '22px' } },
+                bazaBtns.map(function (btn) {
+                    return generateBazaBtn(btn, {
+                        onClick: handleSelectBaza,
+                        selected: (selectedBaza === btn.baza),
+                    });
+                }).concat(
+                    newItemBtns.map(function (btn) {
+                        return generateNewItemBtn(btn, {
+                            onClick: handleSelectNewItem,
+                            selected: (selectedNewItemBaza === btn.baza),
+                        });
+                    })
+                )
+            ),
+            ('default_db/BI_audit_KRS/BI_audit_KRS' === selectedBaza) && h(AsyncTypeahead, {
+                isLoading: this.state.isSearching,
+                allowNew: false,
+                multiple: false,
+                options: this.state.options,
+                labelKey: "label",
+                emptyLabel: "Brak danych pasujących do kryteriów wyszukiwania",
+                searchText: "Wyszukiwanie...",
+                // labelKey: function (option) {
+                //   return [
+                //     option.nazwa.replace('"', ''),
+                //     option.nip,
+                //     option.krs,
+                //     option.regon,
+                //     option.S_miejscowosc,
+                //   ].join(' ')
+                // },
+                minLength: 3,
+                onSearch: handleSearch,
+                placeholder: "Wyszukaj...",
+                onChange: handleSelected,
+                autoFocus: true,
+                filterBy: filterByHelper,
+                renderMenuItemChildren: function (option, props) {
+                    return h(P5UI_AddItemToReport_BazaMenuItem, { key: option.ID, baza: selectedBaza, data: option });
+                }
+            }),
+            ('default_db/BI_audit_KRS_person/BI_audit_KRS_person' === selectedBaza) && h(AsyncTypeahead, {
+                isLoading: this.state.isSearching,
+                allowNew: false,
+                multiple: false,
+                options: this.state.options,
+                labelKey: "label",
+                emptyLabel: "Brak danych pasujących do kryteriów wyszukiwania",
+                searchText: "Wyszukiwanie...",
+                // labelKey: function (option) {
+                //   return [
+                //     option.nazwa.replace('"', ''),
+                //     option.nip,
+                //     option.krs,
+                //     option.regon,
+                //     option.S_miejscowosc,
+                //   ].join(' ')
+                // },
+                minLength: 3,
+                onSearch: handleSearch,
+                placeholder: "Wyszukaj...",
+                onChange: handleSelected,
+                autoFocus: true,
+                filterBy: filterByHelper,
+                renderMenuItemChildren: function (option, props) {
+                    return h(P5UI_AddItemToReport_BazaMenuItem, { key: option.ID, baza: selectedBaza, data: option });
+                }
+            }),
+            ('default_db/BI_audit_MSIG/BI_audit_MSIG' === selectedBaza) && h(AsyncTypeahead, {
+                isLoading: this.state.isSearching,
+                allowNew: false,
+                multiple: false,
+                options: this.state.options,
+                labelKey: "label",
+                emptyLabel: "Brak danych pasujących do kryteriów wyszukiwania",
+                searchText: "Wyszukiwanie...",
+                // labelKey: function (option) {
+                //   return [
+                //     option.nazwa.replace('"', ''),
+                //     option.nip,
+                //     option.krs,
+                //     option.regon,
+                //     option.S_miejscowosc,
+                //   ].join(' ')
+                // },
+                minLength: 3,
+                onSearch: handleSearch,
+                placeholder: "Wyszukaj...",
+                onChange: handleSelected,
+                autoFocus: true,
+                filterBy: filterByHelper,
+                renderMenuItemChildren: function (option, props) {
+                    return h(P5UI_AddItemToReport_BazaMenuItem, { key: option.ID, baza: selectedBaza, data: option });
+                }
+            }),
+            ('default_db/BI_audit_MSIG_person/BI_audit_MSIG_person' === selectedBaza) && h(AsyncTypeahead, {
+                isLoading: this.state.isSearching,
+                allowNew: false,
+                multiple: false,
+                options: this.state.options,
+                labelKey: "label",
+                emptyLabel: "Brak danych pasujących do kryteriów wyszukiwania",
+                searchText: "Wyszukiwanie...",
+                // labelKey: function (option) {
+                //   return [
+                //     option.nazwa.replace('"', ''),
+                //     option.nip,
+                //     option.krs,
+                //     option.regon,
+                //     option.S_miejscowosc,
+                //   ].join(' ')
+                // },
+                minLength: 3,
+                onSearch: handleSearch,
+                placeholder: "Wyszukaj...",
+                onChange: handleSelected,
+                autoFocus: true,
+                filterBy: filterByHelper,
+                renderMenuItemChildren: function (option, props) {
+                    return h(P5UI_AddItemToReport_BazaMenuItem, { key: option.ID, baza: selectedBaza, data: option });
+                }
+            }),
+            ('default_db/BI_audit_CEIDG/BI_audit_CEIDG' === selectedBaza) && h(AsyncTypeahead, {
+                isLoading: this.state.isSearching,
+                allowNew: false,
+                multiple: false,
+                options: this.state.options,
+                labelKey: "label",
+                emptyLabel: "Brak danych pasujących do kryteriów wyszukiwania",
+                searchText: "Wyszukiwanie...",
+                // labelKey: function (option) {
+                //   return [
+                //     option.nazwa.replace('"', ''),
+                //     option.nip,
+                //     option.krs,
+                //     option.regon,
+                //     option.S_miejscowosc,
+                //   ].join(' ')
+                // },
+                minLength: 3,
+                onSearch: handleSearch,
+                placeholder: "Wyszukaj...",
+                onChange: handleSelected,
+                autoFocus: true,
+                filterBy: filterByHelper,
+                renderMenuItemChildren: function (option, props) {
+                    return h(P5UI_AddItemToReport_BazaMenuItem, { key: option.ID, baza: selectedBaza, data: option });
+                }
+            }),
+            ("default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY" === selectedNewItemBaza) && h('div', { className: 'form-group' }, [
+              h('input',{
+                className:'form-control required',
+                id:'personName',
+                placeholder:'Imię'
+              }),
+              h('input',{
+                className:'form-control required',
+                id:'personSurname',
+                placeholder:'Nazwisko'
+              }),
+              h('input',{
+                className:'form-control required',
+                id:'personPesel',
+                placeholder:'Pesel'
+              }),
+              h('input',{
+                className:'form-control',
+                id:'personNip',
+                placeholder:'NIP'
+              }),
+              h('button', { className: "btn btn-primary", onClick: function () {
+                _onSelect(selectedNewItemBaza, {
+                  personName: document.getElementById('personName').value,
+                  personSurname: document.getElementById('personSurname').value,
+                  personPesel: document.getElementById('personPesel').value,
+                  personNip: document.getElementById('personNip').value,
+                })
+                swal.close();
+              }.bind(this) }, "Dodaj osobę")
+            ]),
+            ("default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI" === selectedNewItemBaza) && h('div', { className: 'form-group' }, [
+              h('input',{
+                className:'form-control required',
+                id:'companyName',
+                placeholder:'Nazwa'
+              }),
+              h('input',{
+                className:'form-control required',
+                id:'companyPesel',
+                placeholder:'Pesel'
+              }),
+              h('input',{
+                className:'form-control required',
+                id:'companyStreet',
+                placeholder:'Ulica'
+              }),
+              h('input',{
+                className:'form-control required',
+                id:'companyNumber',
+                placeholder:'Numer budynku'
+              }),
+              h('input',{
+                className:'form-control required',
+                id:'companyNumberLocal',
+                placeholder:'Numer lokalu'
+              }),
+              h('input',{
+                className:'form-control required',
+                id:'companyPostCode',
+                placeholder:'Kod pocztowy'
+              }),
+              h('input',{
+                className:'form-control required',
+                id:'companyCity',
+                placeholder:'Miejscowosc'
+              }),
+              h('input',{
+                className:'form-control required',
+                id:'companyNip',
+                placeholder:'NIP'
+              }),
+              h('input',{
+                className:'form-control',
+                id:'companyRegon',
+                placeholder:'REGON'
+              }),
+              h('input',{
+                className:'form-control',
+                id:'companyKrs',
+                placeholder:'KRS'
+              }),
+              h('button', { className: "btn btn-primary", onClick: function () {
+                _onSelect(selectedNewItemBaza, {
+                  companyName: document.getElementById('companyName').value,
+                  companyNip: document.getElementById('companyNip').value,
+                  companyRegon: document.getElementById('companyRegon').value,
+                  companyPesel: document.getElementById('companyPesel').value,
+                  companyStreet: document.getElementById('companyStreet').value,
+                  companyNumber: document.getElementById('companyNumber').value,
+                  companyNumberLocal: document.getElementById('companyNumberLocal').value,
+                  companyPostCode: document.getElementById('companyPostCode').value,
+                  companyCity: document.getElementById('companyCity').value,
+                  companyKrs: document.getElementById('companyKrs').value,
+                })
+                swal.close();
+              }.bind(this) }, "Dodaj podmiot")
+            ]),
+            (selectedBaza && selectedItem) && this.renderItemSave(selectedBaza, selectedItem),
+            ('default_db/BI_audit_KRS/BI_audit_KRS' === selectedBaza && selectedItem) && h(P5UI_AddItemToReport_SelectKrsPerson, {
+              krs: selectedItem,
+              selectPerson: function (person) {
+                _onSelect("default_db/BI_audit_KRS_person/BI_audit_KRS_person", person);
+                // ReactDOM.unmountComponentAtNode(document.getElementById(FUNCTION_NAME + '__searchBaza'));
+                // swal.close()
+              },
+              fetchMoreKrsPerson: _fetchMoreKrsPerson
+            }),
+            ('default_db/BI_audit_MSIG/BI_audit_MSIG' === selectedBaza && selectedItem) && h(P5UI_AddItemToReport_SelectMSIGPerson, {
+              msig: selectedItem,
+              selectPerson: function (person) {
+                _onSelect("default_db/BI_audit_MSIG_person/BI_audit_MSIG_person", person);
+                // ReactDOM.unmountComponentAtNode(document.getElementById(FUNCTION_NAME + '__searchBaza'));
+                // swal.close()
+              }
+            }),
+            (DBG && selectedItem) && h('pre', { style: { textAlign: 'left' } }, JSON.stringify(selectedItem, null, 2)),
+        ])
+    }
+});
+
+function getWindowWidth() {
+    var w = window, d = document,
+        e = d.documentElement,
+        g = d.getElementsByTagName('body')[0];
+    return w.innerWidth || e.clientWidth || g.clientWidth;
+}
+
+function addItemToRaport(event) {
+    // default_db/BI_audit_KRS/BI_audit_KRS
+    // default_db/BI_audit_KRS_person/BI_audit_KRS_person
+    // default_db/BI_audit_MSIG/BI_audit_MSIG
+    // default_db/BI_audit_MSIG_person/BI_audit_MSIG_person
+    // default_db/BI_audit_taxpayer/BI_audit_taxpayer
+    // default_db/BI_audit_CEIDG/BI_audit_CEIDG
+    // default_db/BI_audit_ENERGA_RUM_UMOWY/BI_audit_ENERGA_RUM_UMOWY
+    // default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI
+    // default_db/BI_audit_ENERGA_FAKTURY/BI_audit_ENERGA_FAKTURY
+    var valueUrl = global.location.hash;
+    swal({
+        title: "Dodaj osobę lub podmiot",
+        width: (getWindowWidth() * 0.8),
+        html: '<div id="' + FUNCTION_NAME + '__searchBaza" style="padding:0 24px 24px 24px; min-height:400px"></div>',
+        animation: false,
+        showConfirmButton: false,
+        showCancelButton: false,
+        showCloseButton: true,
+        allowEnterKey: false,
+        onOpen: function () {
+            ReactDOM.render(
+                h(P5UI_AddItemToReport, {
+                    onSelect: function (from, baza, selected) {
+                        DBG && console.log('TODO: selected ', { from, baza, selected });
+                        global.fetch(URL_SAVE_TO_DB, {
+                          method: 'POST',
+                          credentials: 'same-origin',
+                          headers: { 'Content-Type': 'application/json' },
+                          body: JSON.stringify({
+                            from: from,
+                            baza: baza,
+                            item: selected
+                          })
+                        }).then(function(response) {
+                          return response.json();
+                        }).then(function(result) {
+                          if(result.type === "success"){
+                            if(valueUrl === '#PRACOWNICY'){
+                              urlFetchPracownicy(1);
+                            }else{
+                              urlFetchKontrahenci(1);
+                            }
+                          }
+                          p5UI__notifyAjaxCallback(result);
+                        })
+                    }
+                }),
+                document.getElementById(FUNCTION_NAME + '__searchBaza')
+            )
+        }
+    }).catch(function (err) {
+        DBG && console.log('err', err)
+    })
+}
+
+// global[FUNCTION_NAME] = addItemToRaport;
+module.exports[FUNCTION_NAME] = addItemToRaport;
+// module.exports = {
+//     P5UI_AddItemToReport_BazaMenuItem,
+//     P5UI_AddItemToReport,
+//     createPracownikAjax
+// }

+ 1052 - 0
tools/Anton1.php.graphShowHide.js

@@ -0,0 +1,1052 @@
+var getItemLocalStorage = global.getItemLocalStorage;
+var setItemLocalStorage = global.setItemLocalStorage;
+var p5WFS_GetFeature = global.p5WFS_GetFeature;
+var renderGraph = global.renderGraph; // @from sankey-init
+var DBG = DBG || 0;
+var DBG1 = 1;
+var globalGraphStore = null;
+function graphStore(state, action) {
+	var prevState = state || {
+		isLoading: false,
+		sentRequestId: 0,
+		receivedRequestId: 0,
+		items: [],
+	};
+	DBG && console.log('DBG: graph store', { prevState, action });
+	switch (action.type) {
+		case 'SET_SENT_REQUEST_ID': return Object.assign(prevState, {
+			sentRequestId: action.sentRequestId,
+			isLoading: true
+		});
+		case 'SET_RESPONSE': return Object.assign(prevState, {
+			receivedRequestId: action.requestId,
+			items: action.items,
+			isLoading: (prevState.sentRequestId > action.requestId) ? true : false,
+		});
+		default: return prevState;
+	}
+}
+var createGraphActions = function () {
+
+	var setSentRequestId = function (sentRequestId) {
+		return { type: 'SET_SENT_REQUEST_ID', sentRequestId: sentRequestId };
+	}
+	var setResponse = function (obj) {
+		return Object.assign(obj, { type: 'SET_RESPONSE' });
+	}
+
+	var fetchData = function (nameSection) {
+		return function (dispatch, getState) {
+			var state = getState();
+			var this__requestId = state.sentRequestId + 1;
+			dispatch(setSentRequestId(this__requestId));
+
+			var reqPromise = graphFetchData(nameSection);
+			return reqPromise.then(function (response) {
+				var items = response;
+				var state = getState();
+
+				if (state.receivedRequestId > this__requestId) {
+					DBG && console.log('DBG: skiped response', { 'state.receivedRequestId': state.receivedRequestId, this__requestId });
+					return;
+				}
+
+				dispatch(
+					setResponse({
+						requestId: this__requestId,
+						msg: "Pobrano dane",
+						typeName: ('pracownicy' === nameSection) ? 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY' : 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+						items: items
+					})
+				);
+			}).catch(function (e) {
+				p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #GS1: ' + e});
+				// dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
+			});
+		}
+	}
+
+	return {
+		fetchData: fetchData,
+	}
+}
+var globalGraphActions = ''; // createGraphActions();
+
+var createReactClass = global.p5VendorJs.createReactClass;
+var h = global.p5VendorJs.React.createElement;
+var ReactDOM = global.p5VendorJs.ReactDOM;
+var Redux = global.p5VendorJs.Redux;
+var ReduxThunk = global.p5VendorJs.ReduxThunk;
+var createStoreWithThunkMiddleware = Redux.applyMiddleware(ReduxThunk)(Redux.createStore); // TODO: to vendor.js
+
+global['P5UI__Anton1GraphView'] = createReactClass({
+	// props.nameSection: PropTypes.string.isRequired
+	// props.store: Redux store with state: { isLoading: false, sentRequestId: 0, receivedRequestId: 0, items: [] }
+	// props.actions: Redux store actions {  }
+	getStateFromStore: function () {
+		var state = this.props.store.getState();
+		return {
+			isLoading: state.isLoading,
+			items: state.items,
+			sentRequestId: state.sentRequestId,
+			receivedRequestId: state.receivedRequestId,
+		};
+	},
+	getInitialState: function () {
+		return this.getStateFromStore();
+	},
+	componentDidMount: function () {
+		DBG && console.log('DBG::P5UI__Anton1GraphView::componentDidMount');
+		this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
+	},
+	componentWillUnmount: function () {
+		this.unsubscribe()
+	},
+	storeUpdated: function () {
+		DBG && console.log('DBG::P5UI__Anton1GraphView::storeUpdated');
+		this.setState(this.getStateFromStore())
+	},
+	shouldComponentUpdate: function (nextProps, nextState) {
+		DBG && console.log('DBG::P5UI__Anton1GraphView::shouldComponentUpdate', { state: this.state, nextState});
+		// return (
+		// 	this.state.isLoading !== nextState.isLoading
+		// 	|| this.state.sentRequestId !== nextState.sentRequestId
+		// 	|| this.state.receivedRequestId !== nextState.receivedRequestId
+		// );
+		if (nextState.receivedRequestId > this.state.receivedRequestId) {
+			var htmlId = 'p5_graphView_' + this.props.nameSection; // #smad-'+nameSection+'-graph-view
+			graphRaportRender({
+				msg: "Pobrano dane",
+				typeName: ('pracownicy' === this.props.nameSection) ? 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY' : 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+				items: nextState.items
+			}, document.getElementById(htmlId))
+		}
+		return (
+			this.state.isLoading !== nextState.isLoading
+		);
+	},
+	render: function () {
+		DBG && console.log('DBG::P5UI__Anton1GraphView::render', { props: this.props, state: this.state });
+		var htmlId = 'p5_graphView_' + this.props.nameSection; // #smad-'+nameSection+'-graph-view
+		var msg = (this.state.isLoading) ? "Pobieranie danych..." : null;
+		return h('div', {}, [
+			msg && h('div', {
+				className: 'alert alert-info',
+				style: {
+					maxWidth: '600px',
+					margin: '0 auto',
+					padding: '3px 24px',
+				}
+			}, msg),
+			h('div', { id: htmlId })
+		]);
+	}
+});
+
+var btnRefresh = null;
+var btnHide = null;
+function graphShowHide(btnNode, nameSection) {
+	var node = $('#smad-'+nameSection+'-graph-view')
+	if (!node || !node.length) {
+		console.log("Missing dom node '#smad-"+nameSection+"-graph-view'")
+		return;
+	}
+	var btnJqNode = jQuery(btnNode);
+	if ('block' == node.css('display')) {
+		DBG && console.warn("DBG:graphShowHide: hide");
+		node.hide()
+		btnRefresh.remove();
+		btnHide.remove();
+		return;
+	}
+	node.show()
+	btnRefresh = jQuery('<button class="btn btn-primary" style="padding:1px 5px">odśwież</button>').appendTo(btnJqNode.parent());
+	btnRefresh.on('click', function () {
+		globalGraphStore.dispatch(globalGraphActions.fetchData(nameSection));
+	})
+	btnHide = jQuery('<button class="btn btn-primary" style="padding:1px 5px"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(btnJqNode.parent());
+	btnHide.on('click', function () {
+		node.hide()
+		btnRefresh.remove();
+		btnHide.remove();
+	})
+	var graphResultNode = node.get(0)
+
+	if (!globalGraphStore) {
+		globalGraphStore = createStoreWithThunkMiddleware(graphStore);
+		globalGraphActions = createGraphActions();
+		ReactDOM.render(
+			h(P5UI__Anton1GraphView, {
+				nameSection: nameSection,
+				store: globalGraphStore,
+				actions: globalGraphActions,
+			}),
+			graphResultNode
+		);
+	}
+
+	globalGraphStore.dispatch(globalGraphActions.fetchData(nameSection));
+}
+
+function graphFetchData(nameSection) { // @return Promise
+	var page = page || getItemLocalStorage('Anton1.biAuditForm.'+nameSection+'.pagination.page');
+	if ( page === 1) {
+		setItemLocalStorage('Anton1.biAuditForm.'+nameSection+'.pagination.page', 1);
+	}
+
+	var filterIdGroup = getItemLocalStorage('Anton1.biAuditForm.'+nameSection+'.filterIdGroup');
+	var filterIdRaport = getItemLocalStorage('Anton1.biAuditForm.'+nameSection+'.filterIdRaport');
+
+	var frm = document.getElementById('filtersFieldRemoveBtn-' + nameSection.toUpperCase()).form
+	var fieldNameList = ('pracownicy' === nameSection) ? FIELD_LIST_PRACOWNICY : FIELD_LIST_KONTRAHENCI
+	var filterFields = fieldNameList.filter(function (fieldName) {
+		if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"')
+		return (frm[fieldName]) ? true : false
+	}).map(function (fieldName) {
+		return [ fieldName, frm[fieldName].value ]
+	}).filter(function (filter) {
+		return ( filter[1].length > 0 )
+	})
+	// filterFields = (filterFields.length > 0) ? '&' + filterFields : ''
+
+	// <ogc:Filter>
+	//     <ogc:Or>
+	//       <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+	//         <ogc:PropertyName>A_STATUS</ogc:PropertyName>
+	//         <ogc:Literal>*O%23MA*</ogc:Literal>
+	//       </ogc:PropertyIsLike>
+	//       <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
+	//         <ogc:PropertyName>A_STATUS</ogc:PropertyName>
+	//         <ogc:Literal>*ARNING</ogc:Literal>
+	//       </ogc:PropertyIsLike>
+	//     </ogc:Or>
+	//   </ogc:Filter>
+	var ogcFilterFields = (filterFields.length > 0)
+	? '<ogc:Filter><ogc:And>' + filterFields.map(function(filter) {
+		if ('ID' === filter[0].substr(2)) return '<ogc:PropertyIsEqualTo>' +
+			'<ogc:PropertyName>' + filter[0].substr(2) + '</ogc:PropertyName>' +
+			'<ogc:Literal>' + filter[1] + '</ogc:Literal>' +
+		'</ogc:PropertyIsEqualTo>';
+
+		return '<ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">' +
+			'<ogc:PropertyName>' + filter[0].substr(2) + '</ogc:PropertyName>' +
+			'<ogc:Literal>*' + filter[1] + '*</ogc:Literal>' +
+		'</ogc:PropertyIsLike>';
+	}) + '</ogc:And></ogc:Filter>'
+	: ''
+
+	var paginationLimit = 20;
+
+	DBG && console.log('graphFetchData...', {
+		paginationLimit: paginationLimit,
+		page: page,
+		filterIdGroup: filterIdGroup,
+		filterIdRaport: filterIdRaport,
+		filterFields: filterFields,
+		ogcFilterFields: ogcFilterFields,
+	});
+
+	function refFieldsOnPathToList(typeName, fields) {
+		var fields = fields || []
+		var flatList = []
+		var refPathBase = [
+			'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
+			'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
+			'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object'
+		]
+		flatList.push(refPathBase.concat(typeName).join('/'))
+		fields.forEach(function (fieldName) {
+			flatList.push(refPathBase.concat(typeName, fieldName).join('/'))
+		})
+		return flatList;
+	}
+
+	return p5WFS_GetFeature(('pracownicy' === nameSection) ? 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY' : 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+		Object.assign({
+			sortBy: 'ID+D',
+			maxFeatures: paginationLimit,
+			startIndex: (page - 1) * paginationLimit,
+			// TODO: backRefNS, backRefPK, backRefField - TODO: from groups
+			// resolve: 'all',
+			// resolveDepth: 2
+			// 'ogc:Filter': '<wfs:Query>' + '\n' + [
+			// 	'ID',
+			// 	'imiona',
+			// 	'nazwisko',
+			// 	'miejscowosc'
+			// ]
+
+			'ogc:Filter': '<wfs:Query>' + '\n' + [].concat(
+				('pracownicy' === nameSection)
+				? [
+					'ID',
+					'imiona',
+					'nazwisko',
+					'miejscowosc'
+				] : [
+					'ID',
+					'Pelna_nazwa_kontrahenta'
+				]
+			)
+			.concat(refFieldsOnPathToList('default_db__x3A__BI_audit_KRS:BI_audit_KRS', [ 'ID', 'nazwa', 'krs', 'S_miejscowosc' ]))
+			.concat(refFieldsOnPathToList('default_db__x3A__BI_audit_MSIG:BI_audit_MSIG', [ 'ID', 'nazwa' ]))
+			.concat(refFieldsOnPathToList('default_db__x3A__BI_audit_CEIDG:BI_audit_CEIDG', [ 'ID', 'nazwisko', 'firma' ]))
+			.concat(refFieldsOnPathToList('default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI', [ 'ID', 'Pelna_nazwa_kontrahenta' ]))
+			.concat(
+				('pracownicy' === nameSection)
+				? []
+				: refFieldsOnPathToList('default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY', [ 'ID', 'imiona', 'nazwisko', 'miejscowosc' ])
+			)
+			.concat([
+				// '*',
+				// 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy/*',
+				[
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
+					'ID'
+				].join('/'),
+				[
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
+					'ID'
+				].join('/'),
+				[
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
+					'ID'
+				].join('/')
+			]).map(function (fieldName) {
+				return '<wfs:PropertyName>' + fieldName + '</wfs:PropertyName>';
+			}).join('\n') + '\n' +
+			( ogcFilterFields ? ogcFilterFields : '' ) +
+			'</wfs:Query>'
+		}, ('pracownicy' === nameSection && filterIdRaport > 0)
+			? {
+				backRefNS: 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+				backRefPK: filterIdRaport,
+				backRefField: 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+			}
+			: {}
+		, ('kontrahenci' === nameSection && filterIdRaport > 0)
+			? {
+				backRefNS: 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+				backRefPK: filterIdRaport,
+				backRefField: 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+			}
+			: {}
+		, ('pracownicy' === nameSection && filterIdGroup > 0)
+			? {
+					backRefNS: 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+					backRefPK: filterIdGroup,
+					backRefField: 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+				}
+			: {}
+		, ('kontrahenci' === nameSection && filterIdGroup > 0)
+			? {
+				backRefNS: 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+				backRefPK: filterIdGroup,
+				backRefField: 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+			}
+			: {}
+		)
+	);
+}
+
+function graphRender(props, wrapNode) {
+	throw "TODO: graphRender..."
+}
+
+function graphRaportRender(props, wrapNode) {
+	var svgNode = jQuery(wrapNode).children('svg')
+	svgNode = (svgNode.length) ? d3.select(svgNode.get(0)) : d3.select(wrapNode).append("svg")
+	// svg.append("rect").attr("x",0).attr("y",0).attr("width","100%").attr("height","100%").attr("fill","white").attr('class','background').on('mouseup', () => redraw())
+	// svgNode.attr("width", '100%')
+	// 	.attr("height", '300px')
+		// .append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
+
+	// var data = parseGraphRec(props.items, props.nameSection)
+	var _todoGraphData = [];
+	parseResponseRec(_todoGraphData, props.items, props.typeName)
+	DBG && console.log('_todoGraphData', _todoGraphData)
+	var _nodes = [];
+	var _links = [];
+	var mapNodeIdToIdx = {};
+	_todoGraphData.forEach(function (levelData, levelIdx) {
+		if (levelData.nodes && levelData.nodes.length) {
+			levelData.nodes.forEach(function (node) {
+				try {
+					if (node.id in mapNodeIdToIdx) return;
+					_nodes.push(node) // _nodes.add(node)
+					mapNodeIdToIdx[node.id] = _nodes.length - 1
+				} catch (e) {
+					DBG && console.log('_graphData.nodes.add [level='+levelIdx+'] error:', e);
+				}
+			})
+		}
+	})
+
+	var linkIdsAdded = []
+	_todoGraphData.forEach(function (levelData, levelIdx) {
+		if (levelData.edges && levelData.edges.length) {
+			levelData.edges.forEach(function (edge) {
+				DBG && console.log('_graphData.edges.add [level='+levelIdx+']:', {edge, source:mapNodeIdToIdx[edge.source], target:mapNodeIdToIdx[edge.target], mapNodeIdToIdx});
+				// try {
+					// var source = mapNodeIdToIdx[edge.source]
+					// var target = mapNodeIdToIdx[edge.target]
+					// if (!source || !target) { // && !== 0
+					// 	console.warn('(!source || !target)', {source, target, edge, mapNodeIdToIdx})
+					// }
+					if (-1 !== linkIdsAdded.indexOf(edge.id)) return
+					// _links.push({
+					// 	id: edge.id,
+					// 	source: mapNodeIdToIdx[edge.source],
+					// 	target: mapNodeIdToIdx[edge.target],
+					// 	value: 1
+					// })
+					_links.push({
+						id: edge.id,
+						source: edge.source,
+						target: edge.target,
+						value: 1
+					}) // _edges.add(edge)
+					linkIdsAdded.push(edge.id)
+				// } catch (e) {
+				// 	DBG && console.log('_graphData.edges.add [level='+levelIdx+'] error:', e);
+				// }
+			})
+		}
+	})
+
+	var totalLinks = _links.length
+	// console.log('DBG:0: _links', _links)
+	DBG && console.log('DBG:1: _nodes', _nodes)
+	_nodes = _nodes.filter(function (node, idx) {
+		if (node.typeName !== props.typeName) return true
+		for (var i=0; i<totalLinks; i++) {
+			var link = _links[i]
+			if (_links[i].source === node.id) return true
+			if (_links[i].target === node.id) return true
+		}
+		return false
+	})
+	// console.log('DBG:2: _nodes', _nodes)
+	jQuery(wrapNode).find('p').remove()
+	if (!_nodes || !_nodes.length) {
+		jQuery(wrapNode).find('svg').remove()
+		jQuery(wrapNode).append('<p>Brak powiązań</p>')
+		return;
+	}
+
+	var rightSideNodes = _nodes.filter(function (node, idx) {
+		for (var i=0; i<totalLinks; i++) {
+			var link = _links[i]
+			// if (_links[i].source === node.id) return true
+			if (_links[i].target === node.id) return true
+		}
+		return false
+	})
+	DBG && console.log('DBG: rightSideNodes (total:'+rightSideNodes.length+') ', rightSideNodes)
+	if (rightSideNodes.length > 20) {
+		// TODO: increase height
+	}
+
+
+	var graphData = {
+		nodes: _nodes,
+		links: _links.filter(function (link) {
+			DBG && console.log('DBG loop link', { link, source: link.source, target: link.target, filtered: (link.source && link.target) });
+			return (link.source && link.target);
+		})
+	};
+
+	DBG && console.warn('render graphData', graphData);
+	var graf = renderGraph(svgNode, graphData, {
+		width: jQuery(wrapNode).width(),
+		height: (rightSideNodes.length > 20) ? rightSideNodes.length * 22 : 500
+	})
+	graf.on('click', (event) => {
+	  DBG && console.log('event', event)
+	  // event = {
+	  //   nativeEvent: d3.event,
+	  //   node: a,
+	  //   element: d3.event.srcElement
+	  // }
+
+	  // TODO: !a.expanded && redraw({type: a.name, criteria: 'ID'})
+	})
+}
+
+/**
+ * Response format:
+ * NOTE: every object could be xlink if found before
+ * lvl1      > lvl2         > lvl3  > lvl4         > lvl5
+ * Pracownik > *_row_object > *_row > *_row_object > Podmiot
+ * Pracownik > *_row_object > *_row > *_row_object > ( KRS | CEIDG | ... )
+ * Pracownik > *_row_object > *_row > *_row_object > Pracownik
+ *
+ * Podmiot > *_row_object > *_row > *_row_object > Pracownik
+ * Podmiot > *_row_object > *_row > *_row_object > ( KRS | CEIDG | ... )
+ * Podmiot > *_row_object > *_row > *_row_object > Podmiot
+ *
+ * TODO: make connections only: Pracownik -> ( KRS | CEIDG | ... )* -> Podmiot
+ * NOTE: lvl4 last `_row_object` is (wfs xlink cache system) xlink to lvl2 `_row_object` - ref to lvl1 object
+ * NOTE: lvl3 is always 1 because it is from __backRef
+ */
+var TN_PRACOWNICY = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY';
+var TN_KONTRAHENCI = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI';
+var TN_ROW_OBJ = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object';
+var TN_ROW = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row';
+var TN_KRS = 'default_db__x3A__BI_audit_KRS:BI_audit_KRS';
+var TN_CEIDG = 'default_db__x3A__BI_audit_CEIDG:BI_audit_CEIDG';
+var TN_MSIG = 'default_db__x3A__BI_audit_MSIG:BI_audit_MSIG';
+function parseResponseRec__Helper__addTodoNode(_todoGraphData, level, json, typeName) { // @return string - node id
+	if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
+	var nodeObject = dataMakeNode({
+		typeName: typeName,
+		primaryKey: (json['ID']) ? json['ID'] : null, // TODO: get primaryKey from object
+		row: json,
+	})
+	_todoGraphData[level].nodes.push(nodeObject)
+	// if (parentNodeId) {
+	// 	_todoGraphData[level].edges.push(dataMakeEdge(parentNodeId, nodeObject))
+	// }
+	return nodeObject.id;
+}
+function parseResponseRec__Helper__addTodoEdge(_todoGraphData, level, parentNodeId, newNodeId) {
+	if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
+	_todoGraphData[level].edges.push(
+		// dataMakeEdge(parentNodeId, nodeObject)
+		{
+			id: parentNodeId + newNodeId,
+			source: parentNodeId,
+			target: newNodeId,
+		}
+	)
+}
+function parseResponseRec(_todoGraphData, json, typeName) {
+	DBG = 1;
+	var parentNodeId = null
+	DBG && console.log('DBG::parseResponseRec', {json:json, typeName:typeName, parentNodeId:parentNodeId, isString: p5Utils__isString(json), isArray: p5Utils__isArray(json), isObject: p5Utils__isObject(json)});
+	switch (typeName) {
+		case TN_PRACOWNICY: parseResponseRec__lvl1__Pracownik(_todoGraphData, json, typeName); break;
+		case TN_KONTRAHENCI: parseResponseRec__lvl1__Kontrahent(_todoGraphData, json, typeName); break;
+		default: throw "Not implemented root element typeName '" + typeName + "'";
+	}
+}
+function parseResponseRec__lvl1__Pracownik(_todoGraphData, jsonList, typeName) {
+	if (!p5Utils__isArray(jsonList)) throw "Not implemented root element - expected list of elements";
+	var isXlinkList = (jsonList.length > 0 && p5Utils__isString(jsonList[0]))
+	DBG && console.log('DBG::parseResponseRec__lvl1__Pracownik', {jsonList:jsonList, typeName:typeName, isString: p5Utils__isString(jsonList), isArray: p5Utils__isArray(jsonList), isObject: p5Utils__isObject(jsonList), isXlinkList});
+	jsonList.forEach(function (jsonPracownik) {
+		if (isXlinkList) {
+			DBG && console.warn('DBG::parseResponseRec__lvl1__Pracownik', {jsonPracownik:jsonPracownik, typeName:typeName, isString: p5Utils__isString(jsonPracownik), isArray: p5Utils__isArray(jsonPracownik), isObject: p5Utils__isObject(jsonPracownik), isXlinkList});
+			// parseResponseXlinkListRec(_todoGraphData, jsonPracownik, typeName)
+			throw "Not implemented xlink in Pracownik child";
+		} else {
+			var idNode = parseResponseRec__Helper__addTodoNode(_todoGraphData, level = 1, jsonPracownik, typeName);
+			if (jsonPracownik[TN_ROW_OBJ] && jsonPracownik[TN_ROW_OBJ].length) {
+				parseResponseRec__lvl2__Pracownik_RowObj(_todoGraphData, idNode, jsonPracownik[TN_ROW_OBJ]);
+			}
+		}
+	})
+}
+function parseResponseRec__lvl2__Pracownik_RowObj(_todoGraphData, parentIdNode, rowObjList) {
+	DBG && console.log('DBG::parseResponseRec__lvl2__Pracownik_RowObj rec...', { parentIdNode, rowObjList });
+	rowObjList.forEach(function (jsonRowObj) {
+		if (!p5Utils__isObject(jsonRowObj)) {
+			DBG && console.warn('DBG::parseResponseRec__lvl2__Pracownik_RowObj SKIP non object element', { jsonRowObj });
+			// skip non object elements
+			return;
+		}
+		if (isP5LinkObject(jsonRowObj)) {
+			DBG && console.log('DBG::parseResponseRec__lvl2__Pracownik_RowObj SKIP xlink', { jsonRowObj });
+			// skip p5 link object (type: "next")
+			return;
+		}
+		DBG && console.log('DBG::parseResponseRec__lvl2__Pracownik_RowObj row obj', { jsonRowObj });
+		if (jsonRowObj[TN_ROW] && jsonRowObj[TN_ROW].length) {
+			// NOTE: jsonRowObj[TN_ROW] is array(1) - always 1 because it is from __backRef
+			parseResponseRec__lvl3__Pracownik_RowObj_Row(_todoGraphData, parentIdNode, jsonRowObj[TN_ROW][0]);
+		}
+	})
+}
+function parseResponseRec__lvl3__Pracownik_RowObj_Row(_todoGraphData, parentIdNode, jsonRow) {
+	DBG && console.log('DBG::parseResponseRec__lvl3__Pracownik_RowObj_Row', { jsonRow, parentIdNode });
+	if (jsonRow[TN_ROW_OBJ] && jsonRow[TN_ROW_OBJ].length) {
+		var jsonListRowObj = jsonRow[TN_ROW_OBJ];
+		DBG && console.log('DBG::parseResponseRec__lvl3__Pracownik_RowObj_Row row obj', { jsonListRowObj, parentIdNode });
+		// NOTE: RowObj on list is a connection path in reverse order
+		// NOTE: last element is Pracownik (parentIdNode)
+		// NOTE: first element is Kontrahent - TODO: or another element defines in Raport.od.* or Raport.do.*
+		// var TN_PRACOWNICY = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY';
+		// var TN_KONTRAHENCI = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI';
+		// var TN_ROW_OBJ = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object';
+		// var TN_ROW = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row';
+		// var TN_KRS = 'default_db__x3A__BI_audit_KRS:BI_audit_KRS';
+		// var TN_CEIDG = 'default_db__x3A__BI_audit_CEIDG:BI_audit_CEIDG';
+		// var TN_MSIG = 'default_db__x3A__BI_audit_MSIG:BI_audit_MSIG';
+		var pathPoints = jsonListRowObj.reverse().slice(1).map(function (jsonRowObj) {
+			if (jsonRowObj[TN_KONTRAHENCI]) return Object.assign(jsonRowObj[TN_KONTRAHENCI][0], { typeName: TN_KONTRAHENCI });
+			if (jsonRowObj[TN_PRACOWNICY]) return Object.assign(jsonRowObj[TN_PRACOWNICY][0], { typeName: TN_PRACOWNICY });
+			if (jsonRowObj[TN_KRS]) return Object.assign(jsonRowObj[TN_KRS][0], { typeName: TN_KRS });
+			if (jsonRowObj[TN_CEIDG]) return Object.assign(jsonRowObj[TN_CEIDG][0], { typeName: TN_CEIDG });
+			if (jsonRowObj[TN_MSIG]) return Object.assign(jsonRowObj[TN_MSIG][0], { typeName: TN_MSIG });
+			return null;
+		}).filter(function (jsonRowObj) {
+			return !!jsonRowObj;
+		}).map(function (jsonRowObj) {
+			DBG && console.warn('DBG::parseResponseRec__lvl3__Pracownik_RowObj_Row path', { parentIdNode, fid: (jsonRowObj ? jsonRowObj.typeName + '.' + jsonRowObj.ID : null), jsonRowObj });
+			return jsonRowObj;
+		})
+		for (var i = 0, prevNodeId = parentIdNode, newNodeId; i < pathPoints.length; i++) {
+			jsonObject = pathPoints[i];
+			newNodeId = parseResponseRec__Helper__addTodoNode(_todoGraphData, level = 4, jsonObject, jsonObject.typeName);
+			parseResponseRec__Helper__addTodoEdge(_todoGraphData, level = 4, prevNodeId, newNodeId);
+			prevNodeId = newNodeId;
+		}
+	}
+}
+
+function parseResponseRec__lvl1__Kontrahent(_todoGraphData, jsonList, typeName) {
+	if (!p5Utils__isArray(jsonList)) throw "Not implemented root element - expected list of elements";
+	var isXlinkList = (jsonList.length > 0 && p5Utils__isString(jsonList[0]))
+	DBG && console.log('DBG::parseResponseRec__lvl1__Kontrahent', {jsonList:jsonList, typeName:typeName, isString: p5Utils__isString(jsonList), isArray: p5Utils__isArray(jsonList), isObject: p5Utils__isObject(jsonList), isXlinkList});
+	jsonList.forEach(function (jsonPracownik) {
+		if (isXlinkList) {
+			DBG && console.warn('DBG::parseResponseRec__lvl1__Kontrahent', {jsonPracownik:jsonPracownik, typeName:typeName, isString: p5Utils__isString(jsonPracownik), isArray: p5Utils__isArray(jsonPracownik), isObject: p5Utils__isObject(jsonPracownik), isXlinkList});
+			// parseResponseXlinkListRec(_todoGraphData, jsonPracownik, typeName)
+			throw "Not implemented xlink in Pracownik child";
+		} else {
+			var idNode = parseResponseRec__Helper__addTodoNode(_todoGraphData, level = 1, jsonPracownik, typeName);
+			if (jsonPracownik[TN_ROW_OBJ] && jsonPracownik[TN_ROW_OBJ].length) {
+				parseResponseRec__lvl2__Kontrahent_RowObj(_todoGraphData, idNode, jsonPracownik[TN_ROW_OBJ]);
+			}
+		}
+	})
+}
+function parseResponseRec__lvl2__Kontrahent_RowObj(_todoGraphData, parentIdNode, rowObjList) {
+	DBG && console.log('DBG::parseResponseRec__lvl2__Kontrahent_RowObj rec...', { parentIdNode, rowObjList });
+	rowObjList.forEach(function (jsonRowObj) {
+		if (!p5Utils__isObject(jsonRowObj)) {
+			DBG && console.warn('DBG::parseResponseRec__lvl2__Kontrahent_RowObj SKIP non object element', { jsonRowObj });
+			// skip non object elements
+			return;
+		}
+		if (isP5LinkObject(jsonRowObj)) {
+			DBG && console.log('DBG::parseResponseRec__lvl2__Kontrahent_RowObj SKIP xlink', { jsonRowObj });
+			// skip p5 link object (type: "next")
+			return;
+		}
+		DBG && console.log('DBG::parseResponseRec__lvl2__Kontrahent_RowObj row obj', { jsonRowObj });
+		if (jsonRowObj[TN_ROW] && jsonRowObj[TN_ROW].length) {
+			// NOTE: jsonRowObj[TN_ROW] is array(1) - always 1 because it is from __backRef
+			parseResponseRec__lvl3__Kontrahent_RowObj_Row(_todoGraphData, parentIdNode, jsonRowObj[TN_ROW][0]);
+		}
+	})
+}
+function parseResponseRec__lvl3__Kontrahent_RowObj_Row(_todoGraphData, parentIdNode, jsonRow) {
+	DBG && console.log('DBG::parseResponseRec__lvl3__Pracownik_RowObj_Row', { jsonRow, parentIdNode });
+	if (jsonRow[TN_ROW_OBJ] && jsonRow[TN_ROW_OBJ].length) {
+		var jsonListRowObj = jsonRow[TN_ROW_OBJ];
+		DBG && console.log('DBG::parseResponseRec__lvl3__Kontrahent_RowObj_Row row obj', { jsonListRowObj, parentIdNode });
+		// NOTE: RowObj on list is a connection path in reverse order
+		// NOTE: last element is Pracownik (parentIdNode)
+		// NOTE: first element is Kontrahent - TODO: or another element defines in Raport.od.* or Raport.do.*
+		// var TN_PRACOWNICY = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY';
+		// var TN_KONTRAHENCI = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI';
+		// var TN_ROW_OBJ = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object';
+		// var TN_ROW = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row';
+		// var TN_KRS = 'default_db__x3A__BI_audit_KRS:BI_audit_KRS';
+		// var TN_CEIDG = 'default_db__x3A__BI_audit_CEIDG:BI_audit_CEIDG';
+		// var TN_MSIG = 'default_db__x3A__BI_audit_MSIG:BI_audit_MSIG';
+		var pathPoints = jsonListRowObj.slice(1).reverse().map(function (jsonRowObj) {
+			if (jsonRowObj[TN_KONTRAHENCI]) return Object.assign(jsonRowObj[TN_KONTRAHENCI][0], { typeName: TN_KONTRAHENCI });
+			if (jsonRowObj[TN_PRACOWNICY]) return Object.assign(jsonRowObj[TN_PRACOWNICY][0], { typeName: TN_PRACOWNICY });
+			if (jsonRowObj[TN_KRS]) return Object.assign(jsonRowObj[TN_KRS][0], { typeName: TN_KRS });
+			if (jsonRowObj[TN_CEIDG]) return Object.assign(jsonRowObj[TN_CEIDG][0], { typeName: TN_CEIDG });
+			if (jsonRowObj[TN_MSIG]) return Object.assign(jsonRowObj[TN_MSIG][0], { typeName: TN_MSIG });
+			return null;
+		}).filter(function (jsonRowObj) {
+			return !!jsonRowObj;
+		}).map(function (jsonRowObj) {
+			DBG && console.warn('DBG::parseResponseRec__lvl3__Kontrahent_RowObj_Row path', { parentIdNode, fid: (jsonRowObj ? jsonRowObj.typeName + '.' + jsonRowObj.ID : null), jsonRowObj });
+			return jsonRowObj;
+		})
+		for (var i = 0, prevNodeId, newNodeId; i < pathPoints.length; i++) {
+			jsonObject = pathPoints[i];
+			newNodeId = parseResponseRec__Helper__addTodoNode(_todoGraphData, level = 4, jsonObject, jsonObject.typeName);
+			if (prevNodeId) parseResponseRec__Helper__addTodoEdge(_todoGraphData, level = 4, prevNodeId, newNodeId);
+			prevNodeId = newNodeId;
+		}
+		{
+			parseResponseRec__Helper__addTodoEdge(_todoGraphData, level = 4, prevNodeId, parentIdNode);
+		}
+	}
+}
+
+
+function parseResponseRec__OLD(_todoGraphData, json, typeName, parentNodeId, level) {
+	var level = level || 0
+	var parentNodeId = parentNodeId || null
+	DBG && console.log('DBG::parseResponseRec', {json:json, typeName:typeName, parentNodeId:parentNodeId, isString: p5Utils__isString(json), isArray: p5Utils__isArray(json), isObject: p5Utils__isObject(json)});
+	if (p5Utils__isArray(json)) {
+		// TODO: create named group
+		var isXlinkList = (json.length > 0 && p5Utils__isString(json[0]))
+		json.forEach(function (subJson) {
+			if (isXlinkList) {
+				parseResponseXlinkListRec(_todoGraphData, subJson, typeName, parentNodeId, level)
+			} else {
+				parseResponseRec(_todoGraphData, subJson, typeName, parentNodeId, level)
+			}
+		})
+	} else if (p5Utils__isObject(json) && isP5LinkObject(json)) {
+		DBG && console.log('DBG::parseResponseRec isP5LinkObject');
+		parseResponseP5Link(_todoGraphData, json, typeName, parentNodeId, level)
+	} else if (p5Utils__isObject(json)) {
+		// _todoGraphData.nodes.add({ id: nodeId, label: nodeId })
+		if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
+		var nodeObject = dataMakeNode({
+			typeName: typeName,
+			primaryKey: (json['ID']) ? json['ID'] : null, // TODO: get primaryKey from object
+			row: json,
+		})
+		var nodeId = nodeObject.id
+
+		if ("default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row" === typeName) {
+			parseResponseRec__row(_todoGraphData, json, typeName, parentNodeId, level)
+		}
+		else if ("default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object" === typeName) {
+			// parseResponseRec__row_object(_todoGraphData, json, typeName, parentNodeId, level)
+			Object.keys(json).filter(function (fieldName) {
+				return (fieldName.indexOf(':') > -1)
+			})
+			.forEach(function (fieldName) {
+				var value = json[fieldName]
+				parseResponseRec(_todoGraphData, value, fieldName, parentNodeId, level + 1)
+			})
+		}
+		else {
+			DBG && console.warn('DBG::parseResponseRec: obj node.push', { id: nodeObject.id, parentNodeId, typeName, nodeObject });
+			_todoGraphData[level].nodes.push(nodeObject)
+			if (parentNodeId) {
+				_todoGraphData[level].edges.push(dataMakeEdge(parentNodeId, nodeObject))
+			}
+			Object.keys(json).filter(function (fieldName) {
+				return (fieldName.indexOf(':') > -1)
+			})
+			.forEach(function (fieldName) {
+				var value = json[fieldName]
+				parseResponseRec(_todoGraphData, value, fieldName, nodeId, level + 1)
+			})
+		}
+	} else if (p5Utils__isString(json)) {
+		DBG && console.log('TODO: Not implemented - parseResponseRec isString');
+	} else {
+		DBG && console.log('TODO: Not implemented - parseResponseRec is not string, not array and not object');
+	}
+}
+function parseResponseXlinkListRec(_todoGraphData, json, typeName, parentNodeId, level) {
+	DBG && console.log('DBG::parseResponseRec:XlinkList', {json:json, typeName:typeName, parentNodeId:parentNodeId, isString: p5Utils__isString(json), isArray: p5Utils__isArray(json), isObject: p5Utils__isObject(json)});
+	if (p5Utils__isString(json)) { // xlink "https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI#BI_audit_ENERGA_RUM_KONTRAHENCI.9233",
+		if ("default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object" === typeName) return;
+		if ("default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row" === typeName) return;
+		var nodeId = json.substr(json.indexOf('#') + 1)
+		{
+			// _graphData.nodes.add({ id: nodeId, label: nodeId })
+			if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
+			var nodeObject = dataMakeXlinkNode({
+				xlink: json,
+				typeName: typeName,
+			})
+			DBG && console.warn('DBG::parseResponseRec: xlink node.push', { id: nodeObject.id, parentNodeId, typeName, nodeObject });
+			_todoGraphData[level].nodes.push(nodeObject)
+			if (parentNodeId) {
+				_todoGraphData[level].edges.push(dataMakeEdge(parentNodeId, nodeObject))
+			}
+		}
+	} else if (p5Utils__isObject(json) && isP5LinkObject(json)) {
+		parseResponseP5Link(_todoGraphData, json, typeName, parentNodeId, level)
+	} else if (p5Utils__isObject(json)) {
+		DBG && console.warn('TODO: Not implemented - parseResponseRec:XlinkList is object', {json:json, typeName:typeName, parentNodeId:parentNodeId, isString: p5Utils__isString(json), isArray: p5Utils__isArray(json), isObject: p5Utils__isObject(json)});
+		parseResponseRec(_todoGraphData, json, typeName, parentNodeId, level + 1)
+	} else {
+		DBG && console.warn('TODO: Not implemented - parseResponseRec:XlinkList is not string and not object');
+	}
+}
+function parseResponseP5Link(_todoGraphData, json, typeName, parentNodeId, level) {
+	DBG && console.log('parseResponseRec isObject and P5Link - fetch more xlink object');
+	// example json: { type: "next",
+	//  @backRefNS: "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA",
+	//  @backRefPK: "42",
+	//  @typeName: "default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_P…ow:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row",
+	//  @startIndex: "10" }
+	if (!parentNodeId) throw "Missing parentNodeId for ref link object";
+	var objectName = typeName.substr(typeName.indexOf(':') + 1)
+	{
+		// _graphData.nodes.add({ id: nodeId, label: nodeId })
+		if (!_todoGraphData[level]) _todoGraphData[level] = { nodes: [], edges: [] }
+		switch (json.type) {
+			case 'next': {
+        // TODO: add fetch next node
+				// var nodeObject = dataMakeFetchMoreNode({
+				// 	parentNodeId: parentNodeId,
+				// 	type: json.type,
+				// 	objectName: objectName,
+				// 	ref: json,
+				// })
+				// _todoGraphData[level].nodes.push(nodeObject)
+				// _todoGraphData[level].edges.push(dataMakeFetchMoreEdge(parentNodeId, nodeObject))
+			} break;
+			default: {
+				DBG && console.log('TODO: Not implemented - parseResponseRec isObject with type "'+json.type+'" - fetch more xlink object');
+			}
+		}
+	}
+}
+
+function parseResponseRec__row(_todoGraphData, json, typeName, parentNodeId, level) {
+	var nodeObject = dataMakeNode({
+		typeName: typeName,
+		primaryKey: (json['ID']) ? json['ID'] : null, // TODO: get primaryKey from object
+	})
+	var nodeId = nodeObject.id
+
+	// 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
+	// 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
+	// 'default_db__x3A__BI_audit_KRS:BI_audit_KRS' --> Kontrahenci
+	var rowObjectChildrens = []
+	var rowTN = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'
+	var rowObjTN = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object'
+	// { row: row_obj: [ { ID, kontr: [ "http...kontr.ID" ] }, { ID, kontr: [ "http...krs.ID" ] } ], ... }
+	var rowJson = json
+	if (rowJson[rowObjTN] && rowJson[rowObjTN].length > 1) {
+		var pathItems = []
+		rowJson[rowObjTN].forEach(function (rowObjJson) {
+			Object.keys(rowObjJson)
+				.filter(function (rowObjFld) { return (-1 !== rowObjFld.indexOf(':')); })
+				.filter(function (rowObjRefFld) { return (rowObjJson[rowObjRefFld] && rowObjJson[rowObjRefFld].length); })
+				.forEach(function (rowObjRefFld) {
+					pathItems.push([ rowObjRefFld, rowObjJson[rowObjRefFld][0] ])
+				})
+		})
+	}
+	// console.log('node('+nodeId+') pathItems:', pathItems);
+	var lastParentFid = null
+	pathItems.reverse().forEach(function (pathItem) {
+		var nodeObject = ('string' === typeof pathItem[1])
+		? dataMakeXlinkNode({
+				xlink: pathItem[1],
+				typeName: pathItem[0]
+			})
+		:	 dataMakeNode({
+				typeName: pathItem[0],
+				primaryKey: (pathItem[1]['ID']) ? pathItem[1]['ID'] : null,
+				row: pathItem[1]
+			})
+		;
+		// _todoGraphData[todoLevel].nodes.push(nodeObject) // already added below
+		if (lastParentFid) _todoGraphData[level].edges.push(dataMakeEdge(lastParentFid, nodeObject))
+		lastParentFid = nodeObject.id
+	})
+
+	Object.keys(json).filter(function (fieldName) {
+		return (fieldName.indexOf(':') > -1)
+	})
+	.forEach(function (fieldName) {
+		var value = json[fieldName]
+		parseResponseRec(_todoGraphData, value, fieldName, parentNodeId, level + 1)
+	})
+}
+
+function parseGraphRec(items, featureType, parentFeatureId) { // TODO: not used
+	var parentFeatureId = parentFeatureId || null
+	var nodesArray = []
+	var linksArray = []
+	if (!items) return;
+	items.forEach(function (item) {
+		if ('string' === typeof item) {
+			DBG && console.log('TODO: xlink "'+item+'": ', {item:item, parentFeatureId:parentFeatureId})
+			return;
+		}
+		if (!item['ID']) {
+			DBG && console.log('TODO: SKIP item('+featureType+') - missing ID: ', {item:item, parentFeatureId:parentFeatureId})
+			return;
+		}
+		var id = item['ID']
+		console.log('item('+featureType+'): ', {item:item, parentFeatureId:parentFeatureId})
+		var featureId = featureType + '.' + id
+		Object.keys(item).filter(function (fieldName) { return ('ID' !== fieldName); })
+		.forEach(function (fieldName) {
+			parseGraphRec(item[fieldName], fieldName, featureId)
+		})
+	})
+  // items.forEach(element => {
+  //   const rowObject = hasTargetArray(element);
+  //   if (rowObject)
+  //     rowObject.array.forEach(objectElement => {
+  //       const trackNode = hasTargetArray(objectElement);
+  //       if (trackNode) {
+  //         let group = trackNode.name;
+  //         let expanded = false;
+  //         if (expansion && expansion.type && group === expansion.type) {
+  //           group = trackNode.array[0][expansion.criteria];
+  //           expanded = true;
+  //         }
+  //         nodes[group] = {expanded: expanded, type: trackNode.name};
+  //         instanceTypes[trackNode.array[0].ID] = group;
+  //       }
+  //     });
+  // });
+
+	return {
+		nodes: nodesArray,
+		links: linksArray
+	}
+}
+
+
+function isP5LinkObject(json) {
+	if ( !('type' in json) || !json['type'] ) return false;
+	if ( !('value' in json) || !json['value'] ) return false;
+	if ( !('@typeName' in json) || !json['@typeName'] ) return false;
+	if ( !('@startIndex' in json) || !json['@startIndex'] ) return false;
+	if ( !('@backRefPK' in json) || !json['@backRefPK'] ) return false;
+	if ( !('@backRefNS' in json) || !json['@backRefNS'] ) return false;
+	return true;
+}
+
+function dataMakeNode(params) {
+	var objectName = params.typeName.substr(params.typeName.indexOf(':') + 1)
+	var nodeId = objectName + '.' + params.primaryKey // TODO: primaryKey?
+	var graphNode = {
+		id: nodeId,
+		name: nodeId,
+		group: objectName,
+		_loaded: true,
+		typeName: params.typeName,
+		primaryKey: params.primaryKey // TODO: _primaryKey
+	}
+	if (params.row) graphNode.row = params.row
+	return graphAddNodeLabel(graphNode)
+}
+function dataMakeEdge(parentNodeId, nodeObject) {
+	return {
+		id: parentNodeId + nodeObject.id,
+		source: parentNodeId,
+		target: nodeObject.id,
+	}
+}
+function dataMakeXlinkNode(params) {
+	var objectName = params.typeName.substr(params.typeName.indexOf(':') + 1)
+	var nodeId = params.xlink.substr(params.xlink.indexOf('#') + 1)
+	var primaryKey = nodeId.substr(nodeId.lastIndexOf('.') + 1)
+	var graphNode = {
+		id: nodeId,
+		name: nodeId,
+		group: objectName,
+		_loaded: false,
+		typeName: params.typeName,
+		primaryKey: primaryKey
+	}
+	return graphAddNodeLabel(graphNode)
+}
+
+function dataMakeFetchMoreNode(params) {
+	// params = {
+	// 	parentNodeId: parentNodeId,
+	// 	type: json.type,
+	// 	objectName: objectName,
+	// 	ref: json,
+	// }
+	DBG && console.log('DBG dataMakeFetchMoreNode(params)', params)
+	var nodeId = params.parentNodeId+'fetch-more-features-'+params.type+'-on-' + params.objectName;
+	return {
+		id: nodeId,
+		label: 'Pobierz więcej (+)',
+		group: 'fetch-more-data', // params.objectName,
+		_loaded: false,
+		_type: 'ref',
+		parentNodeId: params.parentNodeId,
+		ref: params.ref,
+		// typeName: typeName,
+		// primaryKey: nodeId.substr(nodeId.lastIndexOf('.') + 1)
+	};
+}
+function dataMakeFetchMoreEdge(parentNodeId, fetchMoreNode) {
+	// @param parentNodeId - from node id
+	// @param fetchMoreNode - from dataMakeFetchMoreNode
+	DBG && console.log('DBG dataMakeFetchMoreEdge(parentNodeId, fetchMoreNode)', {parentNodeId:parentNodeId, fetchMoreNode:fetchMoreNode})
+	return {
+		id: fetchMoreNode.id,
+		from: parentNodeId,
+		to: fetchMoreNode.id
+	}
+}
+function makeShortLabel(label) { // TODO: shorter name
+	// BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.1234567
+
+	if (label.length < 30) return label;
+	var exLabel = label.split('.')
+	if (exLabel.length !== 2) return label;
+	return exLabel[0].substr(0, 24) + '...' + exLabel[0].substr(-10) + '.' + exLabel[1];
+}
+function graphAddNodeLabel(graphNode) {
+	// var graphNode = {
+	// 	id: nodeId,
+	// 	name: nodeId,
+	// 	group: objectName,
+	// 	_loaded: true,
+	// 	typeName: params.typeName,
+	// 	primaryKey: params.primaryKey // TODO: _primaryKey
+	// }
+	var label = graphNode.id // TODO: get from schema assert @label attribute
+	label = makeShortLabel(graphNode.id)
+	switch (graphNode.typeName) {
+		case 'default_db__x3A__BI_audit_KRS:BI_audit_KRS': {
+			// <xs:assert test="@default_db__x3A__BI_audit_KRS:label = concat(nazwa, ' ', krs, ' ', S_miejscowosc)" id="I_audit_KRS___d6e76977-1">
+			if (graphNode.row) label = [graphNode.row.nazwa, graphNode.row.krs, graphNode.row.S_miejscowosc].filter(function (val) { return val; }).join(' ');
+			label = (label) ? label : makeShortLabel(graphNode.id)
+			label = label + ' (krs)'
+		} break;
+		case 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY': {
+			// <xs:assert id="_PRACOWNICY___d6e76324-1" test="@label = concat(imiona, ' ', nazwisko, ' ', miejscowosc)"/>
+			if (graphNode.row) label = [graphNode.row.imiona, graphNode.row.nazwisko, graphNode.row.miejscowosc].filter(function (val) { return val; }).join(' ');
+			label = (label) ? label : makeShortLabel(graphNode.id)
+			label = label + ' (pracownicy)'
+		} break;
+		case 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI': {
+			// <xs:assert id="KONTRAHENCI___d6e76526-1" test="@label = concat(substr(Pelna_nazwa_kontrahenta, 0, 20, '\n umów na kwotę ', @sum))"/>
+			if (graphNode.row) label = [graphNode.row.Pelna_nazwa_kontrahenta].filter(function (val) { return val; }).join(' ');
+			label = (label) ? label : makeShortLabel(graphNode.id)
+			label = label + ' (kontrahent)'
+		} break;
+		case 'default_db__x3A__BI_audit_CEIDG:BI_audit_CEIDG': {
+			// <xs:assert test="@label = concat(nazwisko, substring(firma, 1, 20))"/>
+			if (graphNode.row) label = [graphNode.row.nazwisko, graphNode.row.firma].filter(function (val) { return val; }).join(' ');
+			label = (label) ? label : makeShortLabel(graphNode.id)
+			label = label + ' (ceidg)'
+		} break;
+		case 'default_db__x3A__BI_audit_MSIG:BI_audit_MSIG': {
+			// <xs:assert test="@label = substring(nazwa, 1, 20)"/>
+			if (graphNode.row) label = [graphNode.row.nazwa].filter(function (val) { return val; }).join(' ');
+			label = (label) ? label : makeShortLabel(graphNode.id)
+			label = label + ' (msig)'
+		} break;
+	}
+	return Object.assign(graphNode, {
+		label: label,
+	})
+}
+
+
+module.exports = {
+	graphShowHide: graphShowHide,
+	graphRender: graphRender,
+	graphRaportRender: graphRaportRender,
+	/** @example: graphRaportRender({
+	 *		msg: "Pobrano dane",
+	 *		typeName: ('pracownicy' === nameSection) ? 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY' : 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+	 *		items: items
+	 *	}, graphResultNode)
+	 */
+}

+ 419 - 0
tools/Anton1.php.graphTest.php

@@ -0,0 +1,419 @@
+<?php
+
+UI::gora();
+UI::inlineJS(dirname(__FILE__) . '/Anton1.php' . '.graphShowHide.js', [
+	'DBG' => V::get('DBG', 0, $_GET),
+	'FIELD_LIST_PRACOWNICY' => array_merge(
+		array_map(function ($fieldName) {
+			return "f_{$fieldName}";
+		}, self::$FIELD_LIST_PRACOWNICY),
+		[
+			'f_Adresy',
+		]
+	),
+	'FIELD_LIST_KONTRAHENCI' => array_map(function ($fieldName) {
+		return "f_{$fieldName}";
+	}, self::$FIELD_LIST_KONTRAHENCI),
+]);
+
+// TODO: cannot use <?xml version="1.0" encoding="UTF-8"
+echo UI::h('script', [ 'id' => "graphxml", 'type' => "text/xmldata" ], '
+<wfs:FeatureCollection xmlns:wfs="http://www.opengis.net/wfs" xmlns="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:default_db__x3A__BI_audit_ENERGA_PRACOWNICY="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_PRACOWNICY" xmlns:p5="https://biuro.biall-net.pl/wfs" xmlns:default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object" xmlns:default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row" xmlns:default_db__x3A__BI_audit_KRS="https://biuro.biall-net.pl/wfs/default_db/BI_audit_KRS" xmlns:default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI" xmlns:default_db__x3A__BI_audit_MSIG="https://biuro.biall-net.pl/wfs/default_db/BI_audit_MSIG" xmlns:default_db__x3A__BI_audit_CEIDG="https://biuro.biall-net.pl/wfs/default_db/BI_audit_CEIDG" xsi:schemaLocation="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_PRACOWNICY https://biuro.biall-net.pl/dev-pl/se-projects/anton1/SE//wfs-data.php/default_db/?SERVICE=WFS&amp;VERSION=1.0.0&amp;TYPENAME=default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY&amp;REQUEST=DescribeFeatureType" numberMatched="unknown" numberReturned="1" next="https://biuro.biall-net.pl/dev-pl/se-projects/anton1/SE//wfs-data.php/default_db/?SERVICE=WFS&amp;VERSION=1.0.0&amp;REQUEST=GetFeature&amp;TYPENAME=default_db__x3A__BI_audit_ENERGA_PRACOWNICY%3ABI_audit_ENERGA_PRACOWNICY&amp;SRSNAME=EPSG%3A3003&amp;sortBy=ID+D&amp;maxFeatures=20&amp;startIndex=20">
+<gml:featureMember>
+<default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY fid="BI_audit_ENERGA_PRACOWNICY.12" p5:primaryKey="12">
+ <default_db__x3A__BI_audit_ENERGA_PRACOWNICY:ID>12</default_db__x3A__BI_audit_ENERGA_PRACOWNICY:ID>
+ <default_db__x3A__BI_audit_ENERGA_PRACOWNICY:imiona>Robert</default_db__x3A__BI_audit_ENERGA_PRACOWNICY:imiona>
+ <default_db__x3A__BI_audit_ENERGA_PRACOWNICY:nazwisko>Szaj</default_db__x3A__BI_audit_ENERGA_PRACOWNICY:nazwisko>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677360" p5:primaryKey="2677360">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677360</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386066" p5:primaryKey="386066">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386066</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677363" p5:primaryKey="2677363">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677363</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17240" p5:primaryKey="17240">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17240</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677362" p5:primaryKey="2677362">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677362</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677361" p5:primaryKey="2677361">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677361</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677360" p5:primaryKey="2677360"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677354" p5:primaryKey="2677354">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677354</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386065" p5:primaryKey="386065">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386065</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677359" p5:primaryKey="2677359">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677359</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17285" p5:primaryKey="17285">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17285</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>KLUB SPORTOWY &quot;SYRENA&quot; MŁYNARY</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677358" p5:primaryKey="2677358">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677358</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.69474" p5:primaryKey="69474">
+		 <default_db__x3A__BI_audit_KRS:ID>69474</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000098611</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>KLUB SPORTOWY &quot;SYRENA&quot; MŁYNARY</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>MŁYNARY</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677357" p5:primaryKey="2677357">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677357</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677356" p5:primaryKey="2677356">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677356</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677355" p5:primaryKey="2677355">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677355</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677354" p5:primaryKey="2677354"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677347" p5:primaryKey="2677347">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677347</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386064" p5:primaryKey="386064">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386064</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677353" p5:primaryKey="2677353">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677353</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17285" p5:primaryKey="17285">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17285</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>KLUB SPORTOWY &quot;SYRENA&quot; MŁYNARY</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677352" p5:primaryKey="2677352">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677352</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677351" p5:primaryKey="2677351">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677351</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.69474" p5:primaryKey="69474">
+		 <default_db__x3A__BI_audit_KRS:ID>69474</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000098611</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>KLUB SPORTOWY &quot;SYRENA&quot; MŁYNARY</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>MŁYNARY</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677350" p5:primaryKey="2677350">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677350</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677349" p5:primaryKey="2677349">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677349</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677348" p5:primaryKey="2677348">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677348</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677347" p5:primaryKey="2677347"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677340" p5:primaryKey="2677340">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677340</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386063" p5:primaryKey="386063">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386063</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677346" p5:primaryKey="2677346">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677346</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17246" p5:primaryKey="17246">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17246</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>&quot;FUNDACJA ENERGA&quot;</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677345" p5:primaryKey="2677345">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677345</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.242187" p5:primaryKey="242187">
+		 <default_db__x3A__BI_audit_KRS:ID>242187</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000326853</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>&quot;FUNDACJA ENERGA&quot;</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677344" p5:primaryKey="2677344">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677344</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677343" p5:primaryKey="2677343">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677343</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677342" p5:primaryKey="2677342">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677342</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677341" p5:primaryKey="2677341">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677341</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677340" p5:primaryKey="2677340"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677333" p5:primaryKey="2677333">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677333</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386062" p5:primaryKey="386062">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386062</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677339" p5:primaryKey="2677339">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677339</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17298" p5:primaryKey="17298">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17298</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>ENERGA ELEKTROWNIE OSTROŁĘKA SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677338" p5:primaryKey="2677338">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677338</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677337" p5:primaryKey="2677337">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677337</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.260109" p5:primaryKey="260109">
+		 <default_db__x3A__BI_audit_KRS:ID>260109</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000348557</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ELEKTROWNIA OSTROŁĘKA SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>OSTROŁĘKA</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677336" p5:primaryKey="2677336">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677336</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677335" p5:primaryKey="2677335">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677335</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677334" p5:primaryKey="2677334">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677334</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677333" p5:primaryKey="2677333"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677326" p5:primaryKey="2677326">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677326</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386061" p5:primaryKey="386061">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386061</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677332" p5:primaryKey="2677332">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677332</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17240" p5:primaryKey="17240">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17240</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677331" p5:primaryKey="2677331">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677331</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677330" p5:primaryKey="2677330">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677330</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_MSIG:BI_audit_MSIG fid="BI_audit_MSIG.191597" p5:primaryKey="191597">
+		 <default_db__x3A__BI_audit_MSIG:ID>191597</default_db__x3A__BI_audit_MSIG:ID>
+		 <default_db__x3A__BI_audit_MSIG:nazwa>BREVA SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ</default_db__x3A__BI_audit_MSIG:nazwa>
+		</default_db__x3A__BI_audit_MSIG:BI_audit_MSIG>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677329" p5:primaryKey="2677329">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677329</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677328" p5:primaryKey="2677328">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677328</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677327" p5:primaryKey="2677327">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677327</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677326" p5:primaryKey="2677326"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677319" p5:primaryKey="2677319">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677319</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386060" p5:primaryKey="386060">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386060</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677325" p5:primaryKey="2677325">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677325</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17240" p5:primaryKey="17240">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17240</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677324" p5:primaryKey="2677324">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677324</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677323" p5:primaryKey="2677323">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677323</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_MSIG:BI_audit_MSIG fid="BI_audit_MSIG.191597" p5:primaryKey="191597">
+		 <default_db__x3A__BI_audit_MSIG:ID>191597</default_db__x3A__BI_audit_MSIG:ID>
+		 <default_db__x3A__BI_audit_MSIG:nazwa>BREVA SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ</default_db__x3A__BI_audit_MSIG:nazwa>
+		</default_db__x3A__BI_audit_MSIG:BI_audit_MSIG>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677322" p5:primaryKey="2677322">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677322</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677321" p5:primaryKey="2677321">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677321</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677320" p5:primaryKey="2677320">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677320</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677319" p5:primaryKey="2677319"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677314" p5:primaryKey="2677314">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677314</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386059" p5:primaryKey="386059">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386059</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677318" p5:primaryKey="2677318">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677318</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17240" p5:primaryKey="17240">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17240</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677317" p5:primaryKey="2677317">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677317</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677316" p5:primaryKey="2677316">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677316</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677315" p5:primaryKey="2677315">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677315</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677314" p5:primaryKey="2677314"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677308" p5:primaryKey="2677308">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677308</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386058" p5:primaryKey="386058">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386058</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677313" p5:primaryKey="2677313">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677313</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17398" p5:primaryKey="17398">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17398</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>ENERGA KOGENERACJA SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677312" p5:primaryKey="2677312">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677312</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.148850" p5:primaryKey="148850">
+		 <default_db__x3A__BI_audit_KRS:ID>148850</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000207049</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA KOGENERACJA SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>ELBLĄG</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677311" p5:primaryKey="2677311">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677311</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677310" p5:primaryKey="2677310">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677310</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677309" p5:primaryKey="2677309">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677309</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677308" p5:primaryKey="2677308"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677301" p5:primaryKey="2677301">
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677301</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row.386057" p5:primaryKey="386057">
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>386057</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:ID>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677307" p5:primaryKey="2677307">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677307</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI fid="BI_audit_ENERGA_RUM_KONTRAHENCI.17398" p5:primaryKey="17398">
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>17398</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:ID>
+		 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>ENERGA KOGENERACJA SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:Pelna_nazwa_kontrahenta>
+		</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677306" p5:primaryKey="2677306">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677306</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677305" p5:primaryKey="2677305">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677305</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.148850" p5:primaryKey="148850">
+		 <default_db__x3A__BI_audit_KRS:ID>148850</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000207049</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA KOGENERACJA SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>ELBLĄG</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677304" p5:primaryKey="2677304">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677304</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677303" p5:primaryKey="2677303">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677303</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+		<default_db__x3A__BI_audit_KRS:BI_audit_KRS fid="BI_audit_KRS.403882" p5:primaryKey="403882">
+		 <default_db__x3A__BI_audit_KRS:ID>403882</default_db__x3A__BI_audit_KRS:ID>
+		 <default_db__x3A__BI_audit_KRS:krs>0000512140</default_db__x3A__BI_audit_KRS:krs>
+		 <default_db__x3A__BI_audit_KRS:nazwa>ENERGA WYTWARZANIE SPÓŁKA AKCYJNA</default_db__x3A__BI_audit_KRS:nazwa>
+		 <default_db__x3A__BI_audit_KRS:S_miejscowosc>GDAŃSK</default_db__x3A__BI_audit_KRS:S_miejscowosc>
+		</default_db__x3A__BI_audit_KRS:BI_audit_KRS>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object fid="BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677302" p5:primaryKey="2677302">
+		<default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>2677302</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:ID>
+	 </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+	 <default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object xlink:href="https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object#BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object.2677301" p5:primaryKey="2677301"/>
+	</default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row>
+ </default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object>
+ <p5:links>
+	<p5:next p5:typeName="default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object" p5:backRefNS="default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY" p5:backRefPK="12" p5:startIndex="10">https://biuro.biall-net.pl/dev-pl/se-projects/anton1/SE//wfs-data.php/default_db/?SERVICE=WFS&amp;VERSION=1.0.0&amp;TYPENAME=default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object&amp;REQUEST=GetFeature&amp;backRefNS=default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY&amp;backRefPK=12&amp;backRefField=default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object&amp;maxFeatures=10&amp;startIndex=10</p5:next>
+ </p5:links>
+</default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY>
+</gml:featureMember>
+</wfs:FeatureCollection>
+');
+echo UI::h('div', [ 'id' => "graph" ]);
+echo UI::h('script', [ 'type' => "text/javascript" ], "
+	var xmlString = document.getElementById('graphxml').innerHTML;
+	var graphResultNode = document.getElementById('graph');
+	p5WFS_GetFeatureFromXmlString(xmlString).then(function (items) {
+		graphRaportRender({
+			msg: '',
+			// typeName: ('pracownicy' === nameSection) ? 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY' : 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
+			typeName: 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+			items: items
+		}, graphResultNode)
+	})
+");

+ 24 - 0
tools/Anton1.php.page-about.view.php

@@ -0,0 +1,24 @@
+<div class="container-fluid">
+  <div class="container"  style="padding: 50px 0;">
+      <h1>O Programie</h1>
+      <h4>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
+      <h5>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...."</h5>
+      <hr>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec ipsum vitae nibh efficitur vulputate id id ipsum. Integer congue nec dui ut rutrum. Nullam quis elit tellus. Nam quis ornare tortor. Mauris fermentum sem orci, eget dignissim risus fringilla vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum lacinia consectetur sollicitudin. Maecenas quis faucibus elit, eu iaculis leo. Integer viverra libero ac egestas laoreet. Suspendisse cursus tellus nec dapibus mattis. Integer eget felis porta, lacinia tellus ut, bibendum odio.
+          </p>
+          <p>
+            Nam rhoncus tortor quam, at dapibus leo commodo quis. Aliquam tempor, sapien quis facilisis facilisis, justo odio laoreet lorem, in accumsan risus erat in nulla. Aenean at risus egestas, egestas quam vitae, porta est. Curabitur non ullamcorper purus. Mauris lacinia diam et purus auctor, a porta est volutpat. Nullam in urna ut dui mattis vulputate. Nullam pharetra diam in metus vestibulum, eu dictum urna tempus. Phasellus porttitor nisi nisl, ut finibus felis consectetur at. Nulla malesuada enim eget tellus fermentum, vitae ullamcorper ante congue. Praesent fermentum finibus commodo. Sed venenatis semper nulla, in viverra mi vehicula nec. Nam est sem, posuere vel turpis ac, cursus maximus erat.
+          </p>
+          <p>
+            Vivamus feugiat suscipit nisl eget ornare. Nulla sodales ex lacus, sed tincidunt felis pulvinar vitae. Mauris ut magna quis ante ornare ullamcorper. Curabitur ut sodales sapien. Donec in arcu lacinia, tempor augue et, imperdiet est. Aenean in orci pharetra, interdum sapien nec, posuere lectus. Vivamus gravida turpis lacus, imperdiet lobortis est euismod non. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi maximus tellus in enim condimentum tristique. Phasellus fringilla ultrices arcu. Fusce egestas tellus eu orci interdum, non consectetur sem consequat. Sed vehicula, dui vitae convallis aliquam, neque risus bibendum mi, in bibendum odio enim in mi.
+          </p>
+          <p>
+            Ut eu justo mauris. Morbi dignissim dolor id ante molestie eleifend. Praesent eu eleifend sapien. Vestibulum placerat tortor vel pellentesque facilisis. Sed pharetra, dolor vel aliquet placerat, metus nulla tempus massa, vitae pulvinar justo lorem ac lectus. Mauris maximus vehicula accumsan. Morbi vestibulum malesuada massa at sodales.
+          </p>
+          <p>
+            Nullam ut arcu tortor. Duis pretium enim erat, fringilla fermentum ligula dapibus eu. Sed eget nunc non ipsum tempus viverra. Praesent eu mi id justo lacinia scelerisque facilisis a est. Nam sit amet risus sapien. Quisque vel facilisis ipsum. Curabitur urna ipsum, bibendum imperdiet convallis at, aliquet vitae enim. Integer et erat elementum sapien sodales rhoncus at nec purus. Sed faucibus ipsum ut lectus volutpat suscipit non maximus lacus. Donec tincidunt purus ac dignissim posuere. Vestibulum id venenatis nisi, in rhoncus justo. Proin rutrum, dolor et luctus condimentum, est nunc efficitur nibh, eu vulputate ligula nisl sed lacus. Proin congue, ante eu aliquam egestas, quam dolor ultricies lectus, in ultrices ante odio at dolor. Nam in diam dapibus, pulvinar enim id, aliquet nunc. Aenean a massa mi. Curabitur molestie odio in ante mollis, quis eleifend lacus efficitur.
+          </p>
+      <hr>
+  </div>
+</div>

+ 63 - 0
tools/Anton1.php.page-help.view.php

@@ -0,0 +1,63 @@
+<!-- start:form -->
+<form method="POST" >
+  <div id="smad-form-section" class="container" style="padding: 80px 0 80px 0;">
+    <div class="row">
+      <div class="col-md-6 col-md-offset-3">
+                <div class="smad-form text-center">
+                    <div class="smad-form-header">
+                        <header style="border-bottom:1px solid #eee; margin-bottom:12px">
+                          <h1>POMOC</h1>
+                            <h3>Wypełnij formularz</h3>
+                        </header>
+                    </div>
+
+                    <div class="smad-message">
+                      <?php
+
+                      if ( isset($messageValidate['success']) ) { ?>
+                      <div class="success-send alert alert-success">Wiadomość została wysłana</div>
+                      <? } ?>
+                      <?php if ( isset($messageValidate['error']) ) { ?>
+                          <?php if (  $messageValidate['error'] == 1  ) { ?>
+                          <div class="success-send alert alert-danger">"Błąd! Wypełnij poprawnie wszystkie pola"</div>
+                          <? } ?>
+                          <?php if ( $messageValidate['error'] == 2  ) { ?>
+                          <div class="success-send alert alert-danger">Błąd! Wystąpił błąd podczas wysyłania.</div>
+                          <? }
+                        }?>
+                    </div>
+
+                    <div class="smad-form-body">
+                      <div class="form-group">
+                        <label class="control-label"><span style="padding-right: 4px;">Zgłaszający</span>
+                        </label>
+                        <div class="">
+                            <input type="text" id="help_name" name="help_name" class="form-control"  disabled value="<?php echo User::getFullName(); ?>">
+                        </div>
+                      </div>
+                      <div class="form-group">
+                        <label class="control-label"><span style="padding-right: 4px;">Email</span>
+                          <i data-toggle="popover" data-trigger="hover" title="" data-content="Email kontaktowy" class="glyphicon glyphicon-info-sign frm-help"></i>
+                        </label>
+                        <div class="">
+                            <input type="text" id="help_email" name="help_email" class="form-control" value="">
+                        </div>
+                      </div>
+                      <div class="form-group">
+                        <label class="control-label"><span style="padding-right: 4px;">Treść wiadomości</span>
+                          <i data-toggle="popover" data-trigger="hover" title="" data-content="Opisz napotkany problem" class="glyphicon glyphicon-info-sign frm-help"></i>
+                        </label>
+                        <div class="">
+                            <textarea name="help_description" class="form-control" rows="5" cols="40" ></textarea>
+                        </div>
+                      </div>
+                    </div>
+                    <div class="form-group">
+                        <button type="submit" name="button_send" value="1aaa" class="btn btn-primary">WYŚLIJ</button>
+                    </div>
+                </div>
+      </div>
+    </div>
+  </div>
+</form>
+<!-- end:form -->

+ 24 - 0
tools/Anton1.php.page-offer.view.php

@@ -0,0 +1,24 @@
+<div class="container-fluid">
+  <div class="container" style="padding: 50px 0;">
+      <h1>Oferta</h1>
+      <h4>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
+      <h5>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...."</h5>
+      <hr>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec ipsum vitae nibh efficitur vulputate id id ipsum. Integer congue nec dui ut rutrum. Nullam quis elit tellus. Nam quis ornare tortor. Mauris fermentum sem orci, eget dignissim risus fringilla vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum lacinia consectetur sollicitudin. Maecenas quis faucibus elit, eu iaculis leo. Integer viverra libero ac egestas laoreet. Suspendisse cursus tellus nec dapibus mattis. Integer eget felis porta, lacinia tellus ut, bibendum odio.
+          </p>
+          <p>
+            Nam rhoncus tortor quam, at dapibus leo commodo quis. Aliquam tempor, sapien quis facilisis facilisis, justo odio laoreet lorem, in accumsan risus erat in nulla. Aenean at risus egestas, egestas quam vitae, porta est. Curabitur non ullamcorper purus. Mauris lacinia diam et purus auctor, a porta est volutpat. Nullam in urna ut dui mattis vulputate. Nullam pharetra diam in metus vestibulum, eu dictum urna tempus. Phasellus porttitor nisi nisl, ut finibus felis consectetur at. Nulla malesuada enim eget tellus fermentum, vitae ullamcorper ante congue. Praesent fermentum finibus commodo. Sed venenatis semper nulla, in viverra mi vehicula nec. Nam est sem, posuere vel turpis ac, cursus maximus erat.
+          </p>
+          <p>
+            Vivamus feugiat suscipit nisl eget ornare. Nulla sodales ex lacus, sed tincidunt felis pulvinar vitae. Mauris ut magna quis ante ornare ullamcorper. Curabitur ut sodales sapien. Donec in arcu lacinia, tempor augue et, imperdiet est. Aenean in orci pharetra, interdum sapien nec, posuere lectus. Vivamus gravida turpis lacus, imperdiet lobortis est euismod non. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi maximus tellus in enim condimentum tristique. Phasellus fringilla ultrices arcu. Fusce egestas tellus eu orci interdum, non consectetur sem consequat. Sed vehicula, dui vitae convallis aliquam, neque risus bibendum mi, in bibendum odio enim in mi.
+          </p>
+          <p>
+            Ut eu justo mauris. Morbi dignissim dolor id ante molestie eleifend. Praesent eu eleifend sapien. Vestibulum placerat tortor vel pellentesque facilisis. Sed pharetra, dolor vel aliquet placerat, metus nulla tempus massa, vitae pulvinar justo lorem ac lectus. Mauris maximus vehicula accumsan. Morbi vestibulum malesuada massa at sodales.
+          </p>
+          <p>
+            Nullam ut arcu tortor. Duis pretium enim erat, fringilla fermentum ligula dapibus eu. Sed eget nunc non ipsum tempus viverra. Praesent eu mi id justo lacinia scelerisque facilisis a est. Nam sit amet risus sapien. Quisque vel facilisis ipsum. Curabitur urna ipsum, bibendum imperdiet convallis at, aliquet vitae enim. Integer et erat elementum sapien sodales rhoncus at nec purus. Sed faucibus ipsum ut lectus volutpat suscipit non maximus lacus. Donec tincidunt purus ac dignissim posuere. Vestibulum id venenatis nisi, in rhoncus justo. Proin rutrum, dolor et luctus condimentum, est nunc efficitur nibh, eu vulputate ligula nisl sed lacus. Proin congue, ante eu aliquam egestas, quam dolor ultricies lectus, in ultrices ante odio at dolor. Nam in diam dapibus, pulvinar enim id, aliquet nunc. Aenean a massa mi. Curabitur molestie odio in ante mollis, quis eleifend lacus efficitur.
+          </p>
+        <hr>
+  </div>
+</div>

+ 24 - 0
tools/Anton1.php.page-training.view.php

@@ -0,0 +1,24 @@
+<div class="container-fluid">
+  <div class="container" style="padding: 50px 0;">
+      <h1>Szkolenie</h1>
+      <h4>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
+      <h5>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...."</h5>
+      <hr>
+          <p>
+            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec ipsum vitae nibh efficitur vulputate id id ipsum. Integer congue nec dui ut rutrum. Nullam quis elit tellus. Nam quis ornare tortor. Mauris fermentum sem orci, eget dignissim risus fringilla vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum lacinia consectetur sollicitudin. Maecenas quis faucibus elit, eu iaculis leo. Integer viverra libero ac egestas laoreet. Suspendisse cursus tellus nec dapibus mattis. Integer eget felis porta, lacinia tellus ut, bibendum odio.
+          </p>
+          <p>
+            Nam rhoncus tortor quam, at dapibus leo commodo quis. Aliquam tempor, sapien quis facilisis facilisis, justo odio laoreet lorem, in accumsan risus erat in nulla. Aenean at risus egestas, egestas quam vitae, porta est. Curabitur non ullamcorper purus. Mauris lacinia diam et purus auctor, a porta est volutpat. Nullam in urna ut dui mattis vulputate. Nullam pharetra diam in metus vestibulum, eu dictum urna tempus. Phasellus porttitor nisi nisl, ut finibus felis consectetur at. Nulla malesuada enim eget tellus fermentum, vitae ullamcorper ante congue. Praesent fermentum finibus commodo. Sed venenatis semper nulla, in viverra mi vehicula nec. Nam est sem, posuere vel turpis ac, cursus maximus erat.
+          </p>
+          <p>
+            Vivamus feugiat suscipit nisl eget ornare. Nulla sodales ex lacus, sed tincidunt felis pulvinar vitae. Mauris ut magna quis ante ornare ullamcorper. Curabitur ut sodales sapien. Donec in arcu lacinia, tempor augue et, imperdiet est. Aenean in orci pharetra, interdum sapien nec, posuere lectus. Vivamus gravida turpis lacus, imperdiet lobortis est euismod non. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi maximus tellus in enim condimentum tristique. Phasellus fringilla ultrices arcu. Fusce egestas tellus eu orci interdum, non consectetur sem consequat. Sed vehicula, dui vitae convallis aliquam, neque risus bibendum mi, in bibendum odio enim in mi.
+          </p>
+          <p>
+            Ut eu justo mauris. Morbi dignissim dolor id ante molestie eleifend. Praesent eu eleifend sapien. Vestibulum placerat tortor vel pellentesque facilisis. Sed pharetra, dolor vel aliquet placerat, metus nulla tempus massa, vitae pulvinar justo lorem ac lectus. Mauris maximus vehicula accumsan. Morbi vestibulum malesuada massa at sodales.
+          </p>
+          <p>
+            Nullam ut arcu tortor. Duis pretium enim erat, fringilla fermentum ligula dapibus eu. Sed eget nunc non ipsum tempus viverra. Praesent eu mi id justo lacinia scelerisque facilisis a est. Nam sit amet risus sapien. Quisque vel facilisis ipsum. Curabitur urna ipsum, bibendum imperdiet convallis at, aliquet vitae enim. Integer et erat elementum sapien sodales rhoncus at nec purus. Sed faucibus ipsum ut lectus volutpat suscipit non maximus lacus. Donec tincidunt purus ac dignissim posuere. Vestibulum id venenatis nisi, in rhoncus justo. Proin rutrum, dolor et luctus condimentum, est nunc efficitur nibh, eu vulputate ligula nisl sed lacus. Proin congue, ante eu aliquam egestas, quam dolor ultricies lectus, in ultrices ante odio at dolor. Nam in diam dapibus, pulvinar enim id, aliquet nunc. Aenean a massa mi. Curabitur molestie odio in ante mollis, quis eleifend lacus efficitur.
+          </p>
+        <hr>
+  </div>
+</div>

+ 171 - 0
tools/Anton1.php.store.js

@@ -0,0 +1,171 @@
+var DBG = DBG || 0;
+var DBG1 = true;
+if (!STORE_NAME) throw "Store name not defined";
+
+var Redux = global.p5VendorJs.Redux;
+var ReduxThunk = global.p5VendorJs.ReduxThunk;
+var createStoreWithThunkMiddleware = Redux.applyMiddleware(ReduxThunk)(Redux.createStore); // TODO: to vendor.js
+
+function getDefaultState() {
+	return {
+		totalOdPracownicy: 0,
+		totalOdPozostale: 0,
+		totalDoKontrahenci: 0,
+		totalDoPozostale: 0,
+		pozostaleOd: [],
+		pozostaleDo: [],
+		depth: 6,
+		onlyTargets: true, // true: "y", false: "n"
+		title: 'Raport bez tytułu z dnia ' + CURRENT_DATE,
+	}
+}
+function getLocalStorageState() {
+	DBG && console.log('DBG: anton1 store INIT');
+	var defaultState = getDefaultState();
+	var defaultOnlyTargetsString = defaultState.onlyTargets ? "y" : "n"
+	var pozostaleOd = getListFromLocalStorage(getSelectedListLocalStorageKey('OD'));
+	var pozostaleDo = getListFromLocalStorage(getSelectedListLocalStorageKey('DO'));
+	var pracownicyIds = getListFromLocalStorage('Anton1.biAuditForm.pracownicyIds');
+	var kontrahenciIds = getListFromLocalStorage('Anton1.biAuditForm.kontrahenciIds');
+	return {
+		totalOdPracownicy: pracownicyIds.length,
+		totalOdPozostale: pozostaleOd.length,
+		totalDoKontrahenci: kontrahenciIds.length,
+		totalDoPozostale: pozostaleDo.length,
+		pozostaleOd: pozostaleOd,
+		pozostaleDo: pozostaleDo,
+		depth: getSignedIntFromLocalStorage('Anton1.biAuditForm.depth', defaultState.depth),
+		onlyTargets: "n" === getStringFromLocalStorage('Anton1.biAuditForm.analizaOnlyTargets', defaultOnlyTargetsString) ? false : true,
+		title: getStringFromLocalStorage('Anton1.biAuditForm.smadReaportTitle', defaultState.title),
+	}
+}
+
+
+function anton1RaportStore(state, action) {
+	var prevState = state || getLocalStorageState();
+	DBG && console.warn('DBG: anton1 store', { prevState, action, actionType: action.type });
+	switch (action.type) {
+		case 'UPDATE': return Object.assign(prevState, {
+			totalOdPracownicy: action.totalOdPracownicy,
+			totalDoKontrahenci: action.totalDoKontrahenci,
+		});
+		case 'ADD_OD': {
+			var listPozostaleOd = prevState.pozostaleOd.concat(action.featureKey);
+			localStorage.setItem(getSelectedListLocalStorageKey('OD'), JSON.stringify(listPozostaleOd))
+			return Object.assign(prevState, {
+				pozostaleOd: listPozostaleOd,
+				totalOdPozostale: listPozostaleOd.length,
+			})
+		}
+		case 'ADD_DO': {
+			var listPozostaleDo = prevState.pozostaleDo.concat(action.featureKey);
+			localStorage.setItem(getSelectedListLocalStorageKey('DO'), JSON.stringify(listPozostaleDo))
+			return Object.assign(prevState, {
+				pozostaleDo: listPozostaleDo,
+				totalDoPozostale: listPozostaleDo.length,
+			})
+		}
+		case 'RM_OD': {
+			var featureKey = action.featureKey;
+			var listPozostaleOd = prevState.pozostaleOd.filter(function (item) {
+				return ( item !== featureKey );
+			})
+			localStorage.setItem(getSelectedListLocalStorageKey('OD'), JSON.stringify(listPozostaleOd))
+			return Object.assign(prevState, {
+				pozostaleOd: listPozostaleOd,
+				totalOdPozostale: listPozostaleOd.length,
+			})
+		}
+		case 'RM_DO': {
+			var featureKey = action.featureKey;
+			var listPozostaleDo = prevState.pozostaleDo.filter(function (item) {
+				return ( item !== featureKey );
+			})
+			localStorage.setItem(getSelectedListLocalStorageKey('DO'), JSON.stringify(listPozostaleDo))
+			return Object.assign(prevState, {
+				pozostaleDo: listPozostaleDo,
+				totalDoPozostale: listPozostaleDo.length,
+			})
+		}
+		case 'CLEAR_POZOSTALE_OD': {
+			localStorage.setItem(getSelectedListLocalStorageKey('OD'), JSON.stringify([]))
+			return Object.assign(prevState, {
+				pozostaleOd: [],
+				totalOdPozostale: 0,
+			})
+		}
+		case 'CLEAR_POZOSTALE_DO': {
+			localStorage.setItem(getSelectedListLocalStorageKey('DO'), JSON.stringify([]))
+			return Object.assign(prevState, {
+				pozostaleDo: [],
+				totalDoPozostale: 0,
+			})
+		}
+		case 'SET_DEPTH': {
+			localStorage.setItem('Anton1.biAuditForm.depth', action.depth)
+			return Object.assign(prevState, {
+				depth: action.depth,
+			})
+		}
+		case 'SET_ONLY_TARGETS': {
+			localStorage.setItem('Anton1.biAuditForm.analizaOnlyTargets', action.onlyTargets ? '"y"' : '"n"')
+			return Object.assign(prevState, {
+				onlyTargets: action.onlyTargets,
+			})
+		}
+		case 'SET_TITLE': {
+			localStorage.setItem('Anton1.biAuditForm.smadReaportTitle', '"' + action.title + '"')
+			return Object.assign(prevState, {
+				title: action.title,
+			})
+		}
+		case 'CLEAR_ALL': {
+			var defaultState = getDefaultState();
+			var defaultOnlyTargetsString = defaultState.onlyTargets ? "y" : "n"
+			setItemLocalStorage('Anton1.biAuditForm.pracownicyIds', []);
+			setItemLocalStorage('Anton1.biAuditForm.kontrahenciIds', []);
+			setItemLocalStorage(getSelectedListLocalStorageKey('OD'), []);
+			setItemLocalStorage(getSelectedListLocalStorageKey('DO'), []);
+			setItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup', 0);
+			setItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup', 0);
+			setItemLocalStorage('Anton1.biAuditForm.pracownicy.pagination.page', 1);
+			setItemLocalStorage('Anton1.biAuditForm.kontrahenci.pagination.page', 1);
+			setItemLocalStorage('Anton1.biAuditForm.analizaOnlyTargets', defaultOnlyTargetsString);
+			setItemLocalStorage('Anton1.biAuditForm.depth', defaultState.depth);
+			setItemLocalStorage('Anton1.biAuditForm.smadReaportTitle', defaultState.title);
+			return Object.assign(prevState, defaultState)
+		}
+		default: return prevState;
+	}
+}
+
+
+function getSelectedListLocalStorageKey(from) { // from: ( OD | DO )
+	switch (from) {
+		case 'OD': return 'Anton1.biAuditForm.odFeatureKeys';
+		case 'DO': return 'Anton1.biAuditForm.doFeatureKeys';
+		default: throw "Not implemented from selected list '" + from + "' - expected 'OD' or 'DO'";
+	}
+}
+function getListFromLocalStorage(key) {
+	return JSON.parse( localStorage.getItem(key) || '[]' );
+}
+function getSignedIntFromLocalStorage(key, defaultValue) {
+	return JSON.parse( localStorage.getItem(key) || defaultValue );
+}
+function getStringFromLocalStorage(key, defaultValue) {
+	var value = localStorage.getItem(key);
+	value = (value) ? JSON.parse(value) : '';
+	return (value) ? value : defaultValue;
+}
+
+function setItemLocalStorage(key, value) {
+	localStorage.setItem( key, JSON.stringify(value) );
+}
+function getItemLocalStorage(key) {
+	return JSON.parse( localStorage.getItem(key) );
+}
+
+
+global[STORE_NAME] = createStoreWithThunkMiddleware(anton1RaportStore);
+global[STORE_NAME + '__defaults'] = getDefaultState;

+ 3563 - 0
tools/Anton1.php.view.js

@@ -0,0 +1,3563 @@
+var DBG = DBG || 0;
+var DBG1 = true;
+var CURRENT_DATE = CURRENT_DATE || '';
+if (!STORE_NAME) throw "Store name not defined";
+if (!global[STORE_NAME]) throw "Store not defined";
+
+if (!URL_TABLE_POWIAZANIA) throw "Brak URL_TABLE_POWIAZANIA";
+if (!BASE_URLS) throw "Brak BASE_URLS"
+
+var RECORD_MORE_FUNCTIONS_OPENED_NODE = null;
+if (!FIELD_LIST_PRACOWNICY) throw "Brak FIELD_LIST_PRACOWNICY"
+if (!FIELD_LIST_KONTRAHENCI) throw "Brak FIELD_LIST_KONTRAHENCI"
+var EXPORT_FIELDS_OD = EXPORT_FIELDS_OD || null;
+var EXPORT_FIELDS_DO = EXPORT_FIELDS_DO || null;
+
+var createReactClass = global.p5VendorJs.createReactClass;
+var h = global.p5VendorJs.React.createElement;
+var ReactDOM = global.p5VendorJs.ReactDOM;
+var swal = window.swal;
+var globalRaportStore = global[STORE_NAME];
+if (!p5UI__clickedOutsideElement) throw "Brak p5UI__clickedOutsideElement"
+if (!global.p5VendorJs.Unstated) throw "Brak Unstated"
+var Unstated = global.p5VendorJs.Unstated;
+
+var P5UI__Anton1Header = createReactClass({
+	getStateFromStore: function () {
+		var storeState = this.props.store.getState();
+		return {
+			totalOdPracownicy: storeState.totalOdPracownicy,
+			totalOdPozostale: storeState.totalOdPozostale,
+			totalDoKontrahenci: storeState.totalDoKontrahenci,
+			totalDoPozostale: storeState.totalDoPozostale,
+			depth: storeState.depth,
+			onlyTargets: storeState.onlyTargets,
+			title: storeState.title,
+		};
+	},
+	getInitialState: function() {
+		return this.getStateFromStore();
+	},
+	componentDidMount: function () {
+		this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
+	},
+	componentWillUnmount: function () {
+		this.unsubscribe()
+	},
+	storeUpdated: function () {
+		DBG && console.log('DBG::P5UI__Anton1Header::storeUpdated ', this.getStateFromStore());
+		this.setState(this.getStateFromStore())
+	},
+	addOdPozostale: function (event) {
+		// window['createPracownikAjax'](event)
+		window['addPozostaleOdDo'](event)
+	},
+	addDoPozostale: function (event) {
+		// window['createKontrahentAjax'](event)
+		window['addPozostaleOdDo'](event)
+	},
+	clearPozostaleOd: function (event) {
+		this.props.store.dispatch({ type: 'CLEAR_POZOSTALE_OD' })
+	},
+	clearPozostaleDo: function (event) {
+		this.props.store.dispatch({ type: 'CLEAR_POZOSTALE_DO' })
+	},
+	handleChangeDepth: function (event) {
+		var store = this.props.store;
+		var depth = event.target.value;
+		store.dispatch({ type: 'SET_DEPTH', depth: depth })
+	},
+	handleChangeSetOnlyTargetsYes: function () {
+		this.props.store.dispatch({ type: 'SET_ONLY_TARGETS', onlyTargets: true })
+	},
+	handleChangeSetOnlyTargetsNo: function () {
+		this.props.store.dispatch({ type: 'SET_ONLY_TARGETS', onlyTargets: false })
+	},
+	handleChangeTitle: function (event) {
+		this.props.store.dispatch({ type: 'SET_TITLE', title: event.target.value })
+	},
+	handleRaportSubmitForm: function (event) {
+		event.preventDefault();
+		var self_store = this.props.store;
+
+		var idsPracownicy = getListFromLocalStorage('Anton1.biAuditForm.pracownicyIds');
+		var idsKontrahenci = getListFromLocalStorage('Anton1.biAuditForm.kontrahenciIds');
+		var pozostaleOd = getListFromLocalStorage(getSelectedListLocalStorageKey('OD'));
+		var pozostaleDo = getListFromLocalStorage(getSelectedListLocalStorageKey('DO'));
+		var allOdLength = idsPracownicy.length + pozostaleOd.length;
+		var allDoLength = idsKontrahenci.length + pozostaleDo.length;
+		var depthValue = getItemLocalStorage('Anton1.biAuditForm.depth');
+		var smadReaportTitle = getItemLocalStorage('Anton1.biAuditForm.smadReaportTitle');
+		var analizaOnlyTargets = getItemLocalStorage('Anton1.biAuditForm.analizaOnlyTargets');
+
+		if ( !smadReaportTitle ) {
+			p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie podano tytułu raportu' });
+			return;
+		}
+		if ( !depthValue ) {
+			p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie podano wartości dla głębokości powiązań' });
+			return;
+		}
+		if ( !analizaOnlyTargets ) {
+			p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie podano wartości czy zwracać wyniki tylko z obiektami docelowymi' });
+			return;
+		}
+		if ( !allOdLength ) {
+			p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie wybrano pozycji OD do analizy (pracownicy lub pozostałe bazy)' });
+			return;
+		}
+		if ( !allOdLength && !allDoLength ) {
+			p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie wybrano pozycji do analizy' });
+			return;
+		}
+
+		// TODO: analizaOnlyTargets = ( 'y' | 'n' ) - allDoLength should depend of analizaOnlyTargets?
+
+		// if not choise 'pracownicy' or 'kontrahenci'
+		if ( !allOdLength || !allDoLength ) {
+			var messageConfirm = '';
+			if ( !allDoLength )  {
+				messageConfirm = 'Nie wybrano podmiotów/kontrahentów! Czas przygotowania raportu może wydłużyć się ze względu na sprawdzenie powiązania ze wszystkimi podmiotami/kontrahentami w systemie. Czy jesteś pewny? ';
+			}
+
+			// show confirm window with message
+			if (!confirm(messageConfirm)) return;
+		}
+
+		window.fetch(URL_GENERATE_BI_AUDIT_RAPORT_AJAX, {
+			method: 'POST',
+			headers: { 'Content-Type': 'application/json' },
+			credentials: 'same-origin',
+			body: JSON.stringify({
+				pracownicyIds: idsPracownicy,
+				kontrahenciIds: idsKontrahenci,
+				pozostaleOd: pozostaleOd,
+				pozostaleDo: pozostaleDo,
+				depthValue: depthValue,
+				smadReaportTitle: smadReaportTitle,
+				analizaOnlyTargets: analizaOnlyTargets
+		  })
+		})
+		.then(function(response) {
+			return response.text();
+		})
+		.then(function(responseText) {
+			try {
+				return JSON.parse(responseText);
+			} catch (e) {
+				throw responseText;
+			}
+		})
+		.then(function(result) {
+			if (result.type == 'success') {
+				p5UI__notifyAjaxCallback(result);
+				self_store.dispatch({ type: 'CLEAR_ALL' })
+				updateTopCounters();
+				$('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false);
+				$('#smad-table-KONTRAHENCI form').find(':checkbox').prop('checked', false);
+				$('#count-selected-item-kontrahenci').text('0');
+				$('#count-selected-item-pracownicy').text('0');
+				$('.bottom--message-warning-critical-search').text('');
+				swal({
+					title: result.msg,
+					html: '<a href="' + URL_TABLE_POWIAZANIA + '" title="przejdź do raportów" >Przejdź do raportów</a>',
+					allowOutsideClick: false, // TODO: btn Anuluj na dole?
+					showCloseButton: true,
+					confirmButtonText: 'OK',
+				});
+				window.setTimeout(function () {
+					console.warn("URL_TABLE_POWIAZANIA:", URL_TABLE_POWIAZANIA);
+				}, 100);
+				window.setTimeout(function () {
+					window.location.href = URL_TABLE_POWIAZANIA;
+				}, 6000);
+				resolve(result.msg);
+			} else {
+				if (result.type && result.msg) p5UI__notifyAjaxCallback(result);
+				reject(result.msg);
+			}
+		})
+		.catch(function(error) {
+			if(DBG) console.log('request failed', error);
+		});
+	},
+	handleAddByLastReportClick: function (event) {
+		swal({
+			title: "dodaj do analizy wg raportu",
+			input: 'radio',
+			inputOptions: {
+				'pracownicy' : "Pracownicy",
+				'kontrahenci' : "Kontrahenci",
+				// 'pracownicy_pozostale' : "Pracownicy (pozostałe)",
+				// 'kontrahenci_pozostale' : "Kontrahenci (pozostałe)",
+			},
+			inputValidator: function (value) {
+				return !value && 'Proszę wybrać typ danych';
+			}
+		}).then(function (data) {
+			handleAddToReportByPreviousReport(data.value);
+		})
+
+		// TODO: like addToReportByPreviousReport but after select report, show counters for pracow., kontr., pozostale od and do with checkbox
+		// swal({
+		// 	title: "TODO: dodaj do analizy wg raportu",
+		// })
+		// TODO: https://github.com/sweetalert2/sweetalert2-react-content
+		// - just pass React element to 'html' ?
+	},
+
+	renderClearPozostaleOdBtn: function () {
+		return h('i', {
+			title: "Wyczyść pozostałe",
+			className: "glyphicon glyphicon-remove",
+			style: { 'font-size': '14px', 'line-height': '21px', 'margin-left': '3px', 'vertical-align': 'middle', color: "#f00", opacity: "0.5", cursor: "pointer" },
+			onClick: this.clearPozostaleOd, 'line-height': '20px'
+		});
+	},
+	renderClearPozostaleDoBtn: function () {
+		return h('i', {
+			title: "Wyczyść pozostałe",
+			className: "glyphicon glyphicon-remove",
+			style: { 'font-size': '14px', 'line-height': '21px', 'margin-left': '3px', 'vertical-align': 'middle', color: "#f00", opacity: "0.5", cursor: "pointer" },
+			onClick: this.clearPozostaleDo, 'line-height': '20px'
+		});
+	},
+	renderSummaryList: function () {
+		var totalOd = this.state.totalOdPracownicy + this.state.totalOdPozostale;
+		var totalDo = this.state.totalDoKontrahenci + this.state.totalDoPozostale;
+		return h('ul', {}, [
+			h('li', { style: { marginTop: "6px" } }, [
+				h('span', {
+					style: totalOd > 0 ? { color: "#d7142d" } : {}
+				}, [
+					" OD ",
+					h('span', { className: "badge", style: totalOd > 0 ? { 'background-color': "#d7142d" } : {} }, totalOd),
+					" : ",
+				]),
+				h('a', { className: "btn btn-primary btn-xs", href: "#PRACOWNICY" }, [ // .bi-btn-primary
+					" pracownicy ",
+					h('span', { className: "badge" }, this.state.totalOdPracownicy),
+				]),
+				h('i', { className: "glyphicon glyphicon-plus", style: { 'font-size': "14px", margin: "0 12px" } }),
+				h('button', { className: "btn btn-primary btn-xs", onClick: this.addOdPozostale }, [ // .bi-btn-primary
+					" pozostałe ",
+					h('span', { className: "badge" }, this.state.totalOdPozostale),
+				]),
+				(this.state.totalOdPozostale > 0) ? this.renderClearPozostaleOdBtn() : null,
+			]),
+			h('li', { style: { marginTop: "6px" } }, [
+				h('span', {
+					style: totalDo > 0 ? { color: "#d7142d" } : {}
+				}, [
+					" DO ",
+					h('span', { className: "badge", style: totalDo > 0 ? { 'background-color': "#d7142d" } : {} }, totalDo),
+					" : ",
+				]),
+				h('a', { className: "btn btn-primary btn-xs", href: "#KONTRAHENCI" }, [ // .bi-btn-primary
+					" kontrahenci ",
+					h('span', { className: "badge" }, this.state.totalDoKontrahenci),
+				]),
+				h('i', { className: "glyphicon glyphicon-plus", style: { 'font-size': "14px", margin: "0 12px" } }),
+				h('button', { className: "btn btn-primary btn-xs", onClick: this.addOdPozostale }, [ // .bi-btn-primary
+					" pozostałe ",
+					h('span', { className: "badge" }, this.state.totalDoPozostale),
+				]),
+				(this.state.totalDoPozostale > 0) ? this.renderClearPozostaleDoBtn() : null,
+			]),
+		]);
+	},
+	renderRaportParamsForm: function () {
+		var depth = parseInt(this.state.depth);
+		var isDepthValid = ( !isNaN(depth) && depth >= 1 && depth <= 16 );
+		var onlyTargets = this.state.onlyTargets;
+		return h('div', {}, [
+			h('div', { className: "row" + ( isDepthValid ? "" : " has-error" ), style: { 'margin-bottom': "12px" } }, [
+				h('div', { className: "form-item col-md-7 col-lg-9 smad-heder-title", style: { 'font-size': "14px", 'text-align': "right", 'padding-top': "5px", 'padding-bottom': "0" } }, [
+					"głębokość powiązań: ",
+				]),
+				h('div', { className: "form-item col-md-5 col-lg-3" }, [
+					h('input', { type: "number", className: "form-control", placeholder: "1-16", value: this.state.depth, onChange: this.handleChangeDepth, min: 1, max: 16 }),
+				]),
+			]),
+			h('div', { className: "row", style: { 'margin-bottom': "12px" } }, [
+				h('div', { className: "form-item col-md-7 col-lg-9 smad-heder-title", style: { 'font-size': "14px", 'text-align': "right", 'padding-top': "5px", 'padding-bottom': "0" } }, [
+					"Czy zwracać wyniki tylko ze znalezionymi obiektami docelowymi (DO)? ",
+				]),
+				h('div', { className: "form-item col-md-5 col-lg-3" }, [
+					h('div', { className: "btn-group" }, [
+						h('div', { className: "btn btn-default" + ( onlyTargets ? " active" : "" ), style: { padding: "6px 12px" }, onClick: this.handleChangeSetOnlyTargetsYes }, "TAK"),
+						h('div', { className: "btn btn-default" + ( onlyTargets ? "" : " active" ), style: { padding: "6px 12px" }, onClick: this.handleChangeSetOnlyTargetsNo }, "NIE"),
+					]),
+				]),
+			]),
+			h('div', { className: "row", style: { 'margin-bottom': "12px" } }, [
+				h('div', { className: "form-item col-md-3 col-lg-3", style: { 'font-size': "14px", 'text-align': "right", 'padding-top': "5px", 'padding-bottom': "0" } }, [
+					"Tytuł:",
+				]),
+				h('div', { className: "form-item col-md-9 col-lg-9" }, [
+					h('input', { type: "text", className: "form-control", placeholder: 'Raport bez tytułu z dnia ' + CURRENT_DATE, value: this.state.title, onChange: this.handleChangeTitle }),
+				]),
+			]),
+		]);
+	},
+	renderRaportFormSubmitBtn: function () {
+		var totalOd = this.state.totalOdPracownicy + this.state.totalOdPozostale;
+		var totalDo = this.state.totalDoKontrahenci + this.state.totalDoPozostale;
+		var isFormValid = (totalOd || totalDo);
+		return h('div', { className: "row", style: { padding: "0", 'margin-bottom': "0", 'text-align': "right" } }, [
+			h('div', { className: "form-item col-md-12 col-lg-12" }, [
+				h('button', {
+					type: "button",
+					className: "btn btn-default" + ( isFormValid ? "" : " disabled" ),
+					onClick: this.handleRaportSubmitForm,
+					style: { padding: "18px 42px", 'font-size': "18px", 'font-weight': "900" }
+				}, "GENERUJ RAPORT POWIĄZAŃ"),
+			]),
+		]);
+	},
+	renderAddMoreBtns: function () {
+		return h('div', {
+			style: { 'padding-top': 6, 'padding-bottom': 20 }
+		}, [
+			h('button', { className: "btn btn-success btn-xs", onClick: this.handleAddByLastReportClick }, "dodaj do analizy wg raportu"),
+		]);
+	},
+	render: function () {
+		DBG && console.log('DBG::P5UI__Anton1Header::render ', { state: this.state });
+		var totalOd = this.state.totalOdPracownicy + this.state.totalOdPozostale;
+		var totalDo = this.state.totalDoKontrahenci + this.state.totalDoPozostale;
+		var depth = this.state.depth;
+		var errorMsg = (depth > 16) ? "Maksymalna głębokość powiązań to 16!" : "";
+		var warningMsg = ( ( !totalOd || !totalDo ) && depth > 6 ) ? "Krytyczne wielkości danych do przeszukania. Optymalna głębokość szukania powiaząń to: 6" : "";
+		return h('div', { className: "container-fluid", style: { backgroundColor: "#efefef" } }, [
+			h('div', { style: { fontSize: '16px', fontWeight: "normal", color: "#777" } }, [
+				h('div', { className: "row" }, [
+					h('div', { className: "col-md-6" }, [
+						h('h3', { style: { color: "#000" } }, [
+							h('span', { style: { fontSize: "120%", color: "#d7142d" } }, "|"),
+							" Tworzenie nowego raportu ",
+							h('br'),
+							h('small', {}, [
+								"(Wybierz elementy do porównania: ",
+								h('span', { style: { color: "#d7142d" } }, " OD "),
+								h('i', { className: "glyphicon glyphicon-random", style: { padding: '0 3px', 'font-size': "80%", color: "#000" } }),
+								h('span', { style: { color: "#d7142d" } }, " DO"),
+								")",
+							])
+						]),
+						"Wybrano:",
+						this.renderSummaryList(),
+						this.renderAddMoreBtns(),
+					]),
+					h('div', { className: "col-md-6", style: { 'padding-top': "20px", 'padding-bottom': "20px" } }, [
+						this.renderRaportParamsForm(),
+						this.renderRaportFormSubmitBtn(),
+					]),
+				]),
+				h('div', { className: "row" }, [
+					h('div', { className: "col-md-8 col-md-offset-2 col-xs-12" }, [
+						errorMsg ? h('div', { className: "alert alert-danger" }, errorMsg) : null,
+						warningMsg ? h('div', { className: "alert alert-warning" }, warningMsg) : null,
+					]),
+				]),
+			])
+		])
+	}
+})
+
+function getSelectedListLocalStorageKey(from) { // from: ( OD | DO )
+  switch (from) {
+    case 'OD': return 'Anton1.biAuditForm.odFeatureKeys';
+    case 'DO': return 'Anton1.biAuditForm.doFeatureKeys';
+    default: throw "Not implemented from selected list '" + from + "' - expected 'OD' or 'DO'";
+  }
+}
+function getListFromLocalStorage(key) {
+  return JSON.parse( localStorage.getItem(key) || '[]' );
+}
+function getSignedIntFromLocalStorage(key, defaultValue) {
+  return JSON.parse( localStorage.getItem(key) || defaultValue );
+}
+function getStringFromLocalStorage(key, defaultValue) {
+	var value = localStorage.getItem(key);
+	value = (value) ? JSON.parse(value) : '';
+	return (value) ? value : defaultValue;
+}
+// function saveToSelectedListInLocalStorage(from, featureKey) {
+//   DBG && console.log("DBG::saveToSelectedListInLocalStorage(from, featureKey)", {from, featureKey}, {added: getSelectedListFromLocalStorage(from).concat(featureKey)});
+//   localStorage.setItem(getSelectedListLocalStorageKey(from), JSON.stringify(
+//     getSelectedListFromLocalStorage(from).concat(featureKey)
+//   ))
+// }
+// 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 );
+//     })
+//   ))
+// }
+
+
+/* DATA FOR READ REAPORT */
+
+function urlFetchKontrahenciPowiazania() {
+	// Documentation: https://github.com/github/fetch
+	fetch(URL_FETCH_KONTRAHENCI_POWIAZANIA, {
+		credentials: 'same-origin'
+	})
+	.then(function parseJSON(response) {
+	  return response.json()
+	})
+	.then(function(data) {
+
+		var reaportItemsKontrahenciPowiazani = null;
+		data.body.items.forEach (function(row) {
+			reaportItemsKontrahenciPowiazani += '<tr><td><input type="checkbox" name="kontrID[]" value="'+row['ID']+'" /></td>'+
+				'<td align="right">'+row["ID"]+'</td>';
+		});
+
+		$( "#body-reaport-kontrahenci-powiazani-tree" ).html(reaportItemsKontrahenciPowiazani);
+
+	}).catch(function(error) {
+		if(DBG) console.log('request failed', error)
+	});
+}
+
+
+/* FORM DATA FOR GENERATAE REAPORT */
+/**
+ * Załadowanie  wybranej pozycji w select  czy zwracać wyniki tylko z obiektami docelowymi onlyTarget
+ */
+function loadCurrentOnlyTargetsSelect() {
+  var analizaOnlyTargets = getItemLocalStorage('Anton1.biAuditForm.analizaOnlyTargets');
+
+	$('#smad-select-target').val(analizaOnlyTargets).attr("selected", "selected");
+	$('#smad-select-target-kontrahenci').val(analizaOnlyTargets).attr("selected", "selected");
+}
+
+/**
+ * Załadowanie do storage informacji czy zwracać wyniki tylko z obiektami docelowymi
+ */
+function updateLocalStorageBiAuditOnlyTargets(idSelect) {
+  $(idSelect).change(function() {
+
+      var newValue = $(idSelect).val();
+      var responseValue = newValue;
+
+      setItemLocalStorage('Anton1.biAuditForm.analizaOnlyTargets', responseValue);
+
+			$('#smad-select-target').val(newValue).attr("selected", "selected");
+			$('#smad-select-target-kontrahenci').val(newValue).attr("selected", "selected");
+			// load in select selected option
+			loadCurrentOnlyTargetsSelect();
+  });
+}
+
+
+/**
+ * Funkcja pozwala na wyświetlenie okienka importu
+ */
+function showViewUploadFile( event, headerTitle, enumType, showCheckbox, csvFileExample ) {
+	event.preventDefault();
+
+	var enumType = enumType;
+
+	if( csvFileExample !== undefined) { // przykład + instrukcja do pobrania
+			csvFileExample = '<div><a href="'+csvFileExample+'" title="Pobierz przykład" download target="_balnk">Pobierz przykład</a></div>';
+	}
+
+	swal({
+		title: 'Importuj plik csv',
+		input: 'file',
+		html: csvFileExample,
+		inputAttributes: {
+			'accept': 'text/csv',
+			'aria-label': 'Upload csv file'
+		},
+		confirmButtonText: 'Importuj',
+		preConfirm: function (file) {
+			return new Promise(function (resolve, reject) {
+				if (!file) {
+					reject("Proszę wybrać plik csv");
+					return
+				}
+				var input = document.querySelector('input[type="file"]');
+
+				var data = new FormData()
+				data.append('file', input.files[0])
+				data.append('showCheckbox', showCheckbox);
+
+				var responseParseFile = parseCsvFile( data, enumType );
+				resolve('file imported')
+			})
+		},
+	}).then(function (result) {
+		if(DBG) console.log('result', result);
+	}).catch(function (e) {
+		if(DBG) console.log('catch: ', e);
+	});
+
+}
+
+
+/**
+ * Funkcja przekazuje dane z pliku csv do przeparsowania
+ */
+function parseCsvFile( fileData, enumType ) {
+	event.preventDefault();
+
+	if(DBG) console.log( 'parseCsvFile fileData', fileData);
+
+	fetch(URL_FORM_DATA_CSV_FILE_AJAX, {
+	  method: 'POST',
+		credentials: 	'same-origin',
+	  body: fileData
+	})
+	.then(function(response) {
+	 return response.json()
+ }).then(function(json) {
+
+					 swal({
+								 title: 'Dane załadowane z pliku CSV',
+								 html: json.body.view,
+								 width: Math.round(window.innerWidth * 0.9),
+								 allowOutsideClick: false, // TODO: btn Anuluj na dole?
+								 showCloseButton: true,
+								 confirmButtonText: 'Zapisz',
+								 preConfirm: function (dataForm) {
+						 			return new Promise(function (resolve, reject) {
+						 				if (!dataForm) {
+						 					reject("Formularz nie zawiera danych do zapisania");
+						 					return
+						 				}
+
+										// zapisanie danych
+						 				var responseSaveData = saveFormCsvFileAjaxAction(enumType);
+						 				resolve('data save from form')
+						 			})
+						 		},
+							 }).then(function (result) {
+
+	 							if(DBG) console.log('result', result)
+	 						}).catch(function (e) {
+	 							if(DBG) console.log('catch: ', e)
+	 						});
+
+ }).catch(function(ex) {
+	 if(DBG) console.log('parsing failed', ex);
+ });
+}
+
+/**
+ * Funkcja zapisuje dane z formularza do wgrania pliku csv
+ */
+function saveFormCsvFileAjaxAction(enumType) {
+	event.preventDefault();
+
+	var formDataFrom =	$("#formDataFromCsv").serialize();
+
+	formDataFrom = formDataFrom.replace(/%5B/g,"[");
+	formDataFrom = formDataFrom.replace(/%5D/g,"]");
+
+	fetch(URL_SAVE_FORM_CSV_FILE_AJAX, {
+	  method: 'POST',
+		credentials: 	'same-origin',
+		headers: {
+			'Content-Type': 'application/json'
+		},
+		body: JSON.stringify({
+			 formData: formDataFrom,
+			 enumType: enumType
+		})
+	})
+	.then(function(response) {
+	 return response.json()
+ }).then(function(json) {
+	 if(DBG) console.log('parsed json', json);
+
+	 if (response.type == 'success') {
+
+	 	p5UI__notifyAjaxCallback(response.msg);
+	 }
+
+	// return json;
+ }).catch(function(ex) {
+	 if(DBG) console.log('parsing failed', ex);
+
+ });
+}
+
+
+/**
+* Dodaj nowego pracownika
+*/
+function createPracownikAjax(event) {
+	event.preventDefault();
+
+	swal({
+	  title: 'Dodaj osobę',
+	  showCancelButton: true,
+	  confirmButtonText: 'Zapisz',
+	  showLoaderOnConfirm: true,
+	  html:
+		'<div class="form-group">'+
+    '<input class="form-control required" id="personName" placeholder="Imię" >' +
+    '<input class="form-control required" id="personSurname" placeholder="Nazwisko">'+
+		'<input class="form-control required" id="personNip" placeholder="NIP">'+
+		'<input class="form-control required" id="personPesel" placeholder="PESEL">'+
+		'<input class="form-control required" id="personRegon" placeholder="REGON">'+
+		'</div>',
+	   preConfirm: () => {
+	    return new Promise(function (resolve, reject) {
+
+				// data from form
+				var personName = $('#personName').val();
+				var personSurname = $('#personSurname').val();
+				var personNip = $('#personNip').val();
+				var personPesel = $('#personPesel').val();
+				var personRegon = $('#personRegon').val();
+
+				//validate data from input
+				if (!personName){
+					reject('Proszę podać imię')
+					return;
+				}
+				if (!personSurname){
+					reject('Proszę podać nazwisko')
+					return;
+				}
+				window.fetch(URL_CREATE_PRACOWNICY, {
+					method: 'POST',
+					header: {
+						'contentType': 'applications/json'
+					},
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'personName': personName,
+						'personSurname': personSurname,
+						'personNip': personNip,
+						'personPesel': personPesel,
+						'personRegon': personRegon
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						resolve(result.body);
+						urlFetchPracownicy(1);
+					}
+				})
+				.catch(function(error) {
+					if(DBG) console.log('request failed', error);
+				})
+
+	    })
+	  },
+	  allowOutsideClick: false
+	}).then(function (createPerson) {
+		 if(DBG) console.log('dodanie osoby: ', createPerson);
+
+	});
+}
+
+/**
+* Dodaj nowego kontrahenta
+*/
+function createKontrahentAjax(event) {
+	event.preventDefault();
+
+	swal({
+	  title: 'Dodaj podmiot/kontrahenta',
+	  showCancelButton: true,
+	  confirmButtonText: 'Zapisz',
+	  showLoaderOnConfirm: true,
+	  html:
+		'<div class="form-group">'+
+    '<input class="form-control required" id="companyFullName" placeholder="Pelna nazwa" >' +
+    '<input class="form-control required" id="companyShortName" placeholder="Skrócona nazwa\">'+
+		'<input class="form-control required" id="companyNameGroup" placeholder="Nazwa grupy kapitałowej">'+
+		'<input class="form-control required" id="companyKrs" placeholder="KRS">'+
+		'<input class="form-control required" id="companyNip" placeholder="NIP">'+
+		'<input class="form-control required" id="companyPesel" placeholder="PESEL">'+
+		'<input class="form-control required" id="companyFax" placeholder="FAX">'+
+		'<input class="form-control required" id="companyTelefon" placeholder="Telefon">'+
+		'<input class="form-control required" id="companyMail" placeholder="Mail">'+
+		'<input class="form-control required" id="companyStreet" placeholder="Ulica">'+
+		'<input class="form-control required" id="companyNumberBuilding" placeholder="Numer budynku">'+
+		'<input class="form-control required" id="companyNumberLocal" placeholder="Numer mieszkania /lokalu">'+
+		'<input class="form-control required" id="companyPostCode" placeholder="Kod pocztowy">'+
+		'<input class="form-control required" id="companyPlace" placeholder="Miejscowosc">'+
+		'<input class="form-control required" id="companyCountry" placeholder="Kraj">'+
+		'<input class="form-control required" id="companyTypeCompany" placeholder="Typ kontrahenta">'+
+		'<input class="form-control required" id="companyTitleDocument" placeholder="Tytul dokumentu">'+
+		'<input class="form-control required" id="companyDesc" placeholder="uwagi">'+
+		'</div>',
+
+	   preConfirm: () => {
+	    return new Promise(function (resolve, reject) {
+
+				// data from form
+				var companyFullName = $('#companyFullName').val();
+				var companyShortName = $('#companyShortName').val();
+				var companyNameGroup = $('#companyNameGroup').val();
+				var companyKrs = $('#companyKrs').val();
+				var companyNip = $('#companyNip').val();
+				var companyPesel = $('#companyPesel').val();
+				var companyFax = $('#companyFax').val();
+				var companyTelefon = $('#companyTelefon').val();
+				var companyMail = $('#companyMail').val();
+				var companyStreet = $('#companyStreet').val();
+				var companyNumberBuilding = $('#companyNumberBuilding').val();
+				var companyNumberLocal = $('#companyNumberLocal').val();
+				var companyPostCode = $('#companyPostCode').val();
+				var companyPlace = $('#companyPlace').val();
+				var companyCountry = $('#companyCountry').val();
+				var companyTypeCompany = $('#companyTypeCompany').val();
+				var companyTitleDocument = $('#companyTitleDocument').val();
+				var companyDesc = $('#companyDesc').val();
+
+
+				//validate data from input
+				if (!companyFullName){
+					reject('Proszę podać pełną nazwę');
+					return;
+				}
+
+				window.fetch(URL_CREATE_KONTRAHENCI, {
+					method: 'POST',
+					header: {
+						'contentType': 'applications/json'
+					},
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'companyFullName': companyFullName,
+						'companyShortName': companyShortName,
+						'companyNameGroup': companyNameGroup,
+						'companyKrs': companyKrs,
+						'companyNip': companyNip,
+						'companyPesel': companyPesel,
+						'companyFax': companyFax,
+						'companyTelefon': companyTelefon,
+						'companyMail': companyMail,
+						'companyStreet': companyStreet,
+						'companyNumberBuilding': companyNumberBuilding,
+						'companyNumberLocal': companyNumberLocal,
+						'companyPostCode': companyPostCode,
+						'companyPlace': companyPlace,
+						'companyCountry': companyCountry,
+						'companyTypeCompany': companyTypeCompany,
+						'companyTitleDocument': companyTitleDocument,
+						'companyDesc': companyDesc
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						resolve(result.body);
+						urlFetchKontrahenci(1);
+					}
+				})
+				.catch(function(error) {
+					if(DBG) console.log('request failed', error);
+				})
+
+	    })
+	  },
+	  allowOutsideClick: false
+	}).then(function (createPerson) {
+		 if(DBG) console.log('dodanie podmiotu: ', createPerson);
+
+	});
+}
+
+/**
+ * Popup z opcja przeniesienia pracowników do innej grupy
+ */
+function addPracownikToGroup(event) {
+	event.preventDefault();
+
+	var pracownicyIdsArray = getItemLocalStorage('Anton1.biAuditForm.pracownicyIds');
+	if (pracownicyIdsArray === null || !pracownicyIdsArray || !pracownicyIdsArray.length) {
+		showTextListIdPracownikow = 'nie wybrano osób';
+	} else {
+		showTextListIdPracownikow = '' + pracownicyIdsArray.length + ' osób';
+	}
+
+	var arrayGroupOptions = [];
+	var listGroupStorage = getItemLocalStorage('Anton1.biAuditForm.pracownicy.groups');
+  // utworzenie tablicy Optionsów grupy
+	listGroupStorage.map(function(item) {
+		if (item.ID !== undefined) {
+			arrayGroupOptions[item.ID] = item.NAZWA;
+		}
+	});
+
+	swal({
+	  title: 'Dodaj do grupy',
+		input: 'select',
+		text: showTextListIdPracownikow,
+	  inputOptions: arrayGroupOptions,
+	  inputPlaceholder: 'Wybierz grupę',
+	  showCancelButton: true,
+	  confirmButtonText: 'Zapisz',
+	  showLoaderOnConfirm: true,
+	  preConfirm: function (idGroup) {
+			if (!idGroup) {
+				swal.showValidationError('Proszę wybrać nazwę grupy');
+				return;
+			}
+			if (!pracownicyIdsArray || !pracownicyIdsArray.length) {
+				swal.showValidationError('Proszę wybrać pracowników');
+				return;
+			}
+	    return new Promise(function (resolve, reject) {
+				window.fetch(URL_ADD_PRACOWNICY_TO_GROUP, {
+					method: 'POST',
+					header: { 'contentType': 'applications/json' },
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'idGroup': idGroup,
+						'pracownicyIds': getItemLocalStorage('Anton1.biAuditForm.pracownicyIds'),
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						resolve(result.msg);
+					} else {
+						reject(result.msg);
+					}
+				})
+				.catch(function(error) {
+					if(DBG) console.warn('request failed', error);
+				});
+	    })
+	  },
+	  allowOutsideClick: false
+	}).then(function (value) {
+		{ // remove from selected
+			setItemLocalStorage('Anton1.biAuditForm.pracownicyIds', []);
+			updateCountItemCheckedByType('pracownicy');
+			$('form').find(':checkbox').prop('checked', false);
+		}
+	}).catch(function (e) {
+		DBG && console.log('DBG: e', e)
+	});
+}
+
+function addPracownikAllToGroup(event) {
+	event.preventDefault();
+
+	var showTextListIdPracownikow = 'wszystkich pracowników pasujących do kryteriów wyszukiwania';
+
+	var arrayGroupOptions = [];
+	var listGroupStorage = getItemLocalStorage('Anton1.biAuditForm.pracownicy.groups');
+  // utworzenie tablicy Optionsów grupy
+	listGroupStorage.map(function(item) {
+		if (item.ID !== undefined) {
+			arrayGroupOptions[item.ID] = item.NAZWA;
+		}
+	});
+
+	swal({
+	  title: 'Dodaj do grupy',
+		input: 'select',
+		text: showTextListIdPracownikow,
+	  inputOptions: arrayGroupOptions,
+	  inputPlaceholder: 'Wybierz grupę',
+	  showCancelButton: true,
+	  confirmButtonText: 'Zapisz',
+	  showLoaderOnConfirm: true,
+	  preConfirm: function (idGroup) {
+	    return new Promise(function (resolve, reject) {
+				if (!idGroup) {
+					reject('Proszę wybrać nazwę grupy');
+					return;
+				}
+
+				var filterFields = {}
+				var frm = document.getElementById('filtersFieldRemoveBtn-PRACOWNICY').form
+				var fieldNameList = FIELD_LIST_PRACOWNICY
+				fieldNameList.filter(function (fieldName) {
+					if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"');
+					return (frm[fieldName]) ? true : false
+				}).map(function (fieldName) {
+					return [ fieldName, frm[fieldName].value ]
+				}).filter(function (filter) {
+					return ( filter[1].length > 0 )
+				}).map(function (filter) {
+					filterFields[ filter[0] ] = filter[1]
+				})
+				var filterIdGroup = getItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup');
+				if (filterIdGroup) filterFields[ 'filterIdGroup' ] = filterIdGroup
+
+				window.fetch(URL_ADD_PRACOWNICY_TO_GROUP, {
+					method: 'POST',
+					header: {
+						'contentType': 'applications/json'
+					},
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'idGroup': idGroup,
+						'type': 'filter',
+						'filter': filterFields,
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						resolve(result.msg);
+					} else {
+						reject(result.msg);
+					}
+				})
+				.catch(function(error) {
+					if(DBG) console.log('request failed', error);
+				});
+	    })
+	  },
+	  allowOutsideClick: false
+	}).then(function (groupPracownicyData) {
+		//TODO: pIOTRKU CZY TU POWINIENEM COŚ JESZCZE OBSŁUŻYĆ
+	});
+}
+
+/**
+ * Popup z opcja przeniesienia kontrahentów do innej grupy
+ */
+function addKontrahenciToGroup(event) {
+	event.preventDefault();
+
+	var kontrahenciIdsArray = getItemLocalStorage('Anton1.biAuditForm.kontrahenciIds');
+	if (kontrahenciIdsArray === null || !kontrahenciIdsArray || !kontrahenciIdsArray.length) {
+		showTextListIdKontrahentow = 'nie wybrano kontrahentów';
+	} else {
+		showTextListIdKontrahentow = '' + kontrahenciIdsArray.length + ' podmiotów/kontrahentów';
+	}
+
+	var arrayGroupOptions = [];
+	var listGroupStorage = getItemLocalStorage('Anton1.biAuditForm.kontrahenci.groups');
+  // utworzenie tablicy Optionsów grupy
+	listGroupStorage.map(function(item) {
+		if (item.ID !== undefined) {
+	   	arrayGroupOptions[item.ID] = item.NAZWA;
+		}
+	});
+
+	swal({
+	  title: 'Dodaj do grupy',
+		input: 'select',
+		text: showTextListIdKontrahentow,
+	  inputOptions: arrayGroupOptions,
+	  inputPlaceholder: 'Wybierz grupę',
+	  showCancelButton: true,
+	  confirmButtonText: 'Zapisz',
+	  showLoaderOnConfirm: true,
+	  preConfirm: function (idGroup) {
+			if (!idGroup) {
+				swal.showValidationError('Proszę wybrać nazwę grupy');
+				return;
+			}
+			if (!kontrahenciIdsArray || !kontrahenciIdsArray.length) {
+				swal.showValidationError('Proszę wybrać kontrahentów');
+				return;
+			}
+	    return new Promise(function (resolve, reject) {
+				window.fetch(URL_ADD_KONTRAHENCI_TO_GROUP, {
+					method: 'POST',
+					header: { 'contentType': 'applications/json' },
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'idGroup': idGroup,
+						'kontrahenciIds': getItemLocalStorage('Anton1.biAuditForm.kontrahenciIds'),
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						resolve(result.msg);
+					} else {
+						reject(result.msg);
+					}
+				})
+				.catch(function(error) {
+					if(DBG) console.warn('request failed', error);
+				});
+	    })
+	  },
+	  allowOutsideClick: false
+	}).then(function (value) {
+		{ // remove from selected
+			setItemLocalStorage('Anton1.biAuditForm.kontrahenciIds', []);
+			updateCountItemCheckedByType('kontrahenci');
+			$('form').find(':checkbox').prop('checked', false);
+		}
+	}).catch(function (e) {
+		DBG && console.log('DBG: e', e)
+	});
+}
+function addKontrahenciAllToGroup(event) {
+	event.preventDefault();
+
+	var kontrahenciIdsArray = getItemLocalStorage('Anton1.biAuditForm.kontrahenciIds');
+
+	var showTextListIdKontrahentow = 'wszystkich podmotów/kontrahentów pasujących do kryteriów wyszukiwania';
+
+	var arrayGroupOptions = [];
+	var listGroupStorage = getItemLocalStorage('Anton1.biAuditForm.kontrahenci.groups');
+  // utworzenie tablicy Optionsów grupy
+	listGroupStorage.map(function(item) {
+		if (item.ID !== undefined) {
+			arrayGroupOptions[item.ID] = item.NAZWA;
+		}
+	});
+
+	swal({
+	  title: 'Dodaj do grupy',
+		input: 'select',
+		text: showTextListIdKontrahentow,
+	  inputOptions: arrayGroupOptions,
+	  inputPlaceholder: 'Wybierz grupę',
+	  showCancelButton: true,
+	  confirmButtonText: 'Zapisz',
+	  showLoaderOnConfirm: true,
+	  preConfirm: function (idGroup) {
+	    return new Promise(function (resolve, reject) {
+				if (!idGroup) {
+					reject('Proszę wybrać nazwę grupy');
+					return;
+				}
+
+				var filterFields = {}
+				var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form
+				var fieldNameList = FIELD_LIST_KONTRAHENCI
+				fieldNameList.filter(function (fieldName) {
+					if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"')
+					return (frm[fieldName]) ? true : false
+				}).map(function (fieldName) {
+					return [ fieldName, frm[fieldName].value ]
+				}).filter(function (filter) {
+					return ( filter[1].length > 0 )
+				}).map(function (filter) {
+					filterFields[ filter[0] ] = filter[1]
+				})
+				var filterIdGroup = getItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup');
+				if (filterIdGroup) filterFields[ 'filterIdGroup' ] = filterIdGroup
+
+				window.fetch(URL_ADD_KONTRAHENCI_TO_GROUP, {
+					method: 'POST',
+					header: {
+						'contentType': 'applications/json'
+					},
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'idGroup': idGroup,
+						'type': 'filter',
+						'filter': filterFields,
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+					$('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false);
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						resolve(result.msg);
+					} else {
+						reject(result.msg);
+					}
+				})
+				.catch(function(error) {
+					if(DBG) console.log('request failed', error);
+				});
+	    })
+	  },
+	  allowOutsideClick: false
+	});
+}
+
+function removeKontrahenciFromGroup(event) {
+	event.preventDefault;
+
+	var kontrahenciIdsArray = getItemLocalStorage('Anton1.biAuditForm.kontrahenciIds');
+	if (kontrahenciIdsArray === null || !kontrahenciIdsArray || !kontrahenciIdsArray.length) {
+		showTextListIdKontrahentow = 'nie wybrano kontrahentów';
+	} else {
+		showTextListIdKontrahentow = '' + kontrahenciIdsArray.length + ' podmiotów/kontrahentów';
+	}
+
+	var groupId = getItemLocalStorage("Anton1.biAuditForm.kontrahenci.filterIdGroup");
+	var removeTitle = "Czy chcesz usunąć z "
+	if (groupId === "0") {
+		removeTitle += "systemu";
+	} else {
+		var arrayGroupOptions = [];
+		var listGroupStorage = getItemLocalStorage('Anton1.biAuditForm.kontrahenci.groups');
+	  // utworzenie tablicy Optionsów grupy
+		listGroupStorage.map(function(item) {
+			if (item.ID !== undefined) {
+				arrayGroupOptions[item.ID] = item.NAZWA;
+			}
+		});
+		removeTitle += "grupy ";
+		removeTitle += arrayGroupOptions[groupId];
+	}
+	swal({
+	  title: removeTitle,
+		text: showTextListIdKontrahentow,
+		showConfirmButton: true,
+	  showCancelButton: true,
+	  confirmButtonText: 'Usuń',
+	  cancelButtonText: 'Anuluj',
+	  showLoaderOnConfirm: true,
+		preConfirm: function () {
+	    return new Promise(function (resolve, reject) {
+				if (!kontrahenciIdsArray || !kontrahenciIdsArray.length) {
+					reject('Wybierz kontrahentów');
+					return;
+				}
+
+				window.fetch(URL_REMOVE_KONTRAHENCI_FROM_GROUP, {
+					method: 'POST',
+					header: { 'contentType': 'applications/json' },
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'idGroup': getItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup'),
+						'kontrahenciIds': getItemLocalStorage('Anton1.biAuditForm.kontrahenciIds'),
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+					result
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						updateTopCounters();
+						$('#smad-table-KONTRAHENCI form').find(':checkbox').prop('checked', false);
+						resolve(result.msg);
+					} else {
+						reject(result.msg);
+					}
+				})
+	    })
+	  },
+	  allowOutsideClick: false
+	}).then((result) => {
+		if (!result) return;
+		if (result.dismiss) return;
+		if (!result.value) return;
+		{ // remove from selected
+			setItemLocalStorage('Anton1.biAuditForm.kontrahenciIds', []);
+			updateCountItemCheckedByType('kontrahenci');
+			$('#smad-table-KONTRAHENCI form').find(':checkbox').prop('checked', false);
+		}
+		urlFetchKontrahenci(1);
+	});
+}
+
+function removePracownikFromGroup(event){
+	event.preventDefault;
+
+	var pracownicyIdsArray = getItemLocalStorage('Anton1.biAuditForm.pracownicyIds');
+	if (pracownicyIdsArray === null || !pracownicyIdsArray || !pracownicyIdsArray.length) {
+		showTextListIdPracownikow = 'nie wybrano osób';
+	} else {
+		showTextListIdPracownikow = '' + pracownicyIdsArray.length + ' osób';
+	}
+	var groupId = getItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup');
+	var removeTitle = "Czy chcesz usunąć z "
+	if (!groupId) {
+		removeTitle += "systemu";
+	} else {
+		var arrayGroupOptions = [];
+		var listGroupStorage = getItemLocalStorage('Anton1.biAuditForm.pracownicy.groups');
+	  // utworzenie tablicy Optionsów grupy
+		listGroupStorage.map(function(item) {
+			if (item.ID !== undefined) {
+				arrayGroupOptions[item.ID] = item.NAZWA;
+			}
+		});
+		removeTitle += "grupy ";
+		removeTitle += arrayGroupOptions[groupId];
+	}
+	swal({
+	  title: removeTitle,
+		text: showTextListIdPracownikow,
+	  showConfirmButton: true,
+	  showCancelButton: true,
+	  confirmButtonText: 'Usuń',
+	  cancelButtonText: 'Anuluj',
+	  showLoaderOnConfirm: true,
+		preConfirm: function () {
+	    return new Promise(function (resolve, reject) {
+				if (!pracownicyIdsArray || !pracownicyIdsArray.length) {
+					reject('Wybierz osoby');
+					return;
+				}
+
+				window.fetch(URL_REMOVE_PRACOWNICY_FROM_GROUP, {
+					method: 'POST',
+					header: { 'contentType': 'applications/json' },
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'idGroup': getItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup'),
+						'pracownicyIds': getItemLocalStorage('Anton1.biAuditForm.pracownicyIds'),
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						updateTopCounters();
+						$('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false);
+						resolve(result.msg);
+					} else {
+						reject(result.msg);
+					}
+				})
+	    })
+	  },
+	  allowOutsideClick: false
+	}).then((result) => {
+		if (!result) return;
+		if (result.dismiss) return;
+		if (!result.value) return;
+		{ // remove from selected
+			setItemLocalStorage('Anton1.biAuditForm.pracownicyIds', []);
+			updateCountItemCheckedByType('pracownicy');
+			$('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false);
+		}
+		urlFetchPracownicy(1);
+	});
+
+}
+
+function createGroupKontrahenci(event) {
+	event.preventDefault();
+
+	swal({
+	  title: 'Utwórz grupę',
+	  input: 'text',
+	  showCancelButton: true,
+	  confirmButtonText: 'Zapisz',
+	  showLoaderOnConfirm: true,
+	  preConfirm: function (NAZWA) {
+	    return new Promise(function (resolve, reject) {
+				if (!NAZWA) {
+					reject('Proszę podać nazwę grupy');
+					return;
+				}
+
+				window.fetch(URL_CREATE_PRACOWNICY_GROUP, {
+					method: 'POST',
+					header: { 'contentType': 'applications/json' },
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'NAZWA': NAZWA
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						resolve(result.body);
+					} else {
+						reject("Proszę podać inną nazwę grupy");
+					}
+				})
+				.catch(function(error) {
+					if(DBG) console.log('request failed', error);
+				})
+	    })
+	  },
+	  allowOutsideClick: false
+	}).then(function (result) {
+		if (!result) return;
+		if (result.dismiss) return;
+		if (!result.value) return;
+		// NOTE: swal has input, so resolver object from preConfirm is in { value: resolvedObject }
+		var addedGroup = result.value;
+		if (addedGroup.id && addedGroup.nazwa) {
+			$('#group-kontrahenci').append('<button class="btn btn-default" title="'+addedGroup['nazwa']+'" data-group-filter="'+addedGroup['id']+'">'+addedGroup['nazwa']+'</button>');
+			{ // add group to local storage
+				setItemLocalStorage(
+					'Anton1.biAuditForm.kontrahenci.groups',
+					[].concat(
+						getItemLocalStorage('Anton1.biAuditForm.kontrahenci.groups') || [],
+						[ { 'ID': addedGroup.id, 'NAZWA': addedGroup.nazwa } ]
+					)
+				);
+			}
+		}
+		//TODO: aktualizacja fitrów na widoku -> SPrawdzić co dostaniemy w odpowiedzi po dodaniu filtra grupy
+	});
+
+}
+
+function createGroupPracownicy(event) {
+	event.preventDefault();
+
+	swal({
+	  title: 'Utwórz grupę',
+	  input: 'text',
+	  showCancelButton: true,
+	  confirmButtonText: 'Zapisz',
+	  showLoaderOnConfirm: true,
+	  preConfirm: function (NAZWA) {
+	    return new Promise(function (resolve, reject) {
+				if (!NAZWA) {
+					reject('Proszę podać nazwę grupy');
+					return;
+				}
+
+				window.fetch(URL_CREATE_PRACOWNICY_GROUP, {
+					method: 'POST',
+					header: { 'contentType': 'applications/json' },
+					credentials: 'same-origin',
+					body: JSON.stringify({
+						'NAZWA': NAZWA
+					})
+				})
+				.then(function(response) {
+					return response.text();
+				})
+				.then(function(responseText) {
+					try {
+						return JSON.parse(responseText);
+					} catch (e) {
+						throw responseText;
+					}
+				})
+				.then(function(result) {
+					console.warn('DBG group added? result', result)
+					if (result.type == 'success') {
+						p5UI__notifyAjaxCallback(result);
+						resolve(result.body);
+					} else {
+						reject("Proszę podać inną nazwę grupy");
+					}
+				})
+				.catch(function(error) {
+					if(DBG) console.log('request failed', error);
+				})
+
+	    })
+	  },
+	  allowOutsideClick: false
+	}).then(function (result) {
+		if (!result) return;
+		if (result.dismiss) return;
+		if (!result.value) return;
+		// NOTE: swal has input, so resolver object from preConfirm is in { value: resolvedObject }
+		var addedGroup = result.value;
+		if (addedGroup.id && addedGroup.nazwa) {
+			$('#group-pracownicy').append('<button class="btn btn-default" title="'+addedGroup['nazwa']+'" data-group-filter="'+addedGroup['id']+'">'+addedGroup['nazwa']+'</button>');
+			{ // add group to local storage
+				setItemLocalStorage(
+					'Anton1.biAuditForm.pracownicy.groups',
+					[].concat(
+						getItemLocalStorage('Anton1.biAuditForm.pracownicy.groups') || [],
+						[ { 'ID': addedGroup.id, 'NAZWA': addedGroup.nazwa } ]
+					)
+				);
+			}
+		}
+		//TODO: aktualizacja fitrów na widoku -> SPrawdzić co dostaniemy w odpowiedzi po dodaniu filtra grupy
+	});
+
+}
+
+/**
+ * Function for load view Form pracownicy/kontrahenci
+ */
+function rootChangeForm() {
+
+	//todo: do przeniesienia
+	urlFetchKontrahenciPowiazania();
+	var valueUrl = global.location.hash;
+
+	switch (valueUrl) {
+		case '#KONTRAHENCI':
+			$( ".container-bi_audit_form_kontrahenci_raport" ).html( VIEW_KONTRAHENCI );
+			urlFetchKontrahenci(1);
+			fetchGroupKontrahenci();
+			$( ".container-bi_audit_form_pracownicy_raport" ).hide();
+			$( ".container-bi_audit_form_kontrahenci_raport" ).show();
+			$(".container-bi-audit_form_operacyjna_baza_zgloszen").hide();
+			//parseGraph();
+			break;
+
+		case '#PRACOWNICY':
+		$( ".container-bi_audit_form_pracownicy_raport" ).html( VIEW_PRACOWNICY );
+			urlFetchPracownicy(1);
+			fetchGroupPracownicy();
+			$( ".container-bi_audit_form_kontrahenci_raport" ).hide();
+			$( ".container-bi_audit_form_pracownicy_raport" ).show();
+			$(".container-bi-audit_form_operacyjna_baza_zgloszen").hide();
+			break;
+
+		case '#OPERACYJNA_BAZA_ZGLOSZEN':
+		$( ".container-bi_audit_form_operacyjna_baza_zgloszen" ).html( OPERACYJNA_BAZA_ZGLOSZEN );
+		// urlFetchPracownicy(1);
+		// fetchGroupPracownicy();
+			$( ".container-bi_audit_form_kontrahenci_raport" ).hide();
+			$( ".container-bi_audit_form_pracownicy_raport" ).hide();
+			$(".container-bi-audit_form_operacyjna_baza_zgloszen").show();
+			break;
+		// case '#REAPORT':
+		// 	$( ".container-bi_audit_form_raport_data" ).html( VIEW_TREE_REAPORT );
+		// 	urlFetchKontrahenciPowiazania();
+		// 	$( ".container-bi_audit_form_kontrahenci_raport" ).hide();
+		// 	$( ".container-bi_audit_form_pracownicy_raport" ).hide();
+		// 	$( ".container-bi_audit_form_raport_data" ).show();
+		// break;
+
+		default:
+		$( ".container-bi_audit_form_pracownicy_raport" ).html( VIEW_PRACOWNICY );
+			urlFetchPracownicy(1);
+			fetchGroupPracownicy();
+			$( ".container-bi_audit_form_kontrahenci_raport" ).hide();
+			$( ".container-training" ).hide();
+			$( ".container-about" ).hide();
+			$( ".container-bi_audit_form_pracownicy_raport" ).show();
+		break;
+	}
+
+	// aktualizacja select option czy zwracać wyniki tylko z obiektami docelowymi
+	updateLocalStorageBiAuditOnlyTargets('#smad-select-target');
+	updateLocalStorageBiAuditOnlyTargets('#smad-select-target-kontrahenci');
+	// load in select selected option BI_analiza_onlyTargets
+	loadCurrentOnlyTargetsSelect();
+
+}
+
+function getAddressData(objectValue) {
+
+	var objectValue = objectValue || [];
+	var listData = '';
+
+	if (!objectValue) {
+		return true;
+	}
+
+	objectValue.forEach (function(item) {
+		if (item['kodPocztowy']) { listData += '<div>kod pocztowy: ' + item['kodPocztowy'] + '<div>'; }
+		if (item['miejscowosc']) { listData += '<div>miejscowość: ' + item['miejscowosc'] + '<div>'; }
+		if (item['nrBudynku']) { listData += '<div>nr budynku: ' + item['nrBudynku'] + '<div>'; }
+		if (item['nrLokalu']) { listData += '<div>nr lokalu: ' + item['nrLokalu'] + '<div>'; }
+		if (item['typAdresu']) { listData += '<div>typ adresu: ' + item['typAdresu'] + '<div>'; }
+		if (item['ulica']) { listData += '<div>ulica: ' + item['ulica'] + '<div>'; }
+		listData += '<div>------<div>';
+	});
+
+	return listData;
+}
+
+
+/**
+ *  Get name name group
+ */
+function getNameGroupById(store, filterIdGroup) {
+
+	var NAZWA = '';
+	if (!store || filterIdGroup === 0 ) {
+		NAZWA = 'Wszyscy';
+	} else {
+
+		$(store).each(function() {
+				if ( parseInt(filterIdGroup) === parseInt(this.ID) ) {
+					NAZWA = this.NAZWA;
+				}
+		});
+	}
+
+	return NAZWA;
+}
+
+function getSearchParamsKontrahenci(page) {
+	var filterIdGroup = getItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup');
+	var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form
+	var fieldNameList = FIELD_LIST_KONTRAHENCI
+	var filterFields = fieldNameList.filter(function (fieldName) {
+		if (!frm[fieldName] && DBG) console.log('Err missing field: "' + fieldName + '"')
+		return (frm[fieldName]) ? true : false
+	}).map(function (fieldName) {
+		return [fieldName, frm[fieldName].value]
+	}).filter(function (filter) {
+		return (filter[1].length > 0)
+	}).map(function (filter) {
+		return '' + filter[0] + '=' + filter[1]
+	}).join('&')
+	return {
+		page: page,
+		filterIdGroup: filterIdGroup,
+		filterFields: (filterFields.length > 0) ? filterFields : null,
+	};
+}
+function getUrlFetchKontrahenci(page) {
+	// return URL_FETCH_PRACOWNICY + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields;
+	var searchParams = getSearchParamsKontrahenci(page);
+	return [
+		URL_FETCH_KONTRAHENCI,
+		'page=' + searchParams.page,
+		'filterIdGroup=' + searchParams.filterIdGroup,
+		searchParams.filterFields,
+	].filter(Boolean).join('&');
+}
+
+function urlFetchKontrahenci(page) {
+	hideMoreRecordFunctionsPopover()
+			var page = page || getItemLocalStorage('Anton1.biAuditForm.kontrahenci.pagination.page');
+
+			selectPage('KONTRAHENCI', page);
+
+			if ( page === 1) {
+				setItemLocalStorage('Anton1.biAuditForm.kontrahenci.pagination.page', 1);
+			}
+
+			var filterIdGroup = getItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup');
+
+			var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form
+			var fieldNameList = FIELD_LIST_KONTRAHENCI
+			var filterFields = fieldNameList.map(function (fieldName) {
+				return [ fieldName, frm[fieldName].value ]
+			}).filter(function (filter) {
+				return ( filter[1].length > 0 )
+			}).map(function (filter) {
+				return '' + filter[0] + '=' + filter[1]
+			}).join('&')
+			filterFields = (filterFields.length > 0) ? '&' + filterFields : ''
+
+			fetch(URL_FETCH_KONTRAHENCI + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields, {
+					credentials: 'same-origin'
+				})
+				.then(function parseJSON(response) {
+					return response.json()
+
+				var filterIdGroup = filterIdGroup || getItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup');
+						})
+				.then(function(data) {
+
+
+						var listItemsKontrahenci = null;
+						data.body.items.forEach (function(row) {
+							listItemsKontrahenci += '<tr><td style="white-space:nowrap">' +
+									'<input style="vertical-align:top" type="checkbox" name="kontrID[]" value="'+row['ID']+'" />' +
+									'<i onClick="kontrahenciLoadMoreRecordFunctions(event, this, '+row['ID']+')" style="margin-left:6px; cursor:pointer; color:#333" class="glyphicon glyphicon-menu-hamburger" title="Więcej funkcji dla rekordu nr ' + row['ID'] + '"></i>' +
+								'</td>' +
+								'<td align="right">'+row["ID"]+'</td>'+
+								'<td align="right">' + ( row["Nazwa_grupy_kapitalowej"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Pelna_nazwa_kontrahenta"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Numer_kontrahenta"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Skrocona_Nazwa_Kontrahenta"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Typ_kontrahenta"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["NIP"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["KRS"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["REGON"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["PESEL"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Forma_prawna_dzialalnosci"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Ulica"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Numer_budynku"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Numer_mieszkania_lokalu"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Miejscowosc"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Kod_pocztowy"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Kraj"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Telefon"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Fax"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Mail"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["A_ADM_COMPANY"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["A_CLASSIFIED"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Dodano"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Podmiot_dominujacy"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["Tytul_dokumentu"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["ownCompany"] || '' ) + '</td>' +
+								'<td align="right">' + ( row["uwagi"] || '' ) + '</td></tr>';
+						});
+
+				if (data.body.pagination !== undefined) {
+					Pagination.Init(document.getElementById('pagination-kontrahenci'), {
+							url: BASE_URLS+'index.php?_route=UrlAction_Anton1#KONTRAHENCI',
+							id_pagination: 'pagination-kontrahenci',
+							type: 'KONTRAHENCI',
+							limit: data.body.pagination.limit,
+							total_items: data.body.pagination.total_items, // pages size
+							size: data.body.pagination.size, // pages size
+							page: page,  // selected page
+							step: 1   // pages before and after current
+					});
+
+					var paginationShowNextCount = 1;
+					if ( parseInt(data.body.pagination.current) !== 1) {
+						 paginationShowNextCount = parseInt(data.body.pagination.limit) * (parseInt(data.body.pagination.current) - 1 ) + 1;
+					}
+					$('#paginationShowNextCount-KONTRAHENCI').text(paginationShowNextCount);
+					$('#smad-filter-desc-kontrahenci').text(data.body.pagination.total_items);
+					if (data.body.pagination.total_items > 0) {
+						var btnAddAll = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO ANALIZY</button>');
+						btnAddAll.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addAllMatchesToReport);
+						$('#smad-filter-desc-kontrahenci').append(btnAddAll);
+
+						// var btnAddByReport = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ DO ANALIZY WG RAPORTU</button>');
+						// btnAddByReport.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addToReportByPreviousReport);
+						// $('#smad-filter-desc-kontrahenci').append(btnAddByReport);
+
+						var btnAddAllToGroup = $('<button class="btn btn-info" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</button>');
+						btnAddAllToGroup.on('click', addKontrahenciAllToGroup);
+						$('#smad-filter-desc-kontrahenci').append(btnAddAllToGroup);
+					}
+				}
+
+				var groupSelectData = getNameGroupById(getItemLocalStorage('Anton1.biAuditForm.kontrahenci.groups'), filterIdGroup);
+				$('#smad-filter-head-title-kontrahenci').text(groupSelectData);
+				if(DBG) console.log('kontrahenci groupSelectData: ', groupSelectData);
+
+
+				$( "#body-kontrahenci" ).html(listItemsKontrahenci);
+				checkAll('KONTRAHENCI');
+				catchEventCheckbox('KONTRAHENCI');
+				checkedChoiseItems('KONTRAHENCI', getItemLocalStorage('Anton1.biAuditForm.kontrahenciIds') );
+
+				//	$( ".container-bi_audit_raport" ).append( data.body.view );
+					if(DBG) console.log('request succeeded with JSON responseKontrahenci', data)
+
+					updateTopCounters();
+				}).catch(function(error) {
+					if(DBG) console.log('request failed', error);
+				})
+}
+
+function getSearchParamsPracownicy(page) {
+	var filterIdGroup = getItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup');
+	var frm = document.getElementById('filtersFieldRemoveBtn-PRACOWNICY').form
+	var fieldNameList = FIELD_LIST_PRACOWNICY
+	var filterFields = fieldNameList.filter(function (fieldName) {
+		if (!frm[fieldName] && DBG) console.log('Err missing field: "' + fieldName + '"')
+		return (frm[fieldName]) ? true : false
+	}).map(function (fieldName) {
+		return [fieldName, frm[fieldName].value]
+	}).filter(function (filter) {
+		return (filter[1].length > 0)
+	}).map(function (filter) {
+		return '' + filter[0] + '=' + filter[1]
+	}).join('&')
+	return {
+		page: page,
+		filterIdGroup: filterIdGroup,
+		filterFields: (filterFields.length > 0) ? filterFields : null,
+	};
+}
+function getUrlFetchPracownicy(page) {
+	// return URL_FETCH_PRACOWNICY + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields;
+	var searchParams = getSearchParamsPracownicy(page);
+	return [
+		URL_FETCH_PRACOWNICY,
+		'page=' + searchParams.page,
+		'filterIdGroup=' + searchParams.filterIdGroup,
+		searchParams.filterFields,
+	].filter(Boolean).join('&');
+}
+
+function urlFetchPracownicy(page) {
+	hideMoreRecordFunctionsPopover()
+	var page = page || getItemLocalStorage('Anton1.biAuditForm.pracownicy.pagination.page');
+
+	if ( page === 1) {
+		setItemLocalStorage('Anton1.biAuditForm.pracownicy.pagination.page', 1);
+	}
+	var filterIdGroup = getItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup');
+	selectPage('PRACOWNICY', page);
+	// var paginationLimit = 20;
+	/*p5WFS_GetFeature('default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+		Object.assign({
+			sortBy: 'ID+D',
+			maxFeatures: paginationLimit,
+			startIndex: (page - 1) * paginationLimit,
+			// TODO: backRefNS, backRefPK, backRefField - TODO: from groups
+			// resolve: 'all',
+			// resolveDepth: 2
+			'ogc:Filter': '<wfs:Query>' + '\n' + [
+				'*',
+				'default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy/*',
+				[
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
+					'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI'
+				].join('/')
+			].map(function (fieldName) {
+				return '<wfs:PropertyName>' + fieldName + '</wfs:PropertyName>';
+			}).join('\n') + '\n' + '</wfs:Query>'
+		}, (filterIdGroup > 0)
+			? {
+					backRefNS: 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
+					backRefPK: filterIdGroup,
+					backRefField: 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
+				}
+			: {}
+		)
+	).then(function (items) {
+		if(DBG)console.log('p5WFS_GetFeature: items: ', items);
+	}).catch(function (err) {
+		if(DBG)console.log('p5WFS_GetFeature: err: ', err);
+	})*/
+
+	var fetchUrl = getUrlFetchPracownicy(page);
+	DBG && console.log('DBG: fetch ', { fetchUrl });
+			fetch(fetchUrl, {
+				credentials: 'same-origin'
+			})
+			.then(function parseJSON(response) {
+			  return response.json()
+			})
+			.then(function(data) {
+
+					var addresPerson = '';
+					var listItemsPracownik = null;
+					if(DBG) console.log('urlFetchPracownicy', data.body.items);
+
+					data.body.items.forEach (function(row) {
+
+						if (row["default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy"]) {
+							addresPerson = getAddressData(row["default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy"]);
+						}
+
+						listItemsPracownik += '<tr><td style="white-space:nowrap">' +
+								'<input style="vertical-align:top" type="checkbox" name="prID[]" value="'+row['ID']+'" />' +
+								'<i onClick="pracownicyLoadMoreRecordFunctions(event, this, '+row['ID']+')" style="margin-left:6px; cursor:pointer; color:#333" class="glyphicon glyphicon-menu-hamburger" title="Więcej funkcji dla rekordu nr ' + row['ID'] + '"></i>' +
+							'</td>' +
+							'<td align="right">'+row["ID"]+'</td>' +
+							'<td align="right">' + ( row["imiona"] || '' ) + '</td>' +
+							'<td align="right">' + ( row["nazwisko"] || '' ) + '</td>' +
+							'<td align="right">' + ( row["nip"] || '' ) + '</td>' +
+							'<td align="right">' + ( row["pesel"] || '' ) + '</td>' +
+							'<td align="right">' + ( row["regon"] || '' ) + '</td>' +
+							'<td align="right">' + ( row["source"] || '' ) + '</td>' +
+							'<td align="right">' + ( row["jednostka_organizacyjna"] || '' ) + '</td>' +
+							'<td align="right">' + ( row["A_STATUS"] || '' ) + '</td>' +
+							'<td align="right">' + ( row["A_STATUS_INFO"] || '' ) + '</td>' +
+							'<td align="right">' + ( row["L_APPOITMENT_USER"] || '' ) + '</td>' +
+							'<td align="right">'+ addresPerson +'</td></tr>';
+					});
+
+			if (data.body.pagination.size) {
+						Pagination.Init(document.getElementById('pagination-pracownicy'), {
+							  url: BASE_URLS+'index.php?_route=UrlAction_Anton1#PRACOWNICY',
+								id_pagination: 'pagination-pracownicy',
+								type: 'PRACOWNICY',
+								limit: data.body.pagination.limit,
+								total_items: data.body.pagination.total_items, // pages size
+								size: data.body.pagination.size, // pages size
+								page: data.body.pagination.current,  // selected page
+								step: 1   // pages before and after current
+						});
+
+						var paginationShowNextCount = 1;
+						if ( parseInt(data.body.pagination.current) !== 1) {
+							 paginationShowNextCount = parseInt(data.body.pagination.limit) * (parseInt(data.body.pagination.current) - 1 ) + 1;
+						}
+						$('#paginationShowNextCount-PRACOWNICY').text(paginationShowNextCount);
+						$('#smad-filter-desc-pracownicy').text(data.body.pagination.total_items);
+						if (data.body.pagination.total_items > 0) {
+							var btnAddAll = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO ANALIZY</button>')
+							btnAddAll.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addAllMatchesToReport);
+							$('#smad-filter-desc-pracownicy').append(btnAddAll);
+
+							// var btnAddByReport = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ DO ANALIZY WG RAPORTU</button>');
+							// btnAddByReport.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addToReportByPreviousReport);
+							// $('#smad-filter-desc-pracownicy').append(btnAddByReport);
+
+							var btnAddAllToGroup = $('<button class="btn btn-info" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</button>');
+							btnAddAllToGroup.on('click', addPracownikAllToGroup);
+							$('#smad-filter-desc-kontrahenci').append(btnAddAllToGroup);
+						}
+			}
+
+
+			// wyświetlenie wybranej grupy w naglówku nad tabela
+			var groupSelectData = getNameGroupById(getItemLocalStorage('Anton1.biAuditForm.pracownicy.groups'), filterIdGroup);
+			$('#smad-filter-head-title-pracownicy').text(groupSelectData);
+
+			// zaladaowanie listy pracowników
+			$( "#body-pracownicy" ).html( listItemsPracownik);
+				checkAll('PRACOWNICY');
+				catchEventCheckbox('PRACOWNICY');
+				checkedChoiseItems('PRACOWNICY', getItemLocalStorage('Anton1.biAuditForm.pracownicyIds') );
+
+				updateTopCounters();
+			}).catch(function(error) {
+				if(DBG) console.log('request failed', error)
+			})
+
+}
+
+function selectPage(type, nrPage) {
+	var type = type.toLowerCase();
+
+	$('#pagination-' + type + ' ul li a').each(function(index, value){
+		if (this.text === nrPage) {
+			$(this).addClass('active');
+		} else {
+			$(this).removeClass('active');
+		}
+	});
+}
+
+function checkAll(type) {
+
+	$('#checkAll-' + type).change(function() {
+
+		  var valueCheckbox = null;
+			var checkboxes = $('form').find(':checkbox');
+			if($(this).prop('checked')) {
+				checkboxes.prop('checked', true);
+				//valueCheckbox = checkboxes.prop("checked");
+					 var allValsChecked = [];
+					 var checkedValues = $('#smad-table-' + type + ' input:checkbox:checked').map(function() {
+
+						 if (this.value !== 'on') {
+							  allValsChecked.push(parseInt(this.value));
+						 }
+					}).get();
+
+					updateListIdBiAuditReaport(type, allValsChecked);
+
+			} else {
+
+				checkboxes.prop('checked', false);
+
+				var allValsUnChecked = [];
+				var checkedValues = $('#smad-table-' + type + ' input:checkbox:not(:checked)').map(function() {
+					if (this.value !== 'on') {
+						 allValsUnChecked.push(parseInt(this.value));
+					}
+			 }).get();
+
+				deleteListIdBiAuditReaport(type, allValsUnChecked);
+			}
+
+			// update count selected IDs
+			updateCountItemCheckedByType(type.toLowerCase());
+	});
+}
+
+/**
+ * Select again checkbox before selected item chekbox from storage (pracownicy/kontrahenci)
+ */
+function checkedChoiseItems(type, store) {
+
+	updateCountItemCheckedByType(type.toLowerCase());
+
+	var idElement = 'smad-table-' + type;
+
+	// if id element exist
+	if (document.getElementById(idElement)) {
+
+		// if not checked
+		if (!store) {
+			return false;
+		}
+
+		// checked again if user selected Item (pracownicy/kontrahent)
+			for (i = 0; i < store.length; i++) {
+				$('#body-'+type.toLowerCase() +' input[type=checkbox] ').map(function(k, v) {
+				    if ( store[i] === parseInt(this.value) ){
+								$(this).prop('checked', true);
+				    }
+					}).get();
+			}
+
+	}
+
+	$('#smad-table-' + type + ' input[type=checkbox]').on( 'load', function() {
+		var itemsCHecked = getItemLocalStorage('Anton1.biAuditForm.pracownicyIds');
+
+	  getItemLocalStorage('Anton1.biAuditForm.kontrahenciIds');
+
+				if (itemsCHecked.lenght === 0 ) {
+						return;
+				}
+			  var valueCheckbox = null;
+				var checkboxes = $('form').find(':checkbox');
+				if($(this).prop('checked')) {
+					   checkboxes.prop('checked', true);
+						 var allValsChecked = [];
+						 var checkedValues = $('#smad-table-' + type + ' input:checkbox:checked').map(function() {
+
+							 if (this.value !== 'on') {
+								  allValsChecked.push(parseInt(this.value));
+							 }
+				}).get();
+
+					updateListIdBiAuditReaport(type, allValsChecked);
+
+			} else {
+
+				checkboxes.prop('checked', false);
+
+				var allValsUnChecked = [];
+				var checkedValues = $('#smad-table-' + type + ' input:checkbox:not(:checked)').map(function() {
+					if (this.value !== 'on') {
+						 allValsUnChecked.push(parseInt(this.value));
+					}
+			 }).get();
+
+				deleteListIdBiAuditReaport(type, allValsUnChecked);
+			}
+
+	});
+}
+
+function catchEventCheckbox(type) {
+
+		$('#smad-table-' + type + ' input[type="checkbox"]').on('change', function() {
+		    if($(this).is(":checked")) {
+					var allValsChecked = [];
+					if (this.value !== 'on') {
+						 allValsChecked.push(parseInt(this.value));
+					}
+
+					updateListIdBiAuditReaport(type, allValsChecked);
+		    } else  {
+
+						var allValsUnChecke = [];
+						if (this.value !== 'on') {
+							 allValsUnChecke.push(parseInt(this.value));
+						}
+
+						deleteListIdBiAuditReaport(type, allValsUnChecke);
+		    }
+
+				// update count selected IDs
+				updateCountItemCheckedByType(type.toLowerCase());
+		});
+
+}
+
+function clearSelectedCheckbox() {
+	$('#checkAll-PRACOWNICY').prop('checked', false)
+	$('#checkAll-KONTRAHENCI').prop('checked', false)
+}
+
+function updateListIdBiAuditReaport(type, valueArray) {
+
+		var currentStoragePracownicyIds = [];
+		var updateListPracownicyIds = null;
+		var currentStorageKontrahenciIds = [];
+		var updateListKontrahenciIds = null;
+
+		if ( type == 'PRACOWNICY') {
+				currentStoragePracownicyIds = getItemLocalStorage('Anton1.biAuditForm.pracownicyIds');
+
+				if(currentStoragePracownicyIds !== null) {
+					updateListPracownicyIds = [...new Set([...currentStoragePracownicyIds ,...valueArray])];
+				}
+				else {
+					updateListPracownicyIds = valueArray;
+				}
+
+				setItemLocalStorage('Anton1.biAuditForm.pracownicyIds', updateListPracownicyIds);
+		}
+
+		if ( type == 'KONTRAHENCI') {
+				currentStorageKontrahenciIds = getItemLocalStorage('Anton1.biAuditForm.kontrahenciIds');
+
+				if(currentStorageKontrahenciIds !== null) {
+					updateListKontrahenciIds = [...new Set([...currentStorageKontrahenciIds ,...valueArray])];
+				}
+				else {
+					updateListKontrahenciIds = valueArray;
+				}
+
+				setItemLocalStorage('Anton1.biAuditForm.kontrahenciIds', updateListKontrahenciIds);
+		}
+}
+
+function deleteListIdBiAuditReaport(type, valueArray) {
+		if ( type == 'PRACOWNICY') {
+				deleteItemLocalStorage('Anton1.biAuditForm.pracownicyIds', valueArray);
+		}
+		if ( type == 'KONTRAHENCI') {
+				deleteItemLocalStorage('Anton1.biAuditForm.kontrahenciIds', valueArray);
+		}
+}
+
+function fetchGroupPracownicy() {
+	fetch(URL_FETCH_GROUP_PRACOWNICY, {
+		credentials: 'same-origin'
+	})
+	.then(function parseJSON(response) {
+		return response.json()
+	})
+	.then(function(data) {
+		setItemLocalStorage('Anton1.biAuditForm.pracownicy.groups', data.body.itmesGroupPracownicy);
+
+		if (data.body.itmesGroupPracownicy === null) {
+			return;
+		}
+
+		var filterIdGroup = getItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup');
+		var currentDepthValue = getItemLocalStorage('Anton1.biAuditForm.depth');
+		setItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup', filterIdGroup);
+
+		setItemLocalStorage('Anton1.biAuditForm.depth', currentDepthValue);
+
+		var groupsPracownicy = '';
+		var activeButton = '';
+
+		data.body.itmesGroupPracownicy.forEach (function(row) {
+			activeButton = '';
+			if ( filterIdGroup === parseInt(row['ID']) ) {
+				activeButton = 'active';
+				$('#group-pracownicy button.active').removeClass('active');
+			}
+			groupsPracownicy += '<button class="btn btn-default '+activeButton+'" title="' + row['NAZWA'] + '" data-group-filter="' + row['ID'] + '">' + row['NAZWA'] + '</button>';
+		});
+		$("#group-pracownicy").append(groupsPracownicy);
+		updateCountItemCheckedByType('pracownicy');
+
+		detectChoiseFilter();
+	}).catch(function(error) {
+		if(DBG) console.log('request failed', error)
+	});
+}
+
+function fetchGroupKontrahenci() {
+	fetch(URL_FETCH_GROUP_KONTRAHENCI, {
+		credentials: 'same-origin'
+	})
+	.then(function parseJSON(response) {
+		return response.json()
+	})
+	.then(function(data) {
+		setItemLocalStorage('Anton1.biAuditForm.kontrahenci.groups', data.body.itemsGroupKontrahenci);
+
+		if (data.body.itemsGroupKontrahenci === null) {
+			return;
+		}
+
+		var filterIdGroup = getItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup');
+		var currentDepthValue = getItemLocalStorage('Anton1.biAuditForm.depth');
+		setItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup', filterIdGroup);
+
+		setItemLocalStorage('Anton1.biAuditForm.depth', currentDepthValue);
+
+		var groupsKontrahenci = '';
+		var activeButton = '';
+
+		data.body.itemsGroupKontrahenci.forEach (function(row) {
+			activeButton = '';
+			if ( filterIdGroup === parseInt(row['ID']) ) {
+				activeButton = 'active';
+				$('#group-kontrahenci button.active').removeClass('active');
+			}
+			groupsKontrahenci += '<button class="btn btn-default '+activeButton+'" title="'+row['NAZWA']+'" data-group-filter="'+row['ID']+'">'+row['NAZWA']+'</button>';
+		});
+
+		$("#group-kontrahenci").append(groupsKontrahenci);
+		updateCountItemCheckedByType('kontrahenci');
+
+		detectChoiseFilter();
+	}).catch(function(error) {
+		if(DBG) console.log('request failed', error)
+	});
+}
+
+
+function detectChoiseFilter() {
+
+	$('#group-kontrahenci').on('click', 'button', function(evt) {
+		$('#group-kontrahenci button.active').removeClass('active');
+		$(this).addClass('active');
+
+		// pobranie id grupy kliknietego buttonu
+		var filterIdGroup = $(this).attr("data-group-filter");
+		// aktaulna wartość  zagłebienia
+		var currentDepthValue = getItemLocalStorage('Anton1.biAuditForm.depth');
+		// czy zwracać wyniki tylko z obiektami docelowymi
+		var analizaOnlyTargets = getItemLocalStorage('Anton1.biAuditForm.analizaOnlyTargets');
+
+		// ustawienie ostaniej wartości zagłebienia  przed resete
+		setItemLocalStorage('Anton1.biAuditForm.depth', currentDepthValue);
+
+		// czy zwracać wyniki tylko z obiektami docelowymi
+		setItemLocalStorage('Anton1.biAuditForm.analizaOnlyTargets', analizaOnlyTargets);
+
+		// ustawić id grupy do sesyjnej
+		setItemLocalStorage('Anton1.biAuditForm.kontrahenci.filterIdGroup', parseInt(filterIdGroup));
+		// wywylac funckje pobrania danych
+		urlFetchKontrahenci(1);
+
+	});
+	$('#group-pracownicy').on('click', 'button', function(e) {
+		e.preventDefault();
+		$('#group-pracownicy button.active').removeClass('active');
+		$(this).addClass('active');
+
+		// pobranie id grupy kliknietego buttonu
+		var filterIdGroup = $(this).attr("data-group-filter");
+		// aktaulna wartość  zagłebienia
+		var currentDepthValue = getItemLocalStorage('Anton1.biAuditForm.depth');
+		// ustawienie ostaniej wartości zagłebienia  przed resete
+		setItemLocalStorage('Anton1.biAuditForm.depth', currentDepthValue);
+
+		// ustawić id grupy do sesyjnej
+		setItemLocalStorage('Anton1.biAuditForm.pracownicy.filterIdGroup', parseInt(filterIdGroup));
+		// wywylac funckje pobrania danych
+		urlFetchPracownicy(1);
+
+	});
+
+}
+
+
+// Local storage
+function setItemLocalStorage(key, array) {
+	localStorage.setItem(key, JSON.stringify(array));
+}
+
+function getItemLocalStorage(key) {
+	var retrievedData = localStorage.getItem(key);
+	var response = JSON.parse(retrievedData);
+
+	return response;
+}
+
+function deleteItemLocalStorage(key, itemsArray) {
+
+	var currentStorageArray = getItemLocalStorage(key);
+
+	var newStorageArray = removeItemArrayInArray(currentStorageArray, itemsArray);
+
+	setItemLocalStorage(key, newStorageArray);
+}
+
+/**
+ * arr - array
+ * item - search item
+ */
+function removeItemInArray(arr, item) {
+      for(var i = arr.length; i--;) {
+          if(arr[i] === item) {
+              arr.splice(i, 1);
+          }
+      }
+
+			return arr;
+  }
+
+/**
+ * arr - array
+ * item - array list items
+ */
+function removeItemArrayInArray(arr, itemsArray) {
+
+      for(var i = arr.length; i--;) {
+	      for(var j = itemsArray.length; j--;) {
+	          if(arr[i] === itemsArray[j]) {
+	              arr.splice(i, 1);
+	          }
+	      }
+      }
+
+			return arr;
+  }
+
+/**
+ * Cleart list local storage by type
+ * typeNameLocalStorage - name (praconwicy/kontrahenci)
+ */
+function clearListLocalStorageByType(typeNameLocalStorage) {
+
+	if (typeNameLocalStorage === 'pracownicy') {
+		setItemLocalStorage('Anton1.biAuditForm.pracownicyIds', []);
+	}
+
+	if (typeNameLocalStorage === 'kontrahenci') {
+		setItemLocalStorage('Anton1.biAuditForm.kontrahenciIds', []);
+	}
+	// update count selected item
+	updateCountItemCheckedByType(typeNameLocalStorage);
+	// unchecked checkbox
+	$('#smad-table-'+typeNameLocalStorage.toUpperCase()+' form').find(':checkbox').prop('checked', false);
+}
+
+/**
+ * Update count selected pracowniyc/kontrahenci
+ */
+function updateCountItemCheckedByType(typeNameLocalStorage) {
+  var countId = 0;
+
+	updateTopCounters();
+
+	if (typeNameLocalStorage === 'pracownicy') {
+		var countPracownicy = getItemLocalStorage('Anton1.biAuditForm.pracownicyIds');
+
+		if (countPracownicy === null || countPracownicy === undefined) {
+			return countId;
+		}
+		countId = Object.keys(countPracownicy).length;
+		$('#count-selected-item-pracownicy').text(countId);
+	}
+
+	if (typeNameLocalStorage === 'kontrahenci') {
+		var countKontrahenci = getItemLocalStorage('Anton1.biAuditForm.kontrahenciIds');
+
+		if (countKontrahenci === null || countKontrahenci === undefined) {
+			return countId;
+		}
+
+		countId = Object.keys(countKontrahenci).length;
+		$('#count-selected-item-kontrahenci').text(countId);
+	}
+
+	return countId;
+}
+
+function updateTopCounters() {
+	var idsPracownicy = getListFromLocalStorage('Anton1.biAuditForm.pracownicyIds');
+	var idsKontrahenci = getListFromLocalStorage('Anton1.biAuditForm.kontrahenciIds');
+	var pozostaleOd = getListFromLocalStorage(getSelectedListLocalStorageKey('OD'));
+	var pozostaleDo = getListFromLocalStorage(getSelectedListLocalStorageKey('DO'));
+	var allOdLength = idsPracownicy.length + pozostaleOd.length;
+	var allDoLength = idsKontrahenci.length + pozostaleDo.length;
+	var depthValue = getItemLocalStorage('Anton1.biAuditForm.depth');
+
+	if (globalRaportStore) globalRaportStore.dispatch({
+		type: 'UPDATE',
+		totalOdPracownicy: idsPracownicy.length,
+		totalDoKontrahenci: idsKontrahenci.length,
+	})
+}
+
+
+var P5UI__Anton1__ExportFieldSelectOverlay = createReactClass({
+	handleChange: function (fieldName) {
+		DBG && console.log('DBG:P5UI__Anton1__ExportFieldSelectOverlay:handleChange', { fieldName })
+		this.props.handleToggle(fieldName);
+	},
+	setRef: function (reactComponent) {
+		this._rootNode = reactComponent;
+	},
+	componentWillMount: function () { // TODO: mv to div at the end of body, then position div by event.target.offsetTop / offsetLeft
+		this._closeDropdownIfClickedOutside = function (event) {
+			if (DBG) console.log("P5UI__Anton1__ExportFieldSelectOverlay::_closeDropdownIfClickedOutside idHtmlPopover:", { 'this__rootNode': this._rootNode })
+			if (!this._rootNode) return;
+
+			var isClickedOutside = p5UI__clickedOutsideElement(this._rootNode, event)
+			if (isClickedOutside) {
+				this._unbindCloseDropdownIfClickedOutside();
+				this.props.handleClose();
+			}
+		}.bind(this);
+		this._bindCloseDropdownIfClickedOutside = function () {
+			if (DBG) console.log("P5UI__Anton1__ExportFieldSelectOverlay::_bindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside)
+			if (!document.addEventListener && document.attachEvent) {
+				document.attachEvent('onclick', this._closeDropdownIfClickedOutside);
+			} else {
+				document.addEventListener('click', this._closeDropdownIfClickedOutside);
+			}
+		}.bind(this);
+		this._unbindCloseDropdownIfClickedOutside = function () {
+			if (DBG) console.log("P5UI__Anton1__ExportFieldSelectOverlay::_unbindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside)
+			if (!document.removeEventListener && document.detachEvent) {
+				document.detachEvent('onclick', this._closeDropdownIfClickedOutside);
+			} else {
+				document.removeEventListener('click', this._closeDropdownIfClickedOutside);
+			}
+		}.bind(this);
+	},
+	componentDidMount: function () {
+		this._bindCloseDropdownIfClickedOutside();
+	},
+	renderExportField: function (field) {
+		// <li><input checked="" type="checkbox" title="ID" value="ID">&nbsp;Nr</li>
+		var self = this;
+		var fieldName = field.name;
+		var label = field.label;
+		var isChecked = this.props.exportFieldsStore.state.selected.has(fieldName);
+		return h('li', {}, [
+			h('label', { style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
+				h('input', {
+					checked: isChecked,
+					type: "checkbox",
+					title: fieldName,
+					value: fieldName,
+					onChange: function () {
+						self.handleChange(fieldName);
+					}
+				}),
+				" ",
+				label.replace(/_/g, ' ')
+			])
+		]);
+	},
+
+	handleExportToHTML: function (event) {
+		event.preventDefault();
+		this.openExportWindow('html');
+	},
+	handleExportToCSV: function (event) {
+		event.preventDefault();
+		this.openExportWindow('csv');
+	},
+	handleExportToLatin2CSV: function (event) {
+		event.preventDefault();
+		this.openExportWindow('csv_cp1250');
+	},
+	handleExportToXLS: function (event) {
+		event.preventDefault();
+		this.openExportWindow('xls');
+	},
+	handleExportToXLSX: function (event) {
+		event.preventDefault();
+		this.openExportWindow('xlsx');
+	},
+	openExportWindow: function (format) {
+		var selected = this.props.exportFieldsStore.state.selected;
+		DBG && console.log('DBG:P5UI__Anton1__ExportFieldSelectOverlay:openExportWindow', { format: format, selected: selected })
+		var exportUrl = [ 'index.php?_route=ExportTableAjax&namespace=' + this.props.namespace,
+			'format=' + format,
+			'flds=' + Array.from(selected).join(','),
+			'sortCol=' + (this.props.sortCol || ''),
+			'sortDir=' + (this.props.sortDir ? "desc" : "asc"),
+			this.props.queryFilter
+		].join('&');
+		var win = window.open(exportUrl, '_blank');
+		win.focus();
+	},
+	// 	if (!exportFields.length) {
+	// 		alert('Nie wybrano żadnych pól do eksportu.');
+	// 		e.preventDefault();
+	// 		return false;
+	// 	}
+
+	// 	var limit = 10000;
+	// 	if (!_data.total || _data.total <= 0) {
+	// 		alert('Brak rekordów do eksportu.');
+	// 		e.preventDefault();
+	// 		return false;
+	// 	}
+	// 	if (_data.total > limit) {
+	// 		if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
+	// 			e.preventDefault();
+	// 			return false;
+	// 		}
+	// 	}
+
+	renderExportToHTML: function () {
+		return h('li', {}, [
+			h('a', { href: "#", onClick: this.handleExportToHTML, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
+				h('i', { className: "glyphicon glyphicon-share" }),
+				" Export do HTML"
+			])
+		]);
+	},
+	renderExportToCSV: function () {
+		return h('li', {}, [
+			h('a', { href: "#", onClick: this.handleExportToCSV, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
+				h('i', { className: "glyphicon glyphicon-share" }),
+				" Export do CSV"
+			])
+		]);
+	},
+	renderExportToLatin2CSV: function () {
+		return h('li', {}, [
+			h('a', {
+				href: "#", onClick: this.handleExportToLatin2CSV,
+				style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" },
+				title: "Export do pliku CSV w kodowaniu Windows-1250",
+			}, [
+				h('i', { className: "glyphicon glyphicon-share" }),
+				" Export do CSV (Windows-1250)"
+			])
+		]);
+	},
+	renderExportToXLS: function () {
+		return h('li', {}, [
+			h('a', { href: "#", onClick: this.handleExportToXLS, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
+				h('i', { className: "glyphicon glyphicon-share" }),
+				" Export do XLS"
+			])
+		]);
+	},
+	renderExportToXLSX: function () {
+		return h('li', {}, [
+			h('a', { href: "#", onClick: this.handleExportToXLSX, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
+				h('i', { className: "glyphicon glyphicon-share" }),
+				" Export do XLSX"
+			])
+		]);
+	},
+
+	render: function () {
+		if (!this.props.exportFields) console.warn('DBG: missing this.props.exportFields', { 'this.props': this.props });
+		if (!this.props.exportFields) return null;
+		return h('ul', {
+			ref: this.setRef,
+			className: "dropdown-menu",
+			style: {
+				height: "250px",
+				'min-width': "300px",
+				'padding': "5px 20px 5px 8px",
+				overflow: "auto",
+				display: "block",
+				position: "absolute",
+				left: this.props.offsetLeft,
+				top: this.props.offsetTop - 250,
+				margin: 0,
+				// height: 250px;
+				// this.props.btnBBox
+			},
+		}, this.props.exportFields.map(this.renderExportField).concat([
+			this.renderExportToHTML(),
+			this.renderExportToCSV(),
+			this.renderExportToLatin2CSV(),
+			this.renderExportToXLS(),
+			this.renderExportToXLSX(),
+		]));
+	}
+});
+
+var _Containers__ExportFields = {}; // namespace => Unstated Container
+var _Containers__get = function (namespace, initialSelected) {
+	if (_Containers__ExportFields[namespace]) return _Containers__ExportFields[namespace];
+	var selected = new Set();
+	if (initialSelected) initialSelected.forEach(function (field) {
+		selected.add(field.name);
+	})
+	_Containers__ExportFields[namespace] = global.p5VendorJs.createUnstatedContainer({
+		state: {
+			namespace: namespace,
+			selected: selected,
+		},
+		toggleField(fieldName) {
+			var selected = this.state.selected;
+			selected.has(fieldName) ? selected.delete(fieldName) : selected.add(fieldName)
+			this.setState({ selected: selected });
+		},
+		selectField(fieldName) {
+			var selected = this.state.selected;
+			selected.add(fieldName)
+			this.setState({ selected: selected });
+		},
+		unselectField(fieldName) {
+			var selected = this.state.selected;
+			selected.delete(fieldName)
+			this.setState({ selected: selected });
+		},
+
+	});
+	// namespace = 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY';
+	// namespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI';
+	return _Containers__ExportFields[namespace];
+}
+
+var P5UI__Anton1__ExportTable = createReactClass({ // @props: { namespace, exportFields }
+	_node: null,
+	getInitialState: function () {
+		return {
+			isOpen: false,
+		};
+	},
+	handleToggleDropdown: function (event) {
+		var offsetLeft = 0;
+		var offsetTop = 0;
+
+		this.removePopup();
+		if (!this.state.isOpen) {
+			var btnBBox = ("BUTTON" !== event.target.nodeName) ? event.target.parentNode.getBoundingClientRect() : event.target.getBoundingClientRect();
+			offsetLeft = btnBBox.left;
+			offsetTop = window.pageYOffset + btnBBox.y;
+			this._node = document.createElement('div');
+			this._node.setAttribute('data-p5class', "P5UI__Anton1__ExportTable");
+			this._node.position = "absolute";
+			this._node.left = "0";
+			this._node.top = "0";
+			this._node.height = "100%";
+			this._node.backgroundColor = "#00000050";
+			this._node.width = "100%";
+			var handleClose = this.handleClose.bind(this);
+			var exportFields = this.props.exportFields;
+			var exportFieldsContainer = _Containers__get(this.props.namespace, this.props.exportFields);
+
+			document.body.appendChild(this._node);
+
+			var self__props = this.props;
+			ReactDOM.render(
+				h(Unstated.Provider, {}, [
+					h(Unstated.Subscribe, { to: [ exportFieldsContainer ] },
+						function (exportFieldsCont) {
+							DBG && console.log('DBG:exportFieldsCont', { exportFieldsCont })
+							return h(P5UI__Anton1__ExportFieldSelectOverlay, Object.assign({}, self__props, {
+								exportFields: exportFields,
+								btnBBox: btnBBox,
+								exportFieldsStore: exportFieldsCont,
+								handleToggle: exportFieldsCont.toggleField.bind(exportFieldsCont),
+								handleClose: handleClose,
+								offsetLeft: offsetLeft,
+								offsetTop: offsetTop,
+							}));
+						}
+					)
+				]),
+				this._node
+			);
+		}
+		this.setState({ isOpen: !this.state.isOpen });
+	},
+	removePopup: function () {
+		if (this._node && 1 === this._node.nodeType) {
+			document.body.removeChild(this._node);
+		}
+		this._node = null;
+	},
+	handleClose: function () {
+		this.removePopup();
+		this.setState({ isOpen: false });
+	},
+	render: function () {
+		// Pagination.code += '<div class="btn-group dropup pagesize" style="margin-left:40px">' +
+		// <button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;<span class="caret"></span></button>
+		// <ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">
+		//   <li><input checked="" type="checkbox" title="ID" value="ID">&nbsp;Nr</li>
+		//   <li><input checked="" type="checkbox" title="A_STATUS" value="A_STATUS">&nbsp;Status</li>
+		//   ...
+		//   <li><input checked="" type="checkbox" title="TV_DVBC_EPG_CHANNEL_NUMBER" value="TV_DVBC_EPG_CHANNEL_NUMBER">&nbsp;TV: Nr kanału w EPG</li>
+		//   <li><a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a></li>
+		//   <li><a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a></li>
+		//   <li><a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share" title="Export do pliku CSV w kodowaniu Windows-1250"></i>Export do CSV (Windows-1250)</a></li>
+		// </ul></div>';
+		return h('div', {
+			className: "btn-group", // className: "btn-group dropup pagesize" + " open",
+		}, [
+			h('button', {
+				className: "btn btn-sm btn-default", // className: "btn btn-sm btn-default dropdown-toggle", // 'data-toggle': "dropdown",
+				onClick: this.handleToggleDropdown
+			}, [
+				"Export ",
+				h('span', { className: "caret" }),
+			]),
+			// h('ul', {
+			// 	className: "dropdown-menu",
+			// 	style: {
+			// 		'max-height': "250px",
+			// 		'min-width': "300px",
+			// 		'padding': "5px 20px 5px 8px",
+			// 		overflow: "auto",
+			// 	}
+			// }, this.props.exportFields.map(this.renderExportField))
+		]);
+
+		// @from TableAjax:
+		// if (priv.options.exportFields && priv.options.exportFields.length) {
+		// 	node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
+		// 	var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;</button>').appendTo(node);
+		// 	var span = $('<span class="caret"></span>').appendTo(btn);
+		// 	var ul = $('<ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">').appendTo(node);
+
+		// 	$.each(_data.cols, function (col, props) {
+		// 		if (-1 !== priv.options.exportFields.indexOf(col)) {
+		// 			var li = $('<li></li>').appendTo(ul);
+		// 			$(p5Utils__format('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>', [(_exportFieldsSelect[col]) ? 'checked' : '', col, props.friendly || col])).appendTo(li);
+		// 			li.on('click', 'input', priv.exportFieldChanged);
+		// 		}
+		// 	});
+
+		// 	var li = $('<li></li>').appendTo(ul);
+		// 	$('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
+		// 	li.on('click', 'a', priv.exportToHTML);
+		// 	var li = $('<li></li>').appendTo(ul);
+		// 	$('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
+		// 	li.on('click', 'a', priv.exportToCSV);
+		// 	var li = $('<li></li>').appendTo(ul);
+		// 	$('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share" title="Export do pliku CSV w kodowaniu Windows-1250"></i>Export do CSV (Windows-1250)</a>').appendTo(li);
+		// 	li.on('click', 'a', priv.exportToCSVWinCP1250);
+		// } else {
+		// 	node = $('<span class="' + nodeClass + '"></span>');
+		// }
+	}
+});
+
+
+// Pagination
+var Pagination = {
+
+    code: '',			// end show html paginations
+    clickPage: 1, // set default 1 page
+
+    // --------------------
+    // Utility
+    // --------------------
+    //  initialize  default data
+    Extend: function(data) {
+        data = data || {};
+        Pagination.url = data.url;
+        Pagination.id_pagination = data.id_pagination;
+        Pagination.type = data.type;
+        Pagination.limit = data.limit;
+        Pagination.total_items = data.total_items;
+        Pagination.size = data.size || 2;
+        Pagination.page = data.page || 1;
+        Pagination.step = data.step || 3;
+    },
+
+    // add pages by number (from [s] to [f])
+    Add: function(s, f) {
+        for (var i = s; i < f; i++) {
+            Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default">' + i + '</a></li>';
+        }
+    },
+
+    // add last page with separator
+    Last: function() {
+        Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default">>></a></li>';
+    },
+
+    // add first page with separator
+    First: function() {
+        Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default"><<</a></li>';
+    },
+
+    // add last page with separator
+    Next: function() {
+        Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default">></a></li>';
+    },
+
+    // add first page with separator
+    Prev: function() {
+        Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default"><</a></li>';
+    },
+
+
+
+    // --------------------
+    // Handlers
+    // --------------------
+
+    // change page
+    Click: function() {
+		clearSelectedCheckbox();
+
+		var selectPage = $("#pagination-"+Pagination.type.toLowerCase()+' .tblAjax__footer__toolbar__pagination').find('a.active').text();
+		Pagination.clickPage = +this.innerHTML || '';
+		if ( selectPage === NaN || selectPage > Pagination.size) { selectPage = 1; }
+
+		switch (this.innerHTML) {
+			case '&gt;&gt;': // last
+				Pagination.clickPage = Pagination.size;
+				break;
+
+			case '&lt;&lt;': // first
+				Pagination.clickPage = 1;
+				break;
+
+			case '&lt;': // prev
+				Pagination.clickPage = parseInt(selectPage) - 1;
+				if (Pagination.clickPage < 1) {
+						Pagination.clickPage = 1;
+				}
+
+				break;
+
+			case '&gt;': // next
+				Pagination.clickPage = parseInt(selectPage) + 1;
+
+				if (Pagination.clickPage > Pagination.size) {
+						Pagination.clickPage = Pagination.size;
+				}
+				break;
+		}
+
+		if ( Pagination.type === 'KONTRAHENCI' ) {
+			setItemLocalStorage('Anton1.biAuditForm.kontrahenci.pagination.page', Pagination.clickPage);
+			Pagination.page = urlFetchKontrahenci(Pagination.clickPage);
+		}
+		else if ( Pagination.type === 'PRACOWNICY' ){
+			setItemLocalStorage('Anton1.biAuditForm.pracownicy.pagination.page', Pagination.clickPage);
+			Pagination.page = urlFetchPracownicy(Pagination.clickPage);
+		}
+
+        Pagination.Start();
+    },
+
+
+    // --------------------
+    // Script structure pagination
+    // --------------------
+
+    // binding pages
+    Bind: function() {
+        var a = Pagination.e.getElementsByTagName('a');
+		// var currentPage = Pagination.clickPage || 1;
+        for (var i = 0; i < a.length; i++) {
+            if (+a[i].innerHTML === Pagination.page) a[i].className = 'btn btn-default active';
+            a[i].addEventListener('click', Pagination.Click, false);
+        }
+    },
+
+	ExportWidget: function() {
+		var exportWidgetId = 'p5__exportWidget__' + Pagination.type;
+		Pagination.code += '<div id="' + exportWidgetId + '" class="btn-group dropup pagesize" style="margin-left:40px"></div>';
+	},
+	getSearchQueryFilter: function () { // @return url query filter by namespace
+		switch (Pagination.type) {
+			case 'PRACOWNICY': {
+				var searchParams = getSearchParamsPracownicy();
+				return [
+					searchParams.filterFields,
+					(searchParams.filterIdGroup) ? 'filterIdGroup=' + searchParams.filterIdGroup : null, // TODO: backRef search
+				].filter(Boolean).join('&')
+			}
+			case 'KONTRAHENCI': {
+				var searchParams = getSearchParamsKontrahenci();
+				return [
+					searchParams.filterFields,
+					(searchParams.filterIdGroup) ? 'filterIdGroup=' + searchParams.filterIdGroup : null, // TODO: backRef search
+				].filter(Boolean).join('&')
+			}
+			default: return '';
+		}
+	},
+	CreateExportWidget: function() {
+		var exportFields = null;
+		var namespace = '';
+		if (Pagination.type === 'PRACOWNICY') {
+			exportFields = EXPORT_FIELDS_OD;
+			namespace = 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY';
+		} else if (Pagination.type === 'KONTRAHENCI') {
+			exportFields = EXPORT_FIELDS_DO;
+			namespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI';
+		}
+		DBG && console.log('DBG:EXPORT_FIELDS...', { EXPORT_FIELDS_OD, EXPORT_FIELDS_DO, exportFields });
+		if (!exportFields || (exportFields && !exportFields.length)) return;
+
+		var exportWidgetId = 'p5__exportWidget__' + Pagination.type;
+		var node = document.getElementById(exportWidgetId);
+		DBG && console.log('node: ', { node });
+		if (!node) return;
+
+		var sortCol = 'ID';
+		var sortDir = 'desc';
+		var queryFilter = Pagination.getSearchQueryFilter();
+		ReactDOM.render(
+			h(P5UI__Anton1__ExportTable, {
+				namespace: namespace,
+				exportFields: exportFields,
+				sortCol: sortCol,
+				sortDir: sortDir,
+				queryFilter: queryFilter,
+			}),
+			node
+		);
+	},
+
+
+	Finish: function() {
+        Pagination.e.innerHTML = Pagination.code;
+        Pagination.Bind();
+        Pagination.CreateExportWidget();
+    },
+
+
+    // find pagination type
+    Start: function() {
+		Pagination.code = '';
+		if ( Pagination.type === 'KONTRAHENCI' ) {
+			Pagination.code += '<div class="foot-info tblAjax__footer__toolbar__info footer_pagination_menu_items"><p>Wiersze od <span id="paginationShowNextCount-KONTRAHENCI"></span> do ' + Pagination.total_items + ' z ' + Pagination.total_items + '</p></div>';
+		} else if ( Pagination.type === 'PRACOWNICY' ) {
+			Pagination.code += '<div class="foot-info tblAjax__footer__toolbar__info footer_pagination_menu_items"><p>Wiersze od <span id="paginationShowNextCount-PRACOWNICY"></span> do ' + Pagination.total_items + ' z ' + Pagination.total_items + '</p></div>';
+		}
+		Pagination.code += '<nav aria-label="Page navigation" class="footer_pagination_menu_items"><ul class="btn-group tblAjax__footer__toolbar__pagination smad-pagination" style="margin-bottom:0">';
+		Pagination.First();
+		Pagination.Prev();
+
+		if ( Pagination.type === 'KONTRAHENCI' ) {
+			Pagination.page = getItemLocalStorage('Anton1.biAuditForm.kontrahenci.pagination.page') || 1;
+		}
+		else if ( Pagination.type === 'PRACOWNICY' ) {
+			Pagination.page = getItemLocalStorage('Anton1.biAuditForm.pracownicy.pagination.page') || 1;
+		}
+
+		if ( Pagination.page > Pagination.size ) {
+			Pagination.page = 1;
+		}
+
+        if (Pagination.size < Pagination.step * 2 + 6) {
+            Pagination.Add(1, Pagination.size + 1);
+        }
+        else if (Pagination.page < Pagination.step * 2 + 1) {
+            Pagination.Add(1, Pagination.step * 2 + 4);
+        }
+        else if (Pagination.page > Pagination.size - Pagination.step * 2) {
+            Pagination.Add(Pagination.size - Pagination.step * 2 - 2, Pagination.size + 1);
+        }
+        else {
+            Pagination.Add(Pagination.page - Pagination.step, Pagination.page + Pagination.step + 1);
+        }
+		Pagination.Next();
+		Pagination.Last();
+		Pagination.code += '</ul></nav>';
+		Pagination.ExportWidget();
+        Pagination.Finish();
+    },
+
+
+    // --------------------
+    // Initialization
+    // --------------------
+
+    // binding buttons
+    Buttons: function(e) {
+        var nav = e.getElementsByTagName('a');
+    },
+
+    // create skeleton
+    Create: function(element) {
+
+        var html = [
+             '<div></div>'  // pagination container
+        ];
+
+		element.innerHTML = html.join('');
+		Pagination.e = element.getElementsByTagName('div')[0];
+		Pagination.Buttons(element);
+    },
+
+    // init
+    Init: function(element, options) {
+        Pagination.Extend(options);
+        Pagination.Create(element);
+        Pagination.Start();
+    }
+};
+
+function todo__fetchRaport(id) {
+/*	p5WFS_GetFeature('default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', {
+		primaryKey: id,
+		resolve: 'all',
+		resolveDepth: 3,
+	}).then(function (features) {
+		if(DBG) console.log('features', features)
+	}).catch(function (e) {
+		if(DBG) console.warn(e)
+		p5UI__notifyAjaxCallback({ type: 'error', msg: e })
+	})*/
+}
+
+function removeFiltersPracownicy(event, btnNode) {
+	event.preventDefault()
+	var fieldNameList = FIELD_LIST_PRACOWNICY
+	fieldNameList.forEach(function (fieldName) {
+		btnNode.form[fieldName].value = ''
+	})
+	urlFetchPracownicy(1)
+}
+function removeFiltersKontrahenci(event, btnNode) {
+	event.preventDefault()
+	var fieldNameList = FIELD_LIST_KONTRAHENCI
+	fieldNameList.forEach(function (fieldName) {
+		btnNode.form[fieldName].value = ''
+	})
+	urlFetchKontrahenci(1)
+}
+
+function onChangeFiltersPracownicy(event, inputNode) {
+	urlFetchPracownicy(1)
+}
+function onKeypressFiltersPracownicy(event, inputNode) {
+	if ("Enter" === event.key) {
+		event.stopPropagation()
+		event.preventDefault()
+		urlFetchPracownicy(1)
+		return false
+	}
+}
+function onChangeFiltersKontrahenci(event, inputNode) {
+	urlFetchKontrahenci(1)
+}
+function onKeypressFiltersKontrahenci(event, inputNode) {
+	if ("Enter" === event.key) {
+		event.stopPropagation()
+		event.preventDefault()
+		urlFetchKontrahenci(1)
+		return false
+	}
+}
+
+function loadMoreRecordFunctions(event, node, rowPK, namespace) {
+	var _node = node
+	var _rowPK = rowPK
+	var toShow = true
+	if (RECORD_MORE_FUNCTIONS_OPENED_NODE) {
+		if (RECORD_MORE_FUNCTIONS_OPENED_NODE === node) toShow = false
+		if (RECORD_MORE_FUNCTIONS_OPENED_NODE !== node) {
+			jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
+		}
+	}
+	RECORD_MORE_FUNCTIONS_OPENED_NODE = node
+
+	// jQuery(node).popover({
+	// 	container: 'body',
+	// 	placement: 'right',
+	// 	trigger: 'click',
+	// 	template: '<div class="popover" role="tooltip" style="max-width:600px;width:440px;">' +
+	// 		'<div class="arrow"></div>' +
+	// 		'<div style="display:block;position:relative;">' +
+	// 			'<div class="popover-title">' +
+	// 			'</div>' +
+	// 			'<button type="button" class="close" onclick="return hideMoreRecordFunctionsPopover();" style="position:absolute;right:8px;top:6px;">&times;</button>' +
+	// 		'</div>' +
+	// 		'<div class="popover-content"></div>' +
+	// 		'</div>' +
+	// 	'',
+	// 	html: true,
+	// })
+	// jQuery(node).popover('show')
+
+	global.fetch(BASE_URLS + 'index.php?_route=ViewTableAjax&namespace=' + namespace + '&_task=moreFunctionsCellAjax&ID=' + rowPK, {
+		credentials: 'same-origin'
+	}).then(function (response) {
+		return response.json()
+	}).then(function (json) {
+		var funcListWrap = $('<div></div>')
+
+		if (_node === RECORD_MORE_FUNCTIONS_OPENED_NODE) {
+			if (json && 'success' === json.type && json.rowFunctions && json.rowFunctions.length > 0) {
+				var popoverContent = generateViewMoreRecordFunctions(json.rowFunctions, namespace, _rowPK);
+				popoverContent.appendTo(funcListWrap);
+			}
+		}
+
+		// jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
+		jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover({
+			container: 'body',
+			placement: 'right',
+			trigger: 'click',
+			template: '<div class="popover" role="tooltip" style="max-width:600px;width:440px;">' +
+				'<div class="arrow"></div>' +
+				'<div style="display:block;position:relative;">' +
+					'<div class="popover-title">' +
+					'</div>' +
+					'<button type="button" class="close" onclick="return hideMoreRecordFunctionsPopover();" style="position:absolute;right:8px;top:6px;">&times;</button>' +
+				'</div>' +
+				'<div class="popover-content"></div>' +
+				'</div>' +
+			'',
+			html: true,
+			content: funcListWrap.html(),
+		})
+		jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('show')
+
+	}).catch(function (err) {
+		if(DBG)  console.log('err', err);
+	})
+}
+
+function generateViewMoreRecordFunctions(rowFunctions, namespace, rowPK) {
+	var popoverContent;
+	var funcNodesToUpdate = [];
+
+	if (!rowFunctions.length) {
+		popoverContent = $('<p class="text-muted">Brak dodatkowych funkcji</p>');
+	} else if (3 === namespace.split('/').length) { // if namesapce is AntAcl [ and has ref fields or back ref ]
+		popoverContent = $('<ul class="list-unstyled"></ul>');
+		var rowFunctionsByType = rowFunctions.reduce(function (ret, funObj) {
+			if (
+				'Powiązania od ' === funObj.label.substr(0, 'Powiązania od '.length)
+				|| 'Powiązania do ' === funObj.label.substr(0, 'Powiązania do '.length)
+			) {
+				if (funObj.total > 0) {
+					ret.refConnections.push(funObj);
+				} else {
+					ret.refEmptyConnections.push(funObj);
+				}
+			} else {
+				ret.others.push(funObj);
+			}
+			return ret;
+			// href: "https://biuro.biall-net.pl/dev-pl/se-master/index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_KRS/BI_audit_KRS&childRefNS=default_db/BI_audit_KRS/BI_audit_KRS&childRefPK=2068689"
+			// ico: "glyphicon glyphicon-random"
+			// label: "Powiązania od 'KRS' <span class="badge">0</span>"
+			// title: "Powiązania od 'Audyt / KRS' (0)"
+		}, { refConnections: [], refEmptyConnections: [], others: [] });
+
+		rowFunctionsByType.others.forEach(function (funObj) {
+			var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, { ico: true, label: true });
+			if (funObj.id) {
+				funcNodesToUpdate.push({ id: funObj.id, node: funcNode });
+			} else {
+				var funcItemNode = $('<li></li>').appendTo(popoverContent);
+				funcItemNode.append(funcNode);
+			}
+		});
+
+		if (!rowFunctionsByType.refConnections.length) {
+			$('<li>Brak powiązań</li>').appendTo(popoverContent);
+		} else {
+			var refConnItemNode = $('<li style="margin-top:10px"><i class="glyphicon glyphicon-random"></i> <b>Powiązania</b></li>').appendTo(popoverContent);
+			{
+				var funObj = {
+					// ico: 'glyphicon glyphicon-random',
+					label: 'przeglądaj',
+					title: "Przeglądaj powiązania",
+					href: 'index.php?_route=RefGraph&namespace=' + namespace + '&primaryKey=' + rowPK,
+					// onclick: function (e) { // TODO: open in
+					// 	console.log('TODO: przeglądaj powiązania')
+					// }
+				}
+				var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, { ico: true, label: true })
+				refConnItemNode.append(" - ");
+				refConnItemNode.append(funcNode);
+			}
+			var refConnFuncList = $('<ul class="list-unstyled" style="margin-left:20px"></ul>').appendTo(refConnItemNode);
+			rowFunctionsByType.refConnections.forEach(function (funObj) {
+				var refFunObj = Object.assign({}, funObj, {
+					// ico: null,
+					label: funObj.label.substr('Powiązania '.length),
+				});
+				var funcNode = p5UI_TableAjax_generateFunctionNode(refFunObj, rowPK, { ico: true, label: true });
+				var funcItemNode = $('<li></li>').appendTo(refConnFuncList);
+				funcItemNode.append(funcNode);
+			})
+		}
+		if (rowFunctionsByType.refEmptyConnections.length) {
+			var refConnItemNode = $('<li style="margin-top:10px; opacity:0.7"></li>').appendTo(popoverContent);
+			var emptyRefsDetailsNode = $('<details></details>').appendTo(refConnItemNode);
+			// $('<summary><i class="glyphicon glyphicon-random"></i> Pozostałe powiązania</summary>').appendTo(emptyRefsDetailsNode);
+			$('<summary style="cursor:pointer">Pozostałe powiązania ...</summary>').appendTo(emptyRefsDetailsNode);
+			var refConnFuncList = $('<ul class="list-unstyled" style="margin-left:20px"></ul>').appendTo(emptyRefsDetailsNode);
+			rowFunctionsByType.refEmptyConnections.forEach(function (funObj) {
+				var refFunObj = Object.assign({}, funObj, {
+					// ico: null,
+					label: funObj.label.substr('Powiązania '.length),
+				});
+				var funcNode = p5UI_TableAjax_generateFunctionNode(refFunObj, rowPK, { ico: true, label: true });
+				var funcItemNode = $('<li></li>').appendTo(refConnFuncList);
+				funcItemNode.append(funcNode);
+			})
+		}
+	} else {
+		popoverContent = $('<ul class="list-unstyled"></ul>');
+		rowFunctions.forEach(function (funObj) {
+			var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, { ico: true, label: true });
+			if (funObj.id) {
+				funcNodesToUpdate.push({ id: funObj.id, node: funcNode });
+			} else {
+				var funcItemNode = $('<li></li>').appendTo(popoverContent);
+				funcItemNode.append(funcNode);
+			}
+		});
+	}
+
+	return popoverContent;
+}
+
+function p5UI_TableAjax_generateFunctionNode(funObj, rowPK, props) {
+	if (!rowPK) throw "Missing primaryKey in p5UI_TableAjax_generateFunctionNode";
+	var defaultsProps = {
+		ico: true,
+		label: false
+	};
+	var props = jQuery.extend({}, defaultsProps, props);
+	var funcNode = $('<a href="#" style="margin:0 2px;"></a>');
+	if ('href' in funObj) funcNode.attr('href', p5Utils__format(funObj.href, [rowPK]));
+	if (props.ico) {
+		if ('ico' in funObj) funcNode.append('<span class="' + funObj.ico + '"></span>');
+	}
+	if ('onclick' in funObj) funcNode.attr('onclick', p5Utils__format(funObj.onclick, [rowPK]));
+	if ('title' in funObj) funcNode.attr('title', funObj.title);
+	if ('target' in funObj) funcNode.attr('target', funObj.target);
+
+	if (props.label) {
+		if ('label' in funObj) {
+			funcNode.append(' ' + funObj.label);
+		} else if ('title' in funObj) {
+			funcNode.append(' ' + funObj.title);
+		}
+	}
+
+	return funcNode;
+};
+global.p5UI_TableAjax_generateFunctionNode = p5UI_TableAjax_generateFunctionNode
+
+function addAllMatchesToReport(event) {
+	switch (event.data.type) {
+		case 'kontrahenci': break; // OK
+		case 'pracownicy': break; // OK
+		default: throw "Wrong type";
+	}
+	var postData = {}
+	if ('filter_idGroup' in event.data.pagination && event.data.pagination['filter_idGroup']) postData['filter_idGroup'] = event.data.pagination['filter_idGroup']
+	Object.keys(event.data.pagination).filter(function (key) {
+		return ('f_' === key.substr(0, 2))
+	}).forEach(function (filterKey) {
+		var value = event.data.pagination[filterKey]
+		postData[filterKey] = value
+	})
+	var thisButton = $(this)
+	thisButton.attr('disabled', true)
+	thisButton.text( thisButton.text() + '...' )
+
+	if ('pracownicy' === event.data.type) {
+		p5UI__notifyAjaxCallback({ type: 'info', msg: "Pobieranie pracowników..." })
+
+		var frm = document.getElementById('filtersFieldRemoveBtn-PRACOWNICY').form
+		var fieldNameList = FIELD_LIST_PRACOWNICY
+		fieldNameList.filter(function (fieldName) {
+			if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"')
+			return (frm[fieldName]) ? true : false
+		}).map(function (fieldName) {
+			return [ fieldName, frm[fieldName].value ]
+		}).filter(function (filter) {
+			return ( filter[1].length > 0 )
+		}).forEach(function (filter) {
+			postData[ filter[0] ] = filter[1];
+		})
+
+		global.fetch(URL_FETCH_PRACOWNICY_IDS_AJAX, {
+			credentials: 'same-origin',
+			method: 'POST',
+			headers: { 'Content-Type': 'application/json' },
+			body: JSON.stringify(postData)
+		})
+		.then(function __parseJSON(response) {
+			return response.json()
+		})
+		.then(function (json) {
+			if ('success' === json.type && json.body && json.body.ids) {
+				updateListIdBiAuditReaport('PRACOWNICY', json.body.ids.map(function (id) {
+					return parseInt(id)
+				}))
+				// jQuery('#body-pracownicy').find('input[name="prID[]"]').attr('checked', true)
+				jQuery('#body-pracownicy').find('input[name="prID[]"]').each(function (idx, inputNode) {
+					inputNode.checked = true;
+				})
+				thisButton.attr('disabled', false)
+				var txt = thisButton.text()
+				thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
+				updateCountItemCheckedByType('pracownicy');
+				p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+json.body.ids.length+" pracowników" })
+			}
+		})
+		.catch(function (e) {
+			p5UI__notifyAjaxCallback({ type: 'error', msg: '' + e })
+			thisButton.attr('disabled', false)
+			var txt = thisButton.text()
+			thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
+		})
+	}
+	if ('kontrahenci' === event.data.type) {
+		p5UI__notifyAjaxCallback({ type: 'info', msg: "Pobieranie podmiotów/kontrahentów..." })
+
+		var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form
+		var fieldNameList = FIELD_LIST_KONTRAHENCI
+		fieldNameList.filter(function (fieldName) {
+			if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"')
+			return (frm[fieldName]) ? true : false
+		}).map(function (fieldName) {
+			return [ fieldName, frm[fieldName].value ]
+		}).filter(function (filter) {
+			return ( filter[1].length > 0 )
+		}).forEach(function (filter) {
+			postData[ filter[0] ] = filter[1];
+		})
+
+		global.fetch(URL_FETCH_KONTRAHENCI_IDS_AJAX, {
+			credentials: 'same-origin',
+			method: 'POST',
+			headers: { 'Content-Type': 'application/json' },
+			body: JSON.stringify(postData)
+		})
+		.then(function __parseJSON(response) {
+			return response.json()
+		})
+		.then(function (json) {
+			if ('success' === json.type && json.body && json.body.ids) {
+				updateListIdBiAuditReaport('KONTRAHENCI', json.body.ids.map(function (id) {
+					return parseInt(id)
+				}))
+				// jQuery('#body-kontrahenci').find('input[name="kontrID[]"]').attr('checked', true); // Not working
+				jQuery('#body-kontrahenci').find('input[name="kontrID[]"]').each(function (idx, inputNode) {
+					inputNode.checked = true;
+				})
+				thisButton.attr('disabled', false);
+				var txt = thisButton.text()
+				thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
+				updateCountItemCheckedByType('kontrahenci');
+				p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+json.body.ids.length+" kontrahentów" })
+			}
+		})
+		.catch(function (e) {
+			p5UI__notifyAjaxCallback({ type: 'error', msg: '' + e })
+			thisButton.attr('disabled', false)
+			var txt = thisButton.text()
+			thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
+		});
+	}
+}
+
+function mock_error__fetchLastReports(id) {
+	return new Promise(function (resolve) {
+		throw "Wystąpił błąd, spróbuj ponownie później"
+	})
+}
+function mock__fetchLastReports(id) {
+	return new Promise(function (resolve) {
+		var fakeResponse = '{"type":"success","msg":"ostatnie raporty","body":{"items":[{"id":"103","adnotacje":"raport pani x","totalPracownicy":"1","totalKontrahenci":"2"},{"id":"102","adnotacje":"test","totalPracownicy":"1","totalKontrahenci":"1"},{"id":"101","adnotacje":"Zuranski test all 7","totalPracownicy":"1","totalKontrahenci":"9307"},{"id":"100","adnotacje":"kike all 4","totalPracownicy":"5","totalKontrahenci":"9305"},{"id":"99","adnotacje":"test pracownik z KRS bez celu 3","totalPracownicy":"1","totalKontrahenci":"9305"}]}}';
+		var json = JSON.parse(fakeResponse);
+		var items = json.body.items;
+		console.log('items', items)
+		setTimeout(function () {
+			console.log('resolve items', items)
+			resolve(items);
+		}, 500);
+	});
+}
+function fetchLastReports(id) {
+	return global.fetch(URL_FETCH_LAST_REPORTS_AJAX, {
+		credentials: 'same-origin',
+		method: 'POST',
+		headers: { 'Content-Type': 'application/json' },
+		body: JSON.stringify({ id: id })
+	})
+	.then(function __parseJSON(response) {
+		return response.json()
+	})
+	.then(function (json) {
+		if ('success' === json.type && json.body && json.body.items) {
+			if (!json.body.items.length) throw "Brak danych"
+			return json.body.items;
+		}
+		throw "Wystąpił błąd, spróbuj ponownie później.";
+	})
+}
+function fetchPracownicyIdsByReport(id) {
+	return global.fetch(URL_FETCH_PRACOWNICY_IDS_BY_REPORT_AJAX, {
+		credentials: 'same-origin',
+		method: 'POST',
+		headers: { 'Content-Type': 'application/json' },
+		body: JSON.stringify({ id: id })
+	})
+	.then(function __parseJSON(response) {
+		return response.json()
+	})
+	.then(function (json) {
+		if ('success' === json.type && json.body && json.body.ids) {
+			if (!json.body.ids.length) throw "Brak danych"
+			return json.body.ids;
+		}
+		throw "Wystąpił błąd, spróbuj ponownie później.";
+	})
+}
+function fetchKontrahenciIdsByReport(id) {
+	return global.fetch(URL_FETCH_KONTRAHENCI_IDS_BY_REPORT_AJAX, {
+		credentials: 'same-origin',
+		method: 'POST',
+		headers: { 'Content-Type': 'application/json' },
+		body: JSON.stringify({ id: id })
+	})
+	.then(function __parseJSON(response) {
+		return response.json()
+	})
+	.then(function (json) {
+		if ('success' === json.type && json.body && json.body.ids) {
+			if (!json.body.ids.length) throw "Brak danych"
+			return json.body.ids;
+		}
+		throw "Wystąpił błąd, spróbuj ponownie później.";
+	})
+}
+
+function addToReportByPreviousReport(event) {
+	var pageType = (event.data.type) ? event.data.type : '';
+	handleAddToReportByPreviousReport(pageType);
+}
+function handleAddToReportByPreviousReport(pageType) {
+	switch (pageType) {
+		case 'pracownicy': break; // OK
+		case 'kontrahenci': break; // OK
+		default: throw "Wrong type";
+	}
+
+	var thisButton = $(this)
+	thisButton.attr('disabled', true)
+	thisButton.text( thisButton.text() + '...' )
+	function this__enableButton() {
+		thisButton.attr('disabled', false)
+		var txt = thisButton.text()
+		thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
+	}
+
+	var lastReportOptions = new Promise(function (resolve) {
+		fetchLastReports() // TODO: TEST remote `mock__`
+		.then(function (items) {
+			var options = {};
+			items.forEach(function (item) {
+				var label = "Nr " + item.id + ": " + item.adnotacje + " ";
+				var total = 0;
+				switch (pageType) {
+					case 'pracownicy':  total = parseInt(item.totalPracownicy); break;
+					case 'kontrahenci': total = parseInt(item.totalKontrahenci); break;
+				}
+				label += ( total > 0 ? "(" + total + ")" : "brak");
+				options['raport-'+item.id] = label;
+			});
+			resolve(options);
+		})
+		.catch(function (e) {
+			swal.showValidationError(''+e)
+			swal.hideLoading();
+			resolve();
+		})
+	});
+
+	swal({
+		title: "Dodaj " + ('pracownicy' === pageType ? "praconików" : "kontrahentów") + " do analizy",
+		showCancelButton: true,
+		cancelButtonText: "Anuluj",
+		showConfirmButton: true,
+		confirmButtonText: "Wybierz",
+		focusCancel: true,
+		width: 600,
+		input: 'select',
+		inputOptions: lastReportOptions,
+		inputClass: "form-control input-lg",
+		preConfirm: function (selected) {
+			var id = parseInt(selected.substr('raport-'.length));
+			swal.showLoading();
+			if ('pracownicy' === pageType) {
+				return new Promise(function (resolve) {
+					fetchPracownicyIdsByReport(id)
+					.then(function (ids) {
+						updateListIdBiAuditReaport('PRACOWNICY', ids.map(function (id) {
+							return parseInt(id)
+						}))
+						ids.forEach(function (id) {
+							jQuery('#body-pracownicy').find('input[name="prID[]"][value="'+id+'"]').each(function (idx, inputNode) {
+								inputNode.checked = true;
+							})
+						})
+						updateCountItemCheckedByType('pracownicy');
+						p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+ids.length+" pracowników" })
+						resolve();
+					})
+					.catch(function (e) {
+						swal.showValidationError(''+e)
+						swal.hideLoading();
+						resolve();
+					});
+				});
+			} else if ('kontrahenci' === pageType) {
+				return new Promise(function (resolve) {
+					fetchKontrahenciIdsByReport(id)
+					.then(function (ids) {
+						updateListIdBiAuditReaport('KONTRAHENCI', ids.map(function (id) {
+							return parseInt(id)
+						}))
+						ids.forEach(function (id) {
+							jQuery('#body-kontrahenci').find('input[name="kontrID[]"][value="'+id+'"]').each(function (idx, inputNode) {
+								inputNode.checked = true;
+							})
+						})
+						updateCountItemCheckedByType('kontrahenci');
+						p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+ids.length+" kontrahentów" })
+						resolve();
+					})
+					.catch(function (e) {
+						swal.showValidationError(''+e)
+						swal.hideLoading();
+						resolve();
+					});
+				});
+			} else return true;
+		},
+		// inputValidator: (value) => {
+		// 	return !value && 'Proszę wybrać raport'
+		// }
+		// html: '<p>Ostatnie raporty:</p>' + '<ul id="' + uniqHtmlId + '"></ul></p>',
+	}).then(function (selected) {
+		this__enableButton();
+	}).catch(function (e) {
+		this__enableButton();
+	})
+}
+
+
+$(document).ready(function(){
+	DBG && console.warn('DBG:: SET window[STORE_NAME]', { store: window[STORE_NAME], STORE_NAME: STORE_NAME, globalRaportStore })
+
+	ReactDOM.render(
+		h(P5UI__Anton1Header, {
+			store: globalRaportStore
+		}),
+		document.getElementById('bi_audit_header')
+	);
+
+	rootChangeForm();
+	updateTopCounters();
+
+	var unsubscribe = globalRaportStore.subscribe(function () {
+		// TODO: fetch data from globalRaportStore.getState()
+		// var defaultState = global[STORE_NAME + '__defaults']();
+	})
+
+
+	$(window).on('hashchange', function() {
+		DBG && console.warn("$(window).on('hashchange', ...")
+
+		rootChangeForm();
+		updateTopCounters();
+		hideMoreRecordFunctionsPopover()
+	});
+
+});
+
+global.hideMoreRecordFunctionsPopover = function() {
+	if (RECORD_MORE_FUNCTIONS_OPENED_NODE) jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
+}
+global.pracownicyLoadMoreRecordFunctions = function(event, node, rowPK) {
+	return loadMoreRecordFunctions(event, node, rowPK, "default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY")
+}
+global.kontrahenciLoadMoreRecordFunctions = function(event, node, rowPK) {
+	return loadMoreRecordFunctions(event, node, rowPK, "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI")
+}
+global.removeFiltersPracownicy = removeFiltersPracownicy;
+global.removeFiltersKontrahenci = removeFiltersKontrahenci;
+global.onChangeFiltersPracownicy = onChangeFiltersPracownicy;
+global.onKeypressFiltersPracownicy = onKeypressFiltersPracownicy;
+global.onChangeFiltersKontrahenci = onChangeFiltersKontrahenci;
+global.onKeypressFiltersKontrahenci = onKeypressFiltersKontrahenci;
+
+global.checkAll = checkAll;
+global.checkedChoiseItems = checkedChoiseItems;
+global.catchEventCheckbox = catchEventCheckbox;
+global.clearSelectedCheckbox = clearSelectedCheckbox;
+global.getNameGroupById = getNameGroupById;
+global.createGroupPracownicy = createGroupPracownicy;
+global.createGroupKontrahenci = createGroupKontrahenci;
+global.selectPage = selectPage;
+global.detectChoiseFilter = detectChoiseFilter;
+
+global.updateListIdBiAuditReaport = updateListIdBiAuditReaport;
+global.deleteListIdBiAuditReaport = deleteListIdBiAuditReaport;
+
+global.urlFetchPracownicy = urlFetchPracownicy;
+global.urlFetchKontrahenci = urlFetchKontrahenci;
+global.getAddressData = getAddressData;
+
+global.Pagination = Pagination;
+global.todo__fetchRaport = todo__fetchRaport;
+
+global.setItemLocalStorage = setItemLocalStorage;
+global.getItemLocalStorage = getItemLocalStorage;
+global.deleteItemLocalStorage = deleteItemLocalStorage;
+global.removeItemInArray = removeItemInArray;
+global.removeItemArrayInArray = removeItemArrayInArray;
+
+global.addPracownikToGroup = addPracownikToGroup;
+global.addPracownikAllToGroup = addPracownikAllToGroup;
+global.addKontrahenciToGroup = addKontrahenciToGroup;
+global.addKontrahenciAllToGroup = addKontrahenciAllToGroup;
+global.createPracownikAjax = createPracownikAjax;
+global.createKontrahentAjax = createKontrahentAjax;
+global.removePracownikFromGroup = removePracownikFromGroup;
+global.removeKontrahenciFromGroup = removeKontrahenciFromGroup;
+
+global.showViewUploadFile = showViewUploadFile;
+global.parseCsvFile = parseCsvFile;
+global.clearListLocalStorageByType = clearListLocalStorageByType;
+
+// message
+global.messageCriticalSearchData = 'Krytyczne wielkości danych do przeszukania. Optymalna wartość głębokość szukania powiaząń to: 6';

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff