report.class.php 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. <?php
  2. if (!defined('IN_ONLINE')) {
  3. exit('Access Denied');
  4. }
  5. /**
  6. * Description of operation_log
  7. *
  8. * @author Administrator
  9. */
  10. class report {
  11. private static $_report;
  12. public static function getInstance() {
  13. if (!self::$_report) {
  14. $c = __CLASS__;
  15. self::$_report = new $c;
  16. }
  17. return self::$_report;
  18. }
  19. /**
  20. * report 配置
  21. */
  22. public function report_config(){
  23. $operate = utils::_get('operate');
  24. $operate = strtolower($operate);
  25. if ($operate == "parity_id"){
  26. //search parity id
  27. if(_isCustomerLogin()){
  28. //$ocean_contact_id = _getContactIDHandNew($_SESSION["ONLINE_USER"], 'public');
  29. $ocean_contact_id = _getCompanyContactHandNew($_SESSION["ONLINE_USER"]);
  30. $air_contact_id = _getAirContactID('public');
  31. $all_id = "ALL;".$ocean_contact_id;
  32. if (utils::endWith($ocean_contact_id,";")){
  33. $all_id .=$air_contact_id;
  34. } else {
  35. $all_id .=";".$air_contact_id;
  36. }
  37. $arr = explode(';', $all_id);
  38. $unique_arr = array_unique($arr);
  39. }else{
  40. $unique_arr= ['ALL'];
  41. }
  42. $option = array();
  43. foreach($unique_arr as $temp){
  44. $option[] =array("label"=>$temp,"value"=>$temp);
  45. }
  46. common::echo_json_encode(200, $option);
  47. exit();
  48. }
  49. /**
  50. * report的配置查询,
  51. */
  52. if ($operate == "search"){
  53. $cp = common::check_input($_POST ['cp']); //current_page
  54. $ps = common::check_input($_POST ['ps']); //ps
  55. if (empty($ps))
  56. $ps = 100;
  57. if (empty($cp))
  58. $cp = 1;
  59. $sqlWhere = "1=1";
  60. $text_search = $_POST['text_search'];
  61. if (!empty($text_search)){
  62. $sqlWhere .= " and (lower(name) like '%".strtolower($text_search)."%')";
  63. }
  64. if(!empty($_POST['application_scope'])){
  65. $pplication_scope = $_POST['application_scope'] =='all' ? "All Users" : "Specific Users";
  66. $sqlWhere .= " and access_type ='". common::check_input($pplication_scope)."'";
  67. }
  68. if(!empty($_POST['is_active'])){
  69. if($_POST['is_active'] == 'true'){
  70. $sqlWhere .= " and is_active = true";
  71. }else{
  72. $sqlWhere .= " and is_active = false";
  73. }
  74. }
  75. if(!empty($_POST['party_id'])){
  76. if($_POST['party_id'] != 'ALL'){
  77. $sqlWhere .= " and '".common::check_input($_POST['party_id'])."' = any(party_ids)";
  78. }
  79. }
  80. $sqlWhere_party_id = '';
  81. $sqlWhere_group_name = '';
  82. if(_isCustomerLogin()){
  83. $ocean_contact_id = _getCompanyContactHandNew($_SESSION["ONLINE_USER"]);
  84. $air_contact_id = _getAirContactID('public');
  85. $all_id = $ocean_contact_id;
  86. if (utils::endWith($ocean_contact_id,";")){
  87. $all_id .=$air_contact_id;
  88. } else {
  89. $all_id .=";".$air_contact_id;
  90. }
  91. $all_id = strtolower($all_id);
  92. $unique_arr = explode(';', $all_id);
  93. //构建安全的数组字面量用于 PostgreSQL 的 && 交集判断
  94. // 转义每个 ID 防注入
  95. $escaped_ids = array();
  96. foreach($unique_arr as $id){
  97. $id = trim($id);
  98. if (empty($id))
  99. continue;
  100. $escaped_ids[] = "'" .common::check_input($id) . "'";
  101. }
  102. if(empty($escaped_ids)){
  103. $escaped_ids[] = "'" .common::check_input('default_value_that_does_not_exist') . "'";
  104. }
  105. $array_str = 'ARRAY[' . implode(',', $escaped_ids) . ']';
  106. $sqlWhere_party_id = " OR party_ids && $array_str ";
  107. //Group Name 判断
  108. $company = _getCompanyHandNew($_SESSION["ONLINE_USER"],'public');
  109. //$company = strtolower($company);
  110. $aa = explode(";", $company);
  111. $escaped_company = array();
  112. foreach ($aa as $value) {
  113. $value = trim($value);
  114. if (empty($value))
  115. continue;
  116. $escaped_company[] = "'" . common::check_input($value) . "'";
  117. }
  118. if(empty($escaped_company)){
  119. $escaped_company[] = "'" . common::check_input('default_value_that_does_not_exist') . "'";
  120. }
  121. $array_str = 'ARRAY[' . implode(',', $escaped_company) . ']';
  122. $sqlWhere_group_name = " OR group_names && $array_str";
  123. $systemAccountsqlWhere = " OR '".common::check_input(_getLoginName())."' = any(system_account)";
  124. $sqlWhere .= " and ( access_type = 'All Users' ".$sqlWhere_party_id . " ".$sqlWhere_group_name ." ".$systemAccountsqlWhere .")";
  125. } else {
  126. //$systemAccountsqlWhere = " OR system_account IS NULL OR array_length(system_account, 1) = 0 OR '".common::check_input(_getLoginName())."' = any(system_account)";
  127. //$sqlWhere .= " and ( 1<>1 ".$systemAccountsqlWhere .")";
  128. }
  129. $rc = $_POST ['rc'];
  130. if ($rc == -1) {
  131. $sql = "select count(*) from public.kln_report_template where " .$sqlWhere;
  132. $rc = common::excuteOneSql($sql);
  133. }
  134. $tp = ceil($rc / $ps);
  135. if ($rc > 0) {
  136. $sql = "select * from public.kln_report_template where " .$sqlWhere;
  137. $sql .= " order by id desc limit " . $ps . " offset " . ($cp - 1) * $ps;
  138. $rs = common::excuteListSql($sql);
  139. $arrTmp = array('searchData' => $rs,
  140. 'isDelete' =>_isVipReportAdmin(_getLoginName()),
  141. 'rc' => intval($rc),
  142. 'ps' => intval($ps),
  143. 'cp' => intval($cp),
  144. 'tp' => intval($tp));
  145. common::echo_json_encode(200,$arrTmp);
  146. exit();
  147. }else{
  148. $arrTmp = array('searchData' =>array(),
  149. 'isDelete' =>_isVipReportAdmin(_getLoginName()),
  150. 'rc' => intval($rc),
  151. 'ps' => intval($ps),
  152. 'cp' => intval($cp),
  153. 'tp' => intval($tp));
  154. common::echo_json_encode(200, $arrTmp);
  155. exit();
  156. }
  157. }
  158. if ($operate == "add"){
  159. $serial_no = $_REQUEST['serial_no'];
  160. if(!empty($serial_no)){
  161. //代表编辑
  162. $reportMain = common::excuteObjectSql("select *,
  163. array_to_json(party_ids) as party_ids_json,
  164. array_to_json(group_names) as group_names_json,
  165. array_to_json(system_account) as system_account_json
  166. from kln_report_template where serial_no = '$serial_no'");
  167. $reportFields = array();
  168. $reportField = common::excuteListSql("select
  169. field_id as ids,
  170. field_level as \"fieldLevel\",
  171. field_type as \"fieldType\",
  172. field_group_name as \"groupName\",
  173. field_db as field,
  174. field_display_name as title,
  175. field_display_name_user as \"displayName\",
  176. data_type as \"dataType\",
  177. custom_fixed_value as value,
  178. is_filter_enabled as \"isFilter\",
  179. is_sort_enabled as \"isSort\",
  180. field_data_mapping as mapping,
  181. (select is_field_data_mapping from public.kln_report_field where display_name = field_display_name limit 1) as \"isFieldDataMapping\"
  182. from kln_report_field_config where template_serial_no = '$serial_no' order by id");
  183. foreach($reportField as $_reportField){
  184. $_reportField['isFilter'] = $_reportField['isFilter'] == 't' ? true : false;
  185. $_reportField['isSort'] = $_reportField['isSort'] == 't' ? true : false;
  186. $_reportField['mapping'] = empty($_reportField['mapping'])? array(): json_decode($_reportField['mapping'],true);
  187. $reportFields[] = $_reportField;
  188. }
  189. $reportAccess = array("type"=>$reportMain['access_type'],
  190. "partyId"=>json_decode($reportMain['party_ids_json'],true),
  191. "groupName"=>json_decode($reportMain['group_names_json'],true),
  192. "systemAccount"=>json_decode($reportMain['system_account_json'],true));
  193. $data = array("reportName"=>$reportMain['name'],"reportLevel"=>$reportMain['level'],"reportDescription"=>$reportMain['description'],
  194. "reportFields"=>$reportFields,"reportAccess"=>$reportAccess);
  195. }else{
  196. $data = array();
  197. }
  198. common::echo_json_encode(200,$data);
  199. exit();
  200. }
  201. if ($operate == "report_field_load"){
  202. column::getInstance()->settingDisplayForVIPReport();
  203. }
  204. if ($operate == "save"){
  205. $serial_no = $_POST['serial_no'];
  206. $name = common::check_input($_POST['report_name']);
  207. $description = common::check_input($_POST['report_description']);
  208. $level = common::check_input($_POST['report_level']);
  209. $access_type = common::check_input($_POST['access_type']);
  210. //Specific Roles 和 对应有值的时候,才取,否则取空数组更新
  211. $party_ids = $access_type == "Specific Roles" && !empty($_POST['party_ids']) ? $_POST['party_ids'] : array();
  212. $group_names = $access_type == "Specific Roles" && !empty($_POST['group_names']) ? $_POST['group_names'] : array();
  213. $system_account = $access_type == "Specific Roles" && !empty($_POST['system_account']) ? $_POST['system_account'] : array();
  214. //单独处理字段id
  215. $fieldsList = $_POST['fieldsList'];
  216. $field_ids = array();
  217. foreach($fieldsList as $_fieldsList){
  218. if (!empty($_fieldsList['ids'])){
  219. $field_ids[] = $_fieldsList['ids'];
  220. }
  221. }
  222. $report_sql_data = common::excuteObjectSql("select sql,count_sql from public.kln_report_sql_manage where lower(level) = '".strtolower($level)."'");
  223. $sql = "";
  224. if (!empty($serial_no)){
  225. $updateSqlSet = " report_sql = '".common::check_input($report_sql_data['sql'])."',
  226. count_sql = '".common::check_input($report_sql_data['count_sql'])."',
  227. modify_by = '"._getLoginName()."',update_time = now()";
  228. if (!empty($name)) {
  229. $updateSqlSet.= ", name = '$name' ";
  230. }
  231. if (!empty($description)) {
  232. $updateSqlSet.= ", description = '$description' ";
  233. }
  234. if (!empty($level)) {
  235. $updateSqlSet.= ", level = '$level' ";
  236. }
  237. if (!empty($access_type)) {
  238. $updateSqlSet.= ", access_type = '$access_type' ";
  239. }
  240. $party_ids_filed= common::toPgTextArrayLiteral($party_ids);
  241. $updateSqlSet.= ", party_ids = $party_ids_filed";
  242. $group_names_filed = common::toPgTextArrayLiteral($group_names);
  243. $updateSqlSet.= ", group_names = $group_names_filed";
  244. $ids_filed = common::toPgTextArrayLiteral($field_ids);
  245. $updateSqlSet.= ", field_ids = $ids_filed";
  246. if (!empty($system_account)) {
  247. $system_account_filed = common::toPgTextArrayLiteral($system_account);
  248. $updateSqlSet.= ", system_account = $system_account_filed";
  249. }
  250. //代表update
  251. $sql .= "update public.kln_report_template set ".$updateSqlSet."
  252. where serial_no = '$serial_no';";
  253. } else {
  254. $party_ids_filed = "NULL";
  255. if (!empty($party_ids)) {
  256. $party_ids_filed= common::toPgTextArrayLiteral($party_ids);
  257. }
  258. $group_names_filed = "NULL";
  259. if (!empty($group_names)) {
  260. $group_names_filed = common::toPgTextArrayLiteral($group_names);
  261. }
  262. $ids_filed = "NULL";
  263. if (!empty($field_ids)) {
  264. $ids_filed = common::toPgTextArrayLiteral($field_ids);
  265. }
  266. $system_account_filed = "NULL";
  267. if (!empty($system_account)) {
  268. $system_account_filed = common::toPgTextArrayLiteral($system_account);
  269. }
  270. $serial_no = common::uuid();
  271. $sql .= "INSERT INTO public.kln_report_template(
  272. serial_no,name, description, level, field_ids, access_type, report_sql,count_sql,
  273. party_ids, group_names, system_account, create_by, created_time, modify_by, update_time )
  274. VALUES ('$serial_no','$name', '$description', '$level', $ids_filed, '$access_type',
  275. '".common::check_input($report_sql_data['sql'])."','".common::check_input($report_sql_data['count_sql'])."',
  276. $party_ids_filed, $group_names_filed ,$system_account_filed,'"._getLoginName()."', now(), '"._getLoginName()."', now());";
  277. }
  278. //先删除,后添加
  279. $sql .= "delete from public.kln_report_field_config where template_serial_no = '$serial_no';";
  280. foreach($fieldsList as $key =>$_tempFieldsList){
  281. $_field_id = empty($_tempFieldsList['ids'])? "NULL": $_tempFieldsList['ids'];
  282. $_field_level = common::check_input($_tempFieldsList['fieldLevel']);
  283. $_field_type = common::check_input($_tempFieldsList['fieldType']);
  284. $_field_group_name = common::check_input($_tempFieldsList['groupName']);
  285. $_field_db = common::check_input($_tempFieldsList['field']);
  286. $_field_code = common::check_input($_tempFieldsList['title']);
  287. $_display_name = common::check_input($_tempFieldsList['displayName']);
  288. $_data_type = common::check_input($_tempFieldsList['dataType']);
  289. $_value_type = $_field_type == "System" ? "" : (empty($_tempFieldsList['value']) ? "Blank" :"Fixed Value");
  290. $_fixed_value = common::check_input($_tempFieldsList['value']);
  291. $_field_data_mapping = empty($_tempFieldsList['mapping'])? "NULL" : "'".json_encode($_tempFieldsList['mapping'])."'";
  292. //这两个不能配置查询和过滤
  293. if($_field_group_name == 'Container Status' || $_field_group_name == 'Milestone'
  294. ||$_field_code == 'Other reference No.' || $_field_code == 'Shipper Zip Code' || $_field_code == 'Consignee Zip Code' ){
  295. $_is_filter_enabled = "false";
  296. } else {
  297. $_is_filter_enabled = $_tempFieldsList['isFilter'];
  298. }
  299. $_is_sort_enabled = $_tempFieldsList['isSort'];
  300. $sql .= "INSERT INTO public.kln_report_field_config(
  301. template_serial_no, field_id, field_level, field_type, field_db, field_group_name,
  302. field_display_name, field_display_name_user, data_type, custom_value_type,
  303. custom_fixed_value, is_filter_enabled, is_sort_enabled, created_time,field_data_mapping)
  304. VALUES ('$serial_no', $_field_id, '$_field_level', '$_field_type', '$_field_db', '$_field_group_name',
  305. '$_field_code', '$_display_name', '$_data_type', '$_value_type',
  306. '$_fixed_value', '$_is_filter_enabled', '$_is_sort_enabled',now(),$_field_data_mapping);";
  307. }
  308. if (!empty($sql)){
  309. common::excuteUpdateSql($sql);
  310. $data = array("msg" =>"success");
  311. }
  312. common::echo_json_encode(200,$data);
  313. exit();
  314. }
  315. if ($operate == "active"){
  316. $serial_no =$_POST['serial_no'];
  317. $is_active = $_POST['is_active'];
  318. $sql = "update public.kln_report_template set is_active = '$is_active' where serial_no = '$serial_no';";
  319. common::excuteUpdateSql($sql);
  320. $data = array("msg" =>"success");
  321. common::echo_json_encode(200,$data);
  322. exit();
  323. }
  324. if ($operate == "delete"){
  325. $serial_no =$_POST['serial_no'];
  326. $sql = "delete from public.kln_report_template where serial_no = '$serial_no';";
  327. $sql .= "delete from public.kln_report_field_config where template_serial_no = '$serial_no';";
  328. common::excuteUpdateSql($sql);
  329. $data = array("msg" =>"success");
  330. common::echo_json_encode(200,$data);
  331. exit();
  332. }
  333. }
  334. /**
  335. * shipment_status_report
  336. */
  337. public function shipment_status_report(){
  338. $operate = utils::_get('operate');
  339. $operate = strtolower($operate);
  340. if ($operate == "report_search") {
  341. $cp = common::check_input($_POST ['cp']); //current_page
  342. $ps = common::check_input($_POST ['ps']); //ps
  343. if (empty($ps))
  344. $ps = 100;
  345. if (empty($cp))
  346. $cp = 1;
  347. $sqlWhere = "1=1 and is_active = true";
  348. $text_search = $_POST['text_search'];
  349. if (!empty($text_search)){
  350. $sqlWhere .= " and (lower(name) like '%".strtolower($text_search)."%')";
  351. }
  352. $sqlWhere_party_id = '';
  353. $sqlWhere_group_name = '';
  354. if(_isCustomerLogin()){
  355. $ocean_contact_id = _getCompanyContactHandNew($_SESSION["ONLINE_USER"]);
  356. $air_contact_id = _getAirContactID('public');
  357. $all_id = $ocean_contact_id;
  358. if (utils::endWith($ocean_contact_id,";")){
  359. $all_id .=$air_contact_id;
  360. } else {
  361. $all_id .=";".$air_contact_id;
  362. }
  363. $all_id = strtolower($all_id);
  364. $unique_arr = explode(';', $all_id);
  365. //构建安全的数组字面量用于 PostgreSQL 的 && 交集判断
  366. // 转义每个 ID 防注入
  367. $escaped_ids = array();
  368. foreach($unique_arr as $id){
  369. $id = trim($id);
  370. if (empty($id))
  371. continue;
  372. $escaped_ids[] = "'" .common::check_input($id) . "'";
  373. }
  374. if(empty($escaped_ids)){
  375. $escaped_ids[] = "'" .common::check_input('default_value_that_does_not_exist') . "'";
  376. }
  377. $array_str = 'ARRAY[' . implode(',', $escaped_ids) . ']';
  378. $sqlWhere_party_id = " OR party_ids && $array_str ";
  379. //Group Name 判断
  380. $company = _getCompanyHandNew($_SESSION["ONLINE_USER"],'public');
  381. //$company = strtolower($company);
  382. $aa = explode(";", $company);
  383. $escaped_company = array();
  384. foreach ($aa as $value) {
  385. $value = trim($value);
  386. if (empty($value))
  387. continue;
  388. $escaped_company[] = "'" . common::check_input($value) . "'";
  389. }
  390. if(empty($escaped_company)){
  391. $escaped_company[] = "'" . common::check_input('default_value_that_does_not_exist') . "'";
  392. }
  393. $array_str = 'ARRAY[' . implode(',', $escaped_company) . ']';
  394. $sqlWhere_group_name = " OR group_names && $array_str";
  395. $systemAccountsqlWhere = " OR '".common::check_input(_getLoginName())."' = any(system_account)";
  396. $sqlWhere .= " and ( access_type = 'All Users' ".$sqlWhere_party_id . " ".$sqlWhere_group_name ." ".$systemAccountsqlWhere .")";
  397. } else {
  398. //$systemAccountsqlWhere = " OR system_account IS NULL OR array_length(system_account, 1) = 0 OR '".common::check_input(_getLoginName())."' = any(system_account)";
  399. //$sqlWhere .= " and ( 1<>1 ".$systemAccountsqlWhere .")";
  400. }
  401. $rc = $_POST ['rc'];
  402. if ($rc == - 1) {
  403. $sql = "select count(*) from public.kln_report_template where " .$sqlWhere;
  404. $rc = common::excuteOneSql($sql);
  405. error_log($sql);
  406. }
  407. $tp = ceil($rc / $ps);
  408. if ($rc > 0) {
  409. $sql = "select serial_no,name,description from public.kln_report_template where " .$sqlWhere;
  410. $sql .= " order by id desc limit " . $ps . " offset " . ($cp - 1) * $ps;
  411. $rs = common::excuteListSql($sql);
  412. $arrTmp = array('searchData' => $rs,
  413. 'rc' => intval($rc),
  414. 'ps' => intval($ps),
  415. 'cp' => intval($cp),
  416. 'tp' => intval($tp));
  417. common::echo_json_encode(200,$arrTmp);
  418. exit();
  419. }else{
  420. $arrTmp = array('searchData' => array(),
  421. 'rc' => intval($rc),
  422. 'ps' => intval($ps),
  423. 'cp' => intval($cp),
  424. 'tp' => intval($tp));
  425. common::echo_json_encode(200, $arrTmp);
  426. exit();
  427. }
  428. }
  429. if ($operate == "report_detail") {
  430. $serial_no = common::check_input($_POST ['serial_no']);
  431. $dataReturn = array();
  432. $tableColumns = array();
  433. $filtersList = array();
  434. $sortByOptions = array();
  435. $mappingConfig = array();
  436. $CustomFiled = "";
  437. $reportFiled = common::excuteListSql("select * from public.kln_report_field_config where template_serial_no = '".$serial_no."'
  438. and is_enabled = true order by id ");
  439. foreach($reportFiled as $filed){
  440. if($filed['is_filter_enabled'] == 't'){
  441. $field_display_name = $filed['field_display_name'];
  442. $field_display_name = strtolower($field_display_name);
  443. $field_display_name = preg_replace('/[^a-z0-9]+/', '_', $field_display_name); // 非字母数字 → _
  444. $field_display_name = trim($field_display_name, '_');
  445. $realSelect = common::getSelectedArray($filed['field_display_name']);
  446. $data_type = $filed['data_type'];
  447. if(!empty($realSelect)){
  448. $data_type = 'select';
  449. }
  450. $filtersList[] = array(
  451. "label"=>$filed['field_display_name_user'],
  452. "field"=>$field_display_name,
  453. "field_real"=>$filed['field_display_name'],
  454. "data_type"=>$data_type,
  455. "value"=>'',"options"=>$realSelect);
  456. }
  457. if($filed['is_sort_enabled'] == 't'){
  458. $sortByOptions[] = $filed['field_db'];
  459. }
  460. //用户自定义字段
  461. if($filed['field_type'] == 'Custom'){
  462. $CustomFiled .= " , '".$filed['custom_fixed_value']."' AS \"".$filed['field_display_name_user']."\"";
  463. }
  464. if(!empty($filed['field_data_mapping'])){
  465. $mappingConfig[$filed['field_display_name']] =json_decode($filed['field_data_mapping'],true);
  466. }
  467. $temp = array();
  468. $temp['field'] = $filed['field_display_name'];
  469. $temp['title'] = $filed['field_display_name_user'];
  470. $temp['type'] = $filed['field_db'] == "Status" ? "status" : "normal";
  471. $temp['formatter'] = "";
  472. $tableColumns[] = $temp;
  473. }
  474. $dataReturn['tableColumns'] = $tableColumns;
  475. $dataReturn['filtersList'] = $filtersList;
  476. if(!empty($sortByOptions)){
  477. $dataReturn['sortBy'] = array("field"=>$sortByOptions[0],"options"=>$sortByOptions,"order"=>"asc");
  478. }else{
  479. $dataReturn['sortBy'] = array("field"=>"","options"=>[],"order"=>"asc");
  480. }
  481. $reportFiled = common::excuteObjectSql("select name,report_sql,count_sql,level from public.kln_report_template where serial_no = '".$serial_no."'");
  482. $sqlManage = common::excuteObjectSql("select sql,count_sql,level from public.kln_report_sql_manage where lower(level) = '".strtolower($reportFiled['level'])."'");
  483. $report_sql = $sqlManage["sql"];
  484. //$count_sql = $sqlManage["count_sql"];
  485. $filterSQLArr = $this->returnFilterSql_v1($filtersList);
  486. $count_sql = common::buildCountSql($filterSQLArr['filterFields'],$reportFiled['level']);
  487. //return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN);
  488. $count_sql = str_replace('<{klnOceanSearchKLN}>', $filterSQLArr['klnOceanSearchKLN'], $count_sql);
  489. $count_sql = str_replace('<{ocItemSearchKLN}>', $filterSQLArr['ocItemSearchKLN'], $count_sql);
  490. $count_sql = str_replace('<{vvSearchKLN}>', $filterSQLArr['vvSearchKLN'], $count_sql);
  491. $count_sql = str_replace('<{orderby}>', "", $count_sql);
  492. error_log($reportFiled['name'].": report_detail_count, ".$count_sql);
  493. $report_sql = str_replace('<{klnOceanSearchKLN}>', $filterSQLArr['klnOceanSearchKLN'], $report_sql);
  494. $report_sql = str_replace('<{ocItemSearchKLN}>', $filterSQLArr['ocItemSearchKLN'], $report_sql);
  495. $report_sql = str_replace('<{CustomFiled}>', $CustomFiled, $report_sql);
  496. $report_sql = str_replace('<{vvSearchKLN}>', $filterSQLArr['vvSearchKLN'], $report_sql);
  497. $report_sql = str_replace('<{orderby}>', $this->returnSortBySql(), $report_sql);
  498. //查询data
  499. $cp = common::check_input($_POST ['cp']); //current_page
  500. $ps = common::check_input($_POST ['ps']); //ps
  501. if (empty($ps))
  502. $ps = 10;
  503. if (empty($cp))
  504. $cp = 1;
  505. $rc = $_POST ['rc'];
  506. if ($rc == -1) {
  507. $rc = common::excuteOneSql($count_sql);
  508. }
  509. $tp = ceil($rc / $ps);
  510. if ($rc > 0) {
  511. $tmp_search_without_limit = $report_sql;
  512. $report_sql .= " limit " . $ps . " offset " . ($cp - 1) * $ps;
  513. error_log($reportFiled['name'].": report_detail_search, ".$report_sql);
  514. $rs = common::excuteListSql($report_sql);
  515. // 第一步:预处理 mapping,转为高效查找的哈希表
  516. $valueMapByField = [];
  517. foreach ($mappingConfig as $fieldName => $mapList) {
  518. $valueMapByField[$fieldName] = [];
  519. foreach ($mapList as $item) {
  520. // 将 system 值作为 key,converted 作为 value
  521. $valueMapByField[$fieldName][(string)$item['system']] = $item['converted'];
  522. }
  523. }
  524. // 第二步:遍历结果集,逐行、逐字段替换值
  525. $convertedRs = [];
  526. foreach ($rs as $row) {
  527. $newRow = [];
  528. foreach ($row as $field => $value) {
  529. // 如果该字段有配置映射,并且当前值在映射中,则替换
  530. if (isset($valueMapByField[$field]) && isset($valueMapByField[$field][(string)$value])) {
  531. $newRow[$field] = $valueMapByField[$field][(string)$value];
  532. } else {
  533. // 否则保留原值
  534. $newRow[$field] = $value;
  535. }
  536. }
  537. $convertedRs[] = $newRow;
  538. }
  539. $arrTmp = array('searchData' => $convertedRs,
  540. 'rc' => intval($rc),
  541. 'ps' => intval($ps),
  542. 'cp' => intval($cp),
  543. 'tp' => intval($tp));
  544. }else{
  545. $arrTmp = array('searchData' => array());
  546. }
  547. $dataReturn['tableData'] = $arrTmp;
  548. $dataReturn['tmp_search'] = common::deCode($tmp_search_without_limit, 'E');
  549. $dataReturn['tmp_mapping'] = common::deCode(json_encode($mappingConfig), 'E');
  550. $dataReturn['reportName'] = $reportFiled['name'];
  551. common::echo_json_encode(200, $dataReturn);
  552. exit();
  553. }
  554. /*
  555. * export excel
  556. */
  557. if ($operate == "excel") {
  558. $sql = common::deCode($_POST['tmp_search'], 'D');
  559. $tmp_mapping = common::deCode($_POST['tmp_mapping'], 'D');
  560. $mappingConfig = json_decode($tmp_mapping,true);
  561. if(!empty($sql)){
  562. $rs = common::excuteListSql($sql);
  563. }
  564. // 第一步:预处理 mapping,转为高效查找的哈希表
  565. $valueMapByField = [];
  566. foreach ($mappingConfig as $fieldName => $mapList) {
  567. $valueMapByField[$fieldName] = [];
  568. foreach ($mapList as $item) {
  569. // 将 system 值作为 key,converted 作为 value
  570. $valueMapByField[$fieldName][(string)$item['system']] = $item['converted'];
  571. }
  572. }
  573. // 第二步:遍历结果集,逐行、逐字段替换值
  574. $convertedRs = [];
  575. foreach ($rs as $row) {
  576. $newRow = [];
  577. foreach ($row as $field => $value) {
  578. //去除null
  579. if(empty($value[$field]) || $value[$field] == null){
  580. $value[$field] = "";
  581. }
  582. // 如果该字段有配置映射,并且当前值在映射中,则替换
  583. if (isset($valueMapByField[$field]) && isset($valueMapByField[$field][(string)$value])) {
  584. $newRow[$field] = $valueMapByField[$field][(string)$value];
  585. } else {
  586. // 否则保留原值
  587. $newRow[$field] = $value;
  588. }
  589. }
  590. $convertedRs[] = $newRow;
  591. }
  592. common::echo_json_encode(200,array("msg"=>"success","Data" => $convertedRs));
  593. exit;
  594. }
  595. if ($operate == "manage_fileds") {
  596. $serial_no = common::check_input($_POST ['serial_no']);
  597. $reportFiled = common::excuteListSql("select * from public.kln_report_field_config
  598. where template_serial_no = '".$serial_no."' order by id ");
  599. $data = array();
  600. foreach($reportFiled as $_reportFiled){
  601. $_reportFiled['is_filter_enabled'] = $_reportFiled['is_filter_enabled'] == 't' ? true : false;
  602. $_reportFiled['is_sort_enabled'] = $_reportFiled['is_sort_enabled'] == 't' ? true : false;
  603. $_reportFiled['is_enabled'] = $_reportFiled['is_enabled'] == 't' ? true : false;
  604. $data[] = $_reportFiled;
  605. }
  606. common::echo_json_encode(200,array("msg"=>"success","data" => $data));
  607. exit;
  608. }
  609. if ($operate == "manage_fileds_save") {
  610. $serial_no = common::check_input($_POST['serial_no']);
  611. $fieldsList = $_POST['fieldsList'];
  612. //先删除,后添加 因为不涉及系统配置字段,全部用kln_report_field_config 字段name
  613. $sql = "delete from public.kln_report_field_config where template_serial_no = '$serial_no';";
  614. foreach($fieldsList as $key =>$_tempFieldsList){
  615. $_field_id = empty($_tempFieldsList['field_id'])? "NULL": $_tempFieldsList['field_id'];
  616. $_field_level = common::check_input($_tempFieldsList['field_level']);
  617. $_field_type = common::check_input($_tempFieldsList['field_type']);
  618. $_field_group_name = common::check_input($_tempFieldsList['field_group_name']);
  619. $_field_db = common::check_input($_tempFieldsList['field_db']);
  620. $_field_code = common::check_input($_tempFieldsList['field_display_name']);
  621. $_display_name = common::check_input($_tempFieldsList['field_display_name_user']);
  622. $_data_type = common::check_input($_tempFieldsList['data_type']);
  623. $_value_type = common::check_input($_tempFieldsList['custom_value_type']);
  624. $_fixed_value = common::check_input($_tempFieldsList['custom_fixed_value']);
  625. $_is_filter_enabled = $_tempFieldsList['is_filter_enabled'];
  626. $_is_sort_enabled = $_tempFieldsList['is_sort_enabled'];
  627. $_is_enabled = $_tempFieldsList['is_enabled'];
  628. $sql .= "INSERT INTO public.kln_report_field_config(
  629. template_serial_no, field_id, field_level, field_type, field_db, field_group_name,
  630. field_display_name, field_display_name_user, data_type, custom_value_type,
  631. custom_fixed_value, is_filter_enabled, is_sort_enabled,is_enabled, created_time)
  632. VALUES ('$serial_no', $_field_id, '$_field_level', '$_field_type', '$_field_db', '$_field_group_name',
  633. '$_field_code', '$_display_name', '$_data_type', '$_value_type',
  634. '$_fixed_value', '$_is_filter_enabled', '$_is_sort_enabled','$_is_enabled',now());";
  635. }
  636. if (!empty($sql)){
  637. common::excuteUpdateSql($sql);
  638. $data = array("msg" =>"success");
  639. }
  640. common::echo_json_encode(200,array("msg"=>"success","Data" => ''));
  641. exit;
  642. }
  643. if ($operate == "report_schedule"){
  644. $serial_no = common::check_input($_POST ['serial_no']);
  645. $schedule = common::excuteObjectSql("select schedule_order_field,validity_type,valid_from,valid_to,
  646. data_reference_field,data_range_type,dynamic_start_offset,dynamic_end_offset,fixed_start_date,fixed_end_date,
  647. delivery_frequency,TO_CHAR(daily_time, 'HH24:MI') as daily_time,
  648. array_to_json(weekly_day) as weekly_days_json,TO_CHAR(weekly_time, 'HH24:MI') as weekly_time,
  649. array_to_json(monthly_day) as monthly_day_json,TO_CHAR(monthly_time, 'HH24:MI') as monthly_time,
  650. quarterly_month,quarterly_day,TO_CHAR(quarterly_time, 'HH24:MI') as quarterly_time,
  651. array_to_json(yearly_month) as yearly_month_json,yearly_day, TO_CHAR(yearly_time, 'HH24:MI') as yearly_time,
  652. timezone,email_recipients
  653. from public.kln_report_schedule where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."'");
  654. $schedule["weekly_days"] = json_decode($schedule["weekly_days"],true);
  655. $schedule["monthly_day"] = json_decode($schedule["monthly_day"],true);
  656. $schedule["yearly_month"] = json_decode($schedule["yearly_month"],true);
  657. //处理成VUE 识别的格式
  658. $data = array();
  659. $data["validityPeriod"] = array("type"=>$schedule["validity_type"],"startDate"=>$schedule["valid_from"],"endDate"=>$schedule["valid_to"]);
  660. if($schedule["data_range_type"] == "dynamic_rolling"){
  661. $data["timeRange"] = array("fieldType"=>$schedule["data_reference_field"],"type"=>$schedule["data_range_type"],
  662. "startDate"=>$schedule["dynamic_start_offset"],"endDate"=>$schedule["dynamic_end_offset"]);
  663. }else{
  664. $data["timeRange"] = array("fieldType"=>$schedule["data_reference_field"],"type"=>$schedule["data_range_type"],
  665. "startDate"=>$schedule["fixed_start_date"],"endDate"=>$schedule["fixed_end_date"]);
  666. }
  667. $time = "";
  668. $week = array();
  669. $month = array();
  670. $quarterMonth = "";
  671. $day = array();
  672. $delivery_frequency = $schedule["delivery_frequency"];
  673. if($delivery_frequency == 'daily'){
  674. $time = $schedule["daily_time"];
  675. }elseif($delivery_frequency == 'weekly'){
  676. $week= json_decode($schedule["weekly_days_json"],true);
  677. $time = $schedule["weekly_time"];
  678. }elseif($delivery_frequency == 'monthly'){
  679. $monthlyDay= json_decode($schedule["monthly_day_json"],true);
  680. $time = $schedule["monthly_time"];
  681. }elseif($delivery_frequency == 'quarterly'){
  682. $quarterMonth = $schedule["quarterly_month"];
  683. $day = $schedule["quarterly_day"];
  684. $time = $schedule["quarterly_time"];
  685. }elseif($delivery_frequency == 'yearly'){
  686. $month= json_decode($schedule["yearly_month_json"],true);
  687. $day = $schedule["yearly_day"];
  688. $time = $schedule["yearly_time"];
  689. }
  690. $data["deliveryFrequency"] = array("emailRecipients"=>$schedule["email_recipients"],"orderBy"=>$schedule["schedule_order_field"],
  691. "timezone"=>$schedule["timezone"],"deliveryFrequency"=>$schedule["delivery_frequency"],
  692. "scheduleDetails" =>array("time"=>$time,"week"=>$week,"month"=>$month,"monthlyDay" =>$monthlyDay,"quarterMonth"=>$quarterMonth,"day"=>$day));
  693. common::echo_json_encode(200,array("msg"=>"success","showData" => $data));
  694. exit;
  695. }
  696. if ($operate == "report_schedule_search"){
  697. $dataReturn = array();
  698. $serial_no = common::check_input($_POST ['serial_no']);
  699. $data_reference_field = strtolower(common::check_input($_POST ['fieldType']));
  700. $data_range_type = common::check_input($_POST ['type']);
  701. if($data_range_type == "dynamic_rolling"){
  702. $dynamic_start_offset = common::check_input($_POST ['startDate']);
  703. $dynamic_end_offset = common::check_input($_POST ['endDate']);
  704. $fixed_start_date = "null";
  705. $fixed_end_date = "null";
  706. }else{
  707. $dynamic_start_offset = "null";
  708. $dynamic_end_offset = "null";
  709. $fixed_start_date = common::check_input($_POST ['startDate']);
  710. $fixed_end_date = common::check_input($_POST ['endDate']);
  711. }
  712. $schedule_order_field = common::check_input($_POST ['orderBy']);
  713. //查询列名
  714. $tableColumns = array();
  715. $mappingConfig = array();
  716. $CustomFiled = "";
  717. $reportFiled = common::excuteListSql("select * from public.kln_report_field_config where template_serial_no = '".$serial_no."'
  718. and is_enabled = true order by id ");
  719. foreach($reportFiled as $filed){
  720. $temp = array();
  721. $temp['field'] = $filed['field_display_name'];
  722. $temp['title'] = $filed['field_display_name_user'];
  723. $temp['type'] = $filed['field_db'] == "Status" ? "status" : "normal";
  724. $temp['formatter'] = "";
  725. $tableColumns[] = $temp;
  726. //用户自定义字段
  727. if($filed['field_type'] == 'Custom'){
  728. $CustomFiled .= " , '".$filed['custom_fixed_value']."' AS \"".$filed['field_display_name_user']."\"";
  729. }
  730. if(!empty($filed['field_data_mapping'])){
  731. $mappingConfig[$filed['field_display_name']] =json_decode($filed['field_data_mapping'],true);
  732. }
  733. }
  734. $dataReturn['tableColumns'] = $tableColumns;
  735. $schedule_search = common::excuteObjectSql("select t.name,t.level,t.report_sql,t.count_sql from public.kln_report_template t where t.serial_no = '$serial_no'");
  736. $report_sql = $schedule_search["report_sql"];
  737. //$count_sql = $schedule_search["count_sql"];
  738. $filterFields = [];
  739. $count_sql = common::buildCountSql($filterFields,$schedule_search['level']);
  740. //$klnOceanSearchKLN = " where " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  741. $klnOceanSearchKLN = " where created_time > CURRENT_DATE - INTERVAL '1 years' and " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  742. $orderby = "";
  743. if(!empty($data_range_type)){
  744. //代表有用户设置的查询参数
  745. if($data_range_type == "dynamic_rolling"){
  746. $klnOceanSearchKLN .= " and ".$data_reference_field." >= CURRENT_DATE - ".$dynamic_start_offset." and ".$data_reference_field." <= CURRENT_DATE + ".$dynamic_end_offset."";
  747. } else {
  748. if(!empty($fixed_start_date)){
  749. $klnOceanSearchKLN .= " and ".$data_reference_field." >= '".common::usDate2sqlDate($fixed_start_date)."'";
  750. }
  751. if(!empty($fixed_end_date)){
  752. $klnOceanSearchKLN .= " and ".$data_reference_field." <= '".common::usDate2sqlDate($fixed_end_date)."'";
  753. }
  754. }
  755. if(!empty($schedule_order_field)){
  756. $orderby = " order by \"".strtoupper($schedule_order_field)."\"";
  757. }
  758. } else {
  759. //如果kln_report_schedule有值了。就直接这样查询 就页面而言不会进入这个分支
  760. $schedule_search = common::excuteObjectSql("select t.name,t.level,s.schedule_order_field,s.data_reference_field,s.data_range_type,
  761. s.dynamic_start_offset,s.dynamic_end_offset,
  762. s.fixed_start_date,s.fixed_end_date,
  763. t.report_sql,t.count_sql
  764. from public.kln_report_template t
  765. left join public.kln_report_schedule s on s.serial_no = t.serial_no
  766. where s.serial_no = '$serial_no' and lower(s.create_by) = '".strtolower(_getLoginName())."'");
  767. if($schedule_search["data_range_type"] == "dynamic_rolling"){
  768. $field_db = strtolower($schedule_search["data_reference_field"]);
  769. $dynamic_start_offset_db = empty($schedule_search["dynamic_start_offset"]) ? 0 : $schedule_search["dynamic_start_offset"];
  770. $dynamic_end_offset_db = empty($schedule_search["dynamic_end_offset"]) ? 0 : $schedule_search["dynamic_end_offset"];
  771. $klnOceanSearchKLN .= " and ".$field_db." >= CURRENT_DATE - ".$dynamic_start_offset_db." and ".$field_db." <= CURRENT_DATE + ".$dynamic_end_offset_db."";
  772. } else {
  773. $field_db = strtolower($schedule_search["data_reference_field"]);
  774. $fixed_start_date_db = $schedule_search["fixed_start_date"];
  775. $fixed_end_date_db = $schedule_search["fixed_end_date"];
  776. if(!empty($fixed_start_date_db)){
  777. $klnOceanSearchKLN .= " and ".$field_db." >= '".$fixed_start_date_db."'";
  778. }
  779. if(!empty($fixed_end_date_db)){
  780. $klnOceanSearchKLN .= " and ".$field_db." <= '".$fixed_end_date_db."'";
  781. }
  782. }
  783. if(!empty($schedule_search["schedule_order_field"])){
  784. $orderby = " order by \"".strtoupper($schedule_search["schedule_order_field"])."\"";
  785. }
  786. }
  787. $count_sql = str_replace('<{klnOceanSearchKLN}>', $klnOceanSearchKLN, $count_sql);
  788. $count_sql = str_replace('<{ocItemSearchKLN}>', " ", $count_sql);
  789. $count_sql = str_replace('<{vvSearchKLN}>', " ", $count_sql);
  790. $count_sql = str_replace('<{orderby}>', "", $count_sql);
  791. error_log($schedule_search['name'].": report_schedule_count, ".$count_sql);
  792. $report_sql = str_replace('<{klnOceanSearchKLN}>', $klnOceanSearchKLN, $report_sql);
  793. $report_sql = str_replace('<{ocItemSearchKLN}>', " ", $report_sql);
  794. $report_sql = str_replace('<{CustomFiled}>', $CustomFiled, $report_sql);
  795. $report_sql = str_replace('<{vvSearchKLN}>', " ", $report_sql);
  796. $report_sql = str_replace('<{orderby}>', $orderby, $report_sql);
  797. //查询sql
  798. $cp = common::check_input($_POST ['cp']); //current_page
  799. $ps = common::check_input($_POST ['ps']); //ps
  800. if (empty($ps))
  801. $ps = 10;
  802. if (empty($cp))
  803. $cp = 1;
  804. $rc = $_POST ['rc'];
  805. if ($rc == -1) {
  806. $rc = common::excuteOneSql($count_sql);
  807. }
  808. $tp = ceil($rc / $ps);
  809. if ($rc > 0) {
  810. $tmp_search_without_limit = $report_sql;
  811. $report_sql .= " limit " . $ps . " offset " . ($cp - 1) * $ps;
  812. error_log($schedule_search['name'].": report_schedule_search, ".$report_sql);
  813. $rs = common::excuteListSql($report_sql);
  814. // 第一步:预处理 mapping,转为高效查找的哈希表
  815. $valueMapByField = [];
  816. foreach ($mappingConfig as $fieldName => $mapList) {
  817. $valueMapByField[$fieldName] = [];
  818. foreach ($mapList as $item) {
  819. // 将 system 值作为 key,converted 作为 value
  820. $valueMapByField[$fieldName][(string)$item['system']] = $item['converted'];
  821. }
  822. }
  823. // 第二步:遍历结果集,逐行、逐字段替换值
  824. $convertedRs = [];
  825. foreach ($rs as $row) {
  826. $newRow = [];
  827. foreach ($row as $field => $value) {
  828. // 如果该字段有配置映射,并且当前值在映射中,则替换
  829. if (isset($valueMapByField[$field]) && isset($valueMapByField[$field][(string)$value])) {
  830. $newRow[$field] = $valueMapByField[$field][(string)$value];
  831. } else {
  832. // 否则保留原值
  833. $newRow[$field] = $value;
  834. }
  835. }
  836. $convertedRs[] = $newRow;
  837. }
  838. $arrTmp = array('searchData' => $convertedRs,
  839. 'rc' => intval($rc),
  840. 'ps' => intval($ps),
  841. 'cp' => intval($cp),
  842. 'tp' => intval($tp));
  843. }else{
  844. $arrTmp = array('searchData' => array(),
  845. 'rc' => intval($rc),
  846. 'ps' => intval($ps),
  847. 'cp' => intval($cp),
  848. 'tp' => intval($tp));
  849. }
  850. $dataReturn['tableData'] = $arrTmp;
  851. common::echo_json_encode(200, $dataReturn);
  852. exit();
  853. exit;
  854. }
  855. if ($operate == "report_schedule_save"){
  856. $serial_no = common::check_input($_POST ['serial_no']);
  857. $validity_type = common::check_input($_POST ['validityPeriodType']);
  858. $valid_from = "null";
  859. $valid_to = "null";
  860. if($validity_type == "custom"){
  861. $valid_from = "'".common::check_input($_POST ['validityPeriodStartDate'])."'";
  862. $valid_to = "'".common::check_input($_POST ['validityPeriodEndDate'])."'";
  863. }
  864. $data_reference_field = strtolower(common::check_input($_POST ['fieldType']));
  865. $data_range_type = common::check_input($_POST ['type']);
  866. if($data_range_type == "dynamic_rolling"){
  867. $dynamic_start_offset = "'".common::check_input($_POST ['startDate'])."'";
  868. $dynamic_end_offset = "'".common::check_input($_POST ['endDate'])."'";
  869. $fixed_start_date = "null";
  870. $fixed_end_date = "null";
  871. }else{
  872. $dynamic_start_offset = "null";
  873. $dynamic_end_offset = "null";
  874. $fixed_start_date = "'".common::check_input($_POST ['startDate'])."'";
  875. $fixed_end_date = "'".common::check_input($_POST ['endDate'])."'";
  876. }
  877. $schedule_order_field = common::check_input($_POST ['orderBy']);
  878. if(empty($schedule_order_field)){
  879. $schedule_order_field = "ETD";
  880. }
  881. $email_recipients = common::check_input($_POST ['emailRecipients']);
  882. $timezone = common::check_input($_POST ['timezone']);
  883. $daily_time = "null";
  884. $weekly_day = "null";
  885. $weekly_time = "null";
  886. $monthly_day = "null";
  887. $monthly_time = "null";
  888. $quarterly_month= "null";
  889. $quarterly_day= "null";
  890. $quarterly_time = "null";
  891. $yearly_month = "null";
  892. $yearly_day = "null";
  893. $yearly_time = "null";
  894. $delivery_frequency = common::check_input($_POST ['deliveryFrequency']);
  895. if($delivery_frequency == 'daily'){
  896. $daily_time = "'".common::check_input($_POST ['time'])."'";
  897. }elseif($delivery_frequency == 'weekly'){
  898. $weekly_day= common::toPgTextArrayLiteral($_POST ['week']);
  899. $weekly_time = "'".common::check_input($_POST ['time'])."'";
  900. }elseif($delivery_frequency == 'monthly'){
  901. $monthly_day= common::toPgTextArrayLiteral($_POST ['monthlyDay']);
  902. $monthly_time = "'".common::check_input($_POST ['time'])."'";
  903. }elseif($delivery_frequency == 'quarterly'){
  904. //检查数组是否有值
  905. $quarterly_month = "'".common::check_input($_POST ['quarterMonth'])."'";
  906. $quarterly_day = "'".common::check_input($_POST ['day'])."'";
  907. $quarterly_time = "'".common::check_input($_POST ['time'])."'";
  908. }elseif($delivery_frequency == 'yearly'){
  909. $yearly_month= common::toPgTextArrayLiteral($_POST ['yearlyMonth']);
  910. $yearly_day = "'".common::check_input($_POST ['day'])."'";
  911. $yearly_time = "'".common::check_input($_POST ['time'])."'";
  912. }
  913. $sql = "";
  914. $klnOceanSearchKLN = ' where ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  915. if (!empty($serial_no)){
  916. $exist = common::excuteObjectSql("select serial_no from public.kln_report_schedule where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."'");
  917. if (!empty($exist['serial_no'])) {
  918. $updateSqlSet = " schedule_order_field = '".$schedule_order_field."',
  919. validity_type = '".$validity_type."',
  920. valid_from = ".$valid_from.",
  921. valid_to = ".$valid_to.",
  922. data_reference_field = '".$data_reference_field."',
  923. data_range_type = '".$data_range_type."',
  924. dynamic_start_offset = ".$dynamic_start_offset.",
  925. dynamic_end_offset = ".$dynamic_end_offset.",
  926. fixed_start_date = ".$fixed_start_date.",
  927. fixed_end_date = ".$fixed_end_date.",
  928. delivery_frequency = '".$delivery_frequency."',
  929. daily_time = ".$daily_time.",
  930. weekly_day = ".$weekly_day.",
  931. weekly_time = ".$weekly_time.",
  932. monthly_day = ".$monthly_day.",
  933. monthly_time = ".$monthly_time.",
  934. quarterly_month = ".$quarterly_month.",
  935. quarterly_day = ".$quarterly_day.",
  936. quarterly_time = ".$quarterly_time.",
  937. yearly_month = ".$yearly_month.",
  938. yearly_day = ".$yearly_day.",
  939. yearly_time = ".$yearly_time.",
  940. timezone = '".$timezone."',
  941. email_recipients = '".$email_recipients."',
  942. next_run_time = null,
  943. search_extend_hand = '".common::check_input($klnOceanSearchKLN)."',
  944. create_by = '"._getLoginName()."',
  945. created_time = now()";
  946. //代表update
  947. $sql .= "update public.kln_report_schedule set ".$updateSqlSet."
  948. where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."';";
  949. } else {
  950. $sql .= "INSERT INTO public.kln_report_schedule(
  951. serial_no, search_extend_hand, schedule_order_field,
  952. validity_type, valid_from, valid_to, data_reference_field, data_range_type,
  953. dynamic_start_offset, dynamic_end_offset, fixed_start_date, fixed_end_date,
  954. delivery_frequency, daily_time, weekly_day, weekly_time, monthly_day,
  955. monthly_time, quarterly_month, quarterly_day, quarterly_time,
  956. yearly_month, yearly_day, yearly_time, timezone, email_recipients,
  957. next_run_time, create_by, created_time)
  958. VALUES ('$serial_no', '".common::check_input($klnOceanSearchKLN)."', '".$schedule_order_field."',
  959. '".$validity_type."', ".$valid_from.", ".$valid_to.", '".$data_reference_field."', '".$data_range_type."',
  960. ".$dynamic_start_offset.", ".$dynamic_end_offset.", ".$fixed_start_date.", ".$fixed_end_date.",
  961. '".$delivery_frequency."', ".$daily_time.", ".$weekly_day.", ".$weekly_time.", ".$monthly_day.",
  962. ".$monthly_time.", ".$quarterly_month.", ".$quarterly_day.", ".$quarterly_time.",
  963. ".$yearly_month.", ".$yearly_day.", ".$yearly_time.", '".$timezone."', '".$email_recipients."',
  964. null, '"._getLoginName()."',now());";
  965. }
  966. }
  967. if (!empty($sql)){
  968. common::excuteUpdateSql($sql);
  969. //执行成功后,处理next_run_time
  970. $config = common::excuteObjectSql("select delivery_frequency,daily_time,
  971. array_to_json(weekly_day) as weekly_day_json,weekly_time,
  972. array_to_json(monthly_day) as monthly_day_json,monthly_time,
  973. quarterly_month,quarterly_day,quarterly_time,
  974. array_to_json(yearly_month) as yearly_month_json,yearly_day,yearly_time,timezone
  975. from public.kln_report_schedule where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."';");
  976. $config["weekly_day"] = json_decode($config["weekly_day_json"],true);
  977. $config["monthly_day"] = json_decode($config["monthly_day_json"],true);
  978. $config["yearly_month"] = json_decode($config["yearly_month_json"],true);
  979. $next = common::calculateNextRunTime($config);
  980. $next_run_time = $next->format('Y-m-d H:i:s');
  981. common::excuteUpdateSql("update public.kln_report_schedule set next_run_time = '$next_run_time' where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."';");
  982. $data = array("msg" =>"success");
  983. }
  984. common::echo_json_encode(200,$data);
  985. exit();
  986. }
  987. }
  988. /**
  989. * 根据提交的参数动态的拼接filter sql
  990. */
  991. public function returnFilterSql($filtersList){
  992. $klnVipDb = common::getReportRealDBFiled();
  993. $vvSearchKLN = " where 1=1 ";
  994. $klnOceanSearchKLN = " where created_time > CURRENT_DATE - INTERVAL '1 years' and " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  995. //$klnOceanSearchKLN = " where " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  996. $ocItemSearchKLN = " where 1=1 ";
  997. foreach($filtersList as $fiter){
  998. if(!empty($_POST[$fiter['field']])){
  999. $key = array_search($fiter['field'], $klnVipDb);
  1000. if($key !== false){
  1001. //找到给key
  1002. $temp_sql_where = "";
  1003. if ($fiter['data_type'] == "string"){
  1004. $temp_sql_where .= " and ".$key." = '". common::check_input($_POST[$fiter['field']])."'";
  1005. } elseif ($fiter['data_type'] == "number"){
  1006. $temp_arr = $_POST [$fiter['field']];
  1007. if(!empty($temp_arr[0])){
  1008. $temp_sql_where .= " and ".$key."::integer >= '". common::check_input($temp_arr[0])."'";
  1009. }
  1010. if(!empty($temp_arr[1])){
  1011. $temp_sql_where .= " and ".$key."::integer <= '". common::check_input($temp_arr[1])."'";
  1012. }
  1013. } elseif ($fiter['data_type'] == "date"){
  1014. $temp_arr = $_POST [$fiter['field']];
  1015. if(!empty($temp_arr[0])){
  1016. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1017. $temp_sql_where .= " and ".$key." >= '". $date_from."'";
  1018. }
  1019. if(!empty($temp_arr[1])){
  1020. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1021. $temp_sql_where .= " and ".$key." <= '". $date_to."'";
  1022. }
  1023. }
  1024. if(utils::startWith($key,"oc") || utils::startWith($key,"oi")){
  1025. $ocItemSearchKLN .= $temp_sql_where;
  1026. } else {
  1027. $klnOceanSearchKLN .= $temp_sql_where;
  1028. }
  1029. } else {
  1030. //获取POST name 用户去别名得字段,放在vvSearchKLN上
  1031. $_post_field = $fiter['field'];
  1032. $_post_field = strtolower($_post_field);
  1033. $_post_field = preg_replace('/[^a-z0-9]+/', '_', $_post_field); // 非字母数字 → _
  1034. $_post_field = trim($_post_field, '_');
  1035. if ($fiter['data_type'] == "string"){
  1036. $vvSearchKLN .= " and \"".$fiter['field_real']."\" ilike '%". common::check_input($_POST [$_post_field])."%'";
  1037. } elseif ($fiter['data_type'] == "number"){
  1038. $temp_arr = $_POST [$_post_field];
  1039. if(!empty($temp_arr[0])){
  1040. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::integer >= '". common::check_input($temp_arr[0])."'";
  1041. }
  1042. if(!empty($temp_arr[1])){
  1043. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::integer <= '". common::check_input($temp_arr[1])."'";
  1044. }
  1045. } elseif ($fiter['data_type'] == "date"){
  1046. $temp_arr = $_POST [$_post_field];
  1047. //先判断日期字符串是否为空,这里则有做 是因为sql 整合了柜子315时间,和 milestone的时间, 只能text转date
  1048. if(!empty($temp_arr[0])){
  1049. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1050. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1051. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') >= '". $date_from."'";
  1052. }
  1053. if(!empty($temp_arr[1])){
  1054. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1055. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1056. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') <= '". $date_to."'";
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }
  1062. return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN);
  1063. }
  1064. /**
  1065. * 根据提交的参数动态的拼接Count sql
  1066. */
  1067. public function returnFilterSql_v1($filtersList){
  1068. $klnVipDb = common::getReportRealDBFiled();
  1069. $vvSearchKLN = " where 1=1 ";
  1070. $klnOceanSearchKLN = " where created_time > CURRENT_DATE - INTERVAL '1 years' and " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1071. //$klnOceanSearchKLN = " where " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1072. $ocItemSearchKLN = " where 1=1 ";
  1073. $filterFields = array();
  1074. foreach($filtersList as $fiter){
  1075. if(!empty($_POST[$fiter['field']])){
  1076. //这里其实可以改成field_real
  1077. $key = array_search($fiter['field'], $klnVipDb);
  1078. $filterFields[] = $fiter['field_real'];
  1079. if($key !== false){
  1080. //找到给key
  1081. $temp_sql_where = "";
  1082. if ($fiter['data_type'] == "string" || $fiter['data_type'] == "select"){
  1083. $temp_sql_where .= " and ".$key." ilike '%". common::check_input($_POST[$fiter['field']])."%'";
  1084. } elseif ($fiter['data_type'] == "number"){
  1085. $temp_arr = $_POST [$fiter['field']];
  1086. if(!empty($temp_arr[0])){
  1087. $temp_sql_where .= " and ".$key."::numeric >= '". common::check_input($temp_arr[0])."'";
  1088. }
  1089. if(!empty($temp_arr[1])){
  1090. $temp_sql_where .= " and ".$key."::numeric <= '". common::check_input($temp_arr[1])."'";
  1091. }
  1092. } elseif ($fiter['data_type'] == "date"){
  1093. $temp_arr = $_POST [$fiter['field']];
  1094. if(!empty($temp_arr[0])){
  1095. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1096. $temp_sql_where .= " and ".$key." >= '". $date_from."'";
  1097. }
  1098. if(!empty($temp_arr[1])){
  1099. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1100. $temp_sql_where .= " and ".$key." <= '". $date_to."'";
  1101. }
  1102. }
  1103. if (utils::startWith($key,"oc") || utils::startWith($key,"oi") || utils::startWith($key,"oe") || utils::startWith($key,"co2_r")
  1104. || $fiter['field'] == "total_distance"
  1105. || $fiter['field'] == "last_mile_delivery"
  1106. || $key == "COALESCE(oe.import_po_no,oo.po_no)"
  1107. || $key == "oo._voyage"
  1108. || $key == "oo._vessel"
  1109. || $key == "oo.new_status"){
  1110. $ocItemSearchKLN .= $temp_sql_where;
  1111. } else {
  1112. $klnOceanSearchKLN .= $temp_sql_where;
  1113. }
  1114. } else {
  1115. //获取POST name 用户去别名得字段,放在vvSearchKLN上
  1116. $_post_field = $fiter['field'];
  1117. $_post_field = strtolower($_post_field);
  1118. $_post_field = preg_replace('/[^a-z0-9]+/', '_', $_post_field); // 非字母数字 → _
  1119. $_post_field = trim($_post_field, '_');
  1120. if ($fiter['data_type'] == "string"){
  1121. $vvSearchKLN .= " and \"".$fiter['field_real']."\" ilike '%". common::check_input($_POST [$_post_field])."%'";
  1122. } elseif ($fiter['data_type'] == "number"){
  1123. $temp_arr = $_POST [$_post_field];
  1124. if(!empty($temp_arr[0])){
  1125. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::numeric >= '". common::check_input($temp_arr[0])."'";
  1126. }
  1127. if(!empty($temp_arr[1])){
  1128. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::numeric <= '". common::check_input($temp_arr[1])."'";
  1129. }
  1130. } elseif ($fiter['data_type'] == "date"){
  1131. $temp_arr = $_POST [$_post_field];
  1132. //先判断日期字符串是否为空,这里则有做 是因为sql 整合了柜子315时间,和 milestone的时间, 只能text转date
  1133. if(!empty($temp_arr[0])){
  1134. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1135. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1136. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') >= '". $date_from."'";
  1137. }
  1138. if(!empty($temp_arr[1])){
  1139. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1140. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1141. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') <= '". $date_to."'";
  1142. }
  1143. }
  1144. }
  1145. }
  1146. }
  1147. return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN,"filterFields"=>$filterFields);
  1148. }
  1149. /**
  1150. * 根据提交的参数动态的拼接sort by sql
  1151. */
  1152. public function returnSortBySql(){
  1153. $sortByField = $_POST['sortByField'];
  1154. $sortByOrder = $_POST['sortByOrder'];
  1155. $sort_sql_temp = " ";
  1156. if(!empty($sortByField) && !empty($sortByOrder)){
  1157. $sort_sql_temp = " order by \"".$sortByField."\" ". $sortByOrder;
  1158. }
  1159. return $sort_sql_temp;
  1160. }
  1161. }
  1162. ?>