report.class.php 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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. $type = $filed['data_type'] == "string" ? "input" : ($filed['data_type'] == "date" ? "date" : "input");
  442. $field_display_name = $filed['field_display_name'];
  443. $field_display_name = strtolower($field_display_name);
  444. $field_display_name = preg_replace('/[^a-z0-9]+/', '_', $field_display_name); // 非字母数字 → _
  445. $field_display_name = trim($field_display_name, '_');
  446. $filtersList[] = array(
  447. "label"=>$filed['field_display_name_user'],
  448. "field"=>$field_display_name,
  449. "field_real"=>$filed['field_display_name'],
  450. "type"=>$type,
  451. "data_type"=>$filed['data_type'],
  452. "value"=>[],"options"=>[]);
  453. }
  454. if($filed['is_sort_enabled'] == 't'){
  455. $sortByOptions[] = $filed['field_db'];
  456. }
  457. //用户自定义字段
  458. if($filed['field_type'] == 'Custom'){
  459. $CustomFiled .= " , '".$filed['custom_fixed_value']."' AS \"".$filed['field_display_name_user']."\"";
  460. }
  461. if(!empty($filed['field_data_mapping'])){
  462. $mappingConfig[$filed['field_display_name']] =json_decode($filed['field_data_mapping'],true);
  463. }
  464. $temp = array();
  465. $temp['field'] = $filed['field_display_name'];
  466. $temp['title'] = $filed['field_display_name_user'];
  467. $temp['type'] = $filed['field_db'] == "Status" ? "status" : "normal";
  468. $temp['formatter'] = "";
  469. $tableColumns[] = $temp;
  470. }
  471. $dataReturn['tableColumns'] = $tableColumns;
  472. $dataReturn['filtersList'] = $filtersList;
  473. if(!empty($sortByOptions)){
  474. $dataReturn['sortBy'] = array("field"=>$sortByOptions[0],"options"=>$sortByOptions,"order"=>"asc");
  475. }else{
  476. $dataReturn['sortBy'] = array("field"=>"","options"=>[],"order"=>"asc");
  477. }
  478. $reportFiled = common::excuteObjectSql("select name,report_sql,count_sql,level from public.kln_report_template where serial_no = '".$serial_no."'");
  479. $sqlManage = common::excuteObjectSql("select sql,count_sql,level from public.kln_report_sql_manage where lower(level) = '".strtolower($reportFiled['level'])."'");
  480. $report_sql = $sqlManage["sql"];
  481. //$count_sql = $sqlManage["count_sql"];
  482. $filterSQLArr = $this->returnFilterSql_v1($filtersList);
  483. $count_sql = common::buildCountSql($filterSQLArr['filterFields'],$reportFiled['level']);
  484. //return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN);
  485. $count_sql = str_replace('<{klnOceanSearchKLN}>', $filterSQLArr['klnOceanSearchKLN'], $count_sql);
  486. $count_sql = str_replace('<{ocItemSearchKLN}>', $filterSQLArr['ocItemSearchKLN'], $count_sql);
  487. $count_sql = str_replace('<{vvSearchKLN}>', $filterSQLArr['vvSearchKLN'], $count_sql);
  488. $count_sql = str_replace('<{orderby}>', "", $count_sql);
  489. error_log($reportFiled['name'].": report_detail_count, ".$count_sql);
  490. $report_sql = str_replace('<{klnOceanSearchKLN}>', $filterSQLArr['klnOceanSearchKLN'], $report_sql);
  491. $report_sql = str_replace('<{ocItemSearchKLN}>', $filterSQLArr['ocItemSearchKLN'], $report_sql);
  492. $report_sql = str_replace('<{CustomFiled}>', $CustomFiled, $report_sql);
  493. $report_sql = str_replace('<{vvSearchKLN}>', $filterSQLArr['vvSearchKLN'], $report_sql);
  494. $report_sql = str_replace('<{orderby}>', $this->returnSortBySql(), $report_sql);
  495. //查询data
  496. $cp = common::check_input($_POST ['cp']); //current_page
  497. $ps = common::check_input($_POST ['ps']); //ps
  498. if (empty($ps))
  499. $ps = 10;
  500. if (empty($cp))
  501. $cp = 1;
  502. $rc = $_POST ['rc'];
  503. if ($rc == -1) {
  504. $rc = common::excuteOneSql($count_sql);
  505. }
  506. $tp = ceil($rc / $ps);
  507. if ($rc > 0) {
  508. $tmp_search_without_limit = $report_sql;
  509. $report_sql .= " limit " . $ps . " offset " . ($cp - 1) * $ps;
  510. error_log($reportFiled['name'].": report_detail_search, ".$report_sql);
  511. $rs = common::excuteListSql($report_sql);
  512. // 第一步:预处理 mapping,转为高效查找的哈希表
  513. $valueMapByField = [];
  514. foreach ($mappingConfig as $fieldName => $mapList) {
  515. $valueMapByField[$fieldName] = [];
  516. foreach ($mapList as $item) {
  517. // 将 system 值作为 key,converted 作为 value
  518. $valueMapByField[$fieldName][(string)$item['system']] = $item['converted'];
  519. }
  520. }
  521. // 第二步:遍历结果集,逐行、逐字段替换值
  522. $convertedRs = [];
  523. foreach ($rs as $row) {
  524. $newRow = [];
  525. foreach ($row as $field => $value) {
  526. // 如果该字段有配置映射,并且当前值在映射中,则替换
  527. if (isset($valueMapByField[$field]) && isset($valueMapByField[$field][(string)$value])) {
  528. $newRow[$field] = $valueMapByField[$field][(string)$value];
  529. } else {
  530. // 否则保留原值
  531. $newRow[$field] = $value;
  532. }
  533. }
  534. $convertedRs[] = $newRow;
  535. }
  536. $arrTmp = array('searchData' => $convertedRs,
  537. 'rc' => intval($rc),
  538. 'ps' => intval($ps),
  539. 'cp' => intval($cp),
  540. 'tp' => intval($tp));
  541. }else{
  542. $arrTmp = array('searchData' => array());
  543. }
  544. $dataReturn['tableData'] = $arrTmp;
  545. $dataReturn['tmp_search'] = common::deCode($tmp_search_without_limit, 'E');
  546. $dataReturn['tmp_mapping'] = common::deCode(json_encode($mappingConfig), 'E');
  547. $dataReturn['reportName'] = $reportFiled['name'];
  548. common::echo_json_encode(200, $dataReturn);
  549. exit();
  550. }
  551. /*
  552. * export excel
  553. */
  554. if ($operate == "excel") {
  555. $sql = common::deCode($_POST['tmp_search'], 'D');
  556. $tmp_mapping = common::deCode($_POST['tmp_mapping'], 'D');
  557. $mappingConfig = json_decode($tmp_mapping,true);
  558. if(!empty($sql)){
  559. $rs = common::excuteListSql($sql);
  560. }
  561. // 第一步:预处理 mapping,转为高效查找的哈希表
  562. $valueMapByField = [];
  563. foreach ($mappingConfig as $fieldName => $mapList) {
  564. $valueMapByField[$fieldName] = [];
  565. foreach ($mapList as $item) {
  566. // 将 system 值作为 key,converted 作为 value
  567. $valueMapByField[$fieldName][(string)$item['system']] = $item['converted'];
  568. }
  569. }
  570. // 第二步:遍历结果集,逐行、逐字段替换值
  571. $convertedRs = [];
  572. foreach ($rs as $row) {
  573. $newRow = [];
  574. foreach ($row as $field => $value) {
  575. //去除null
  576. if(empty($value[$field]) || $value[$field] == null){
  577. $value[$field] = "";
  578. }
  579. // 如果该字段有配置映射,并且当前值在映射中,则替换
  580. if (isset($valueMapByField[$field]) && isset($valueMapByField[$field][(string)$value])) {
  581. $newRow[$field] = $valueMapByField[$field][(string)$value];
  582. } else {
  583. // 否则保留原值
  584. $newRow[$field] = $value;
  585. }
  586. }
  587. $convertedRs[] = $newRow;
  588. }
  589. common::echo_json_encode(200,array("msg"=>"success","Data" => $convertedRs));
  590. exit;
  591. }
  592. if ($operate == "manage_fileds") {
  593. $serial_no = common::check_input($_POST ['serial_no']);
  594. $reportFiled = common::excuteListSql("select * from public.kln_report_field_config
  595. where template_serial_no = '".$serial_no."' order by id ");
  596. $data = array();
  597. foreach($reportFiled as $_reportFiled){
  598. $_reportFiled['is_filter_enabled'] = $_reportFiled['is_filter_enabled'] == 't' ? true : false;
  599. $_reportFiled['is_sort_enabled'] = $_reportFiled['is_sort_enabled'] == 't' ? true : false;
  600. $_reportFiled['is_enabled'] = $_reportFiled['is_enabled'] == 't' ? true : false;
  601. $data[] = $_reportFiled;
  602. }
  603. common::echo_json_encode(200,array("msg"=>"success","data" => $data));
  604. exit;
  605. }
  606. if ($operate == "manage_fileds_save") {
  607. $serial_no = common::check_input($_POST['serial_no']);
  608. $fieldsList = $_POST['fieldsList'];
  609. //先删除,后添加 因为不涉及系统配置字段,全部用kln_report_field_config 字段name
  610. $sql = "delete from public.kln_report_field_config where template_serial_no = '$serial_no';";
  611. foreach($fieldsList as $key =>$_tempFieldsList){
  612. $_field_id = empty($_tempFieldsList['field_id'])? "NULL": $_tempFieldsList['field_id'];
  613. $_field_level = common::check_input($_tempFieldsList['field_level']);
  614. $_field_type = common::check_input($_tempFieldsList['field_type']);
  615. $_field_group_name = common::check_input($_tempFieldsList['field_group_name']);
  616. $_field_db = common::check_input($_tempFieldsList['field_db']);
  617. $_field_code = common::check_input($_tempFieldsList['field_display_name']);
  618. $_display_name = common::check_input($_tempFieldsList['field_display_name_user']);
  619. $_data_type = common::check_input($_tempFieldsList['data_type']);
  620. $_value_type = common::check_input($_tempFieldsList['custom_value_type']);
  621. $_fixed_value = common::check_input($_tempFieldsList['custom_fixed_value']);
  622. $_is_filter_enabled = $_tempFieldsList['is_filter_enabled'];
  623. $_is_sort_enabled = $_tempFieldsList['is_sort_enabled'];
  624. $_is_enabled = $_tempFieldsList['is_enabled'];
  625. $sql .= "INSERT INTO public.kln_report_field_config(
  626. template_serial_no, field_id, field_level, field_type, field_db, field_group_name,
  627. field_display_name, field_display_name_user, data_type, custom_value_type,
  628. custom_fixed_value, is_filter_enabled, is_sort_enabled,is_enabled, created_time)
  629. VALUES ('$serial_no', $_field_id, '$_field_level', '$_field_type', '$_field_db', '$_field_group_name',
  630. '$_field_code', '$_display_name', '$_data_type', '$_value_type',
  631. '$_fixed_value', '$_is_filter_enabled', '$_is_sort_enabled','$_is_enabled',now());";
  632. }
  633. if (!empty($sql)){
  634. common::excuteUpdateSql($sql);
  635. $data = array("msg" =>"success");
  636. }
  637. common::echo_json_encode(200,array("msg"=>"success","Data" => ''));
  638. exit;
  639. }
  640. if ($operate == "report_schedule"){
  641. $serial_no = common::check_input($_POST ['serial_no']);
  642. $schedule = common::excuteObjectSql("select schedule_order_field,validity_type,valid_from,valid_to,
  643. data_reference_field,data_range_type,dynamic_start_offset,dynamic_end_offset,fixed_start_date,fixed_end_date,
  644. delivery_frequency,TO_CHAR(daily_time, 'HH24:MI') as daily_time,
  645. array_to_json(weekly_day) as weekly_days_json,TO_CHAR(weekly_time, 'HH24:MI') as weekly_time,
  646. array_to_json(monthly_day) as monthly_day_json,TO_CHAR(monthly_time, 'HH24:MI') as monthly_time,
  647. quarterly_month,quarterly_day,TO_CHAR(quarterly_time, 'HH24:MI') as quarterly_time,
  648. array_to_json(yearly_month) as yearly_month_json,yearly_day, TO_CHAR(yearly_time, 'HH24:MI') as yearly_time,
  649. timezone,email_recipients
  650. from public.kln_report_schedule where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."'");
  651. $schedule["weekly_days"] = json_decode($schedule["weekly_days"],true);
  652. $schedule["monthly_day"] = json_decode($schedule["monthly_day"],true);
  653. $schedule["yearly_month"] = json_decode($schedule["yearly_month"],true);
  654. //处理成VUE 识别的格式
  655. $data = array();
  656. $data["validityPeriod"] = array("type"=>$schedule["validity_type"],"startDate"=>$schedule["valid_from"],"endDate"=>$schedule["valid_to"]);
  657. if($schedule["data_range_type"] == "dynamic_rolling"){
  658. $data["timeRange"] = array("fieldType"=>$schedule["data_reference_field"],"type"=>$schedule["data_range_type"],
  659. "startDate"=>$schedule["dynamic_start_offset"],"endDate"=>$schedule["dynamic_end_offset"]);
  660. }else{
  661. $data["timeRange"] = array("fieldType"=>$schedule["data_reference_field"],"type"=>$schedule["data_range_type"],
  662. "startDate"=>$schedule["fixed_start_date"],"endDate"=>$schedule["fixed_end_date"]);
  663. }
  664. $time = "";
  665. $week = array();
  666. $month = array();
  667. $quarterMonth = "";
  668. $day = array();
  669. $delivery_frequency = $schedule["delivery_frequency"];
  670. if($delivery_frequency == 'daily'){
  671. $time = $schedule["daily_time"];
  672. }elseif($delivery_frequency == 'weekly'){
  673. $week= json_decode($schedule["weekly_days_json"],true);
  674. $time = $schedule["weekly_time"];
  675. }elseif($delivery_frequency == 'monthly'){
  676. $monthlyDay= json_decode($schedule["monthly_day_json"],true);
  677. $time = $schedule["monthly_time"];
  678. }elseif($delivery_frequency == 'quarterly'){
  679. $quarterMonth = $schedule["quarterly_month"];
  680. $day = $schedule["quarterly_day"];
  681. $time = $schedule["quarterly_time"];
  682. }elseif($delivery_frequency == 'yearly'){
  683. $month= json_decode($schedule["yearly_month_json"],true);
  684. $day = $schedule["yearly_day"];
  685. $time = $schedule["yearly_time"];
  686. }
  687. $data["deliveryFrequency"] = array("emailRecipients"=>$schedule["email_recipients"],"orderBy"=>$schedule["schedule_order_field"],
  688. "timezone"=>$schedule["timezone"],"deliveryFrequency"=>$schedule["delivery_frequency"],
  689. "scheduleDetails" =>array("time"=>$time,"week"=>$week,"month"=>$month,"monthlyDay" =>$monthlyDay,"quarterMonth"=>$quarterMonth,"day"=>$day));
  690. common::echo_json_encode(200,array("msg"=>"success","showData" => $data));
  691. exit;
  692. }
  693. if ($operate == "report_schedule_search"){
  694. $dataReturn = array();
  695. $serial_no = common::check_input($_POST ['serial_no']);
  696. $data_reference_field = strtolower(common::check_input($_POST ['fieldType']));
  697. $data_range_type = common::check_input($_POST ['type']);
  698. if($data_range_type == "dynamic_rolling"){
  699. $dynamic_start_offset = common::check_input($_POST ['startDate']);
  700. $dynamic_end_offset = common::check_input($_POST ['endDate']);
  701. $fixed_start_date = "null";
  702. $fixed_end_date = "null";
  703. }else{
  704. $dynamic_start_offset = "null";
  705. $dynamic_end_offset = "null";
  706. $fixed_start_date = common::check_input($_POST ['startDate']);
  707. $fixed_end_date = common::check_input($_POST ['endDate']);
  708. }
  709. $schedule_order_field = common::check_input($_POST ['orderBy']);
  710. //查询列名
  711. $tableColumns = array();
  712. $mappingConfig = array();
  713. $CustomFiled = "";
  714. $reportFiled = common::excuteListSql("select * from public.kln_report_field_config where template_serial_no = '".$serial_no."'
  715. and is_enabled = true order by id ");
  716. foreach($reportFiled as $filed){
  717. $temp = array();
  718. $temp['field'] = $filed['field_display_name'];
  719. $temp['title'] = $filed['field_display_name_user'];
  720. $temp['type'] = $filed['field_db'] == "Status" ? "status" : "normal";
  721. $temp['formatter'] = "";
  722. $tableColumns[] = $temp;
  723. //用户自定义字段
  724. if($filed['field_type'] == 'Custom'){
  725. $CustomFiled .= " , '".$filed['custom_fixed_value']."' AS \"".$filed['field_display_name_user']."\"";
  726. }
  727. if(!empty($filed['field_data_mapping'])){
  728. $mappingConfig[$filed['field_display_name']] =json_decode($filed['field_data_mapping'],true);
  729. }
  730. }
  731. $dataReturn['tableColumns'] = $tableColumns;
  732. $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'");
  733. $report_sql = $schedule_search["report_sql"];
  734. //$count_sql = $schedule_search["count_sql"];
  735. $filterFields = [];
  736. $count_sql = common::buildCountSql($filterFields,$schedule_search['level']);
  737. //$klnOceanSearchKLN = " where " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  738. $klnOceanSearchKLN = " where created_time > CURRENT_DATE - INTERVAL '1 years' and " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  739. $orderby = "";
  740. if(!empty($data_range_type)){
  741. //代表有用户设置的查询参数
  742. if($data_range_type == "dynamic_rolling"){
  743. $klnOceanSearchKLN .= " and ".$data_reference_field." >= CURRENT_DATE - ".$dynamic_start_offset." and ".$data_reference_field." <= CURRENT_DATE + ".$dynamic_end_offset."";
  744. } else {
  745. if(!empty($fixed_start_date)){
  746. $klnOceanSearchKLN .= " and ".$data_reference_field." >= '".common::usDate2sqlDate($fixed_start_date)."'";
  747. }
  748. if(!empty($fixed_end_date)){
  749. $klnOceanSearchKLN .= " and ".$data_reference_field." <= '".common::usDate2sqlDate($fixed_end_date)."'";
  750. }
  751. }
  752. if(!empty($schedule_order_field)){
  753. $orderby = " order by \"".strtoupper($schedule_order_field)."\"";
  754. }
  755. } else {
  756. //如果kln_report_schedule有值了。就直接这样查询 就页面而言不会进入这个分支
  757. $schedule_search = common::excuteObjectSql("select t.name,t.level,s.schedule_order_field,s.data_reference_field,s.data_range_type,
  758. s.dynamic_start_offset,s.dynamic_end_offset,
  759. s.fixed_start_date,s.fixed_end_date,
  760. t.report_sql,t.count_sql
  761. from public.kln_report_template t
  762. left join public.kln_report_schedule s on s.serial_no = t.serial_no
  763. where s.serial_no = '$serial_no' and lower(s.create_by) = '".strtolower(_getLoginName())."'");
  764. if($schedule_search["data_range_type"] == "dynamic_rolling"){
  765. $field_db = strtolower($schedule_search["data_reference_field"]);
  766. $dynamic_start_offset_db = empty($schedule_search["dynamic_start_offset"]) ? 0 : $schedule_search["dynamic_start_offset"];
  767. $dynamic_end_offset_db = empty($schedule_search["dynamic_end_offset"]) ? 0 : $schedule_search["dynamic_end_offset"];
  768. $klnOceanSearchKLN .= " and ".$field_db." >= CURRENT_DATE - ".$dynamic_start_offset_db." and ".$field_db." <= CURRENT_DATE + ".$dynamic_end_offset_db."";
  769. } else {
  770. $field_db = strtolower($schedule_search["data_reference_field"]);
  771. $fixed_start_date_db = $schedule_search["fixed_start_date"];
  772. $fixed_end_date_db = $schedule_search["fixed_end_date"];
  773. if(!empty($fixed_start_date_db)){
  774. $klnOceanSearchKLN .= " and ".$field_db." >= '".$fixed_start_date_db."'";
  775. }
  776. if(!empty($fixed_end_date_db)){
  777. $klnOceanSearchKLN .= " and ".$field_db." <= '".$fixed_end_date_db."'";
  778. }
  779. }
  780. if(!empty($schedule_search["schedule_order_field"])){
  781. $orderby = " order by \"".strtoupper($schedule_search["schedule_order_field"])."\"";
  782. }
  783. }
  784. $count_sql = str_replace('<{klnOceanSearchKLN}>', $klnOceanSearchKLN, $count_sql);
  785. $count_sql = str_replace('<{ocItemSearchKLN}>', " ", $count_sql);
  786. $count_sql = str_replace('<{vvSearchKLN}>', " ", $count_sql);
  787. $count_sql = str_replace('<{orderby}>', "", $count_sql);
  788. error_log($schedule_search['name'].": report_schedule_count, ".$count_sql);
  789. $report_sql = str_replace('<{klnOceanSearchKLN}>', $klnOceanSearchKLN, $report_sql);
  790. $report_sql = str_replace('<{ocItemSearchKLN}>', " ", $report_sql);
  791. $report_sql = str_replace('<{CustomFiled}>', $CustomFiled, $report_sql);
  792. $report_sql = str_replace('<{vvSearchKLN}>', " ", $report_sql);
  793. $report_sql = str_replace('<{orderby}>', $orderby, $report_sql);
  794. //查询sql
  795. $cp = common::check_input($_POST ['cp']); //current_page
  796. $ps = common::check_input($_POST ['ps']); //ps
  797. if (empty($ps))
  798. $ps = 10;
  799. if (empty($cp))
  800. $cp = 1;
  801. $rc = $_POST ['rc'];
  802. if ($rc == -1) {
  803. $rc = common::excuteOneSql($count_sql);
  804. }
  805. $tp = ceil($rc / $ps);
  806. if ($rc > 0) {
  807. $tmp_search_without_limit = $report_sql;
  808. $report_sql .= " limit " . $ps . " offset " . ($cp - 1) * $ps;
  809. error_log($schedule_search['name'].": report_schedule_search, ".$report_sql);
  810. $rs = common::excuteListSql($report_sql);
  811. // 第一步:预处理 mapping,转为高效查找的哈希表
  812. $valueMapByField = [];
  813. foreach ($mappingConfig as $fieldName => $mapList) {
  814. $valueMapByField[$fieldName] = [];
  815. foreach ($mapList as $item) {
  816. // 将 system 值作为 key,converted 作为 value
  817. $valueMapByField[$fieldName][(string)$item['system']] = $item['converted'];
  818. }
  819. }
  820. // 第二步:遍历结果集,逐行、逐字段替换值
  821. $convertedRs = [];
  822. foreach ($rs as $row) {
  823. $newRow = [];
  824. foreach ($row as $field => $value) {
  825. // 如果该字段有配置映射,并且当前值在映射中,则替换
  826. if (isset($valueMapByField[$field]) && isset($valueMapByField[$field][(string)$value])) {
  827. $newRow[$field] = $valueMapByField[$field][(string)$value];
  828. } else {
  829. // 否则保留原值
  830. $newRow[$field] = $value;
  831. }
  832. }
  833. $convertedRs[] = $newRow;
  834. }
  835. $arrTmp = array('searchData' => $convertedRs,
  836. 'rc' => intval($rc),
  837. 'ps' => intval($ps),
  838. 'cp' => intval($cp),
  839. 'tp' => intval($tp));
  840. }else{
  841. $arrTmp = array('searchData' => array(),
  842. 'rc' => intval($rc),
  843. 'ps' => intval($ps),
  844. 'cp' => intval($cp),
  845. 'tp' => intval($tp));
  846. }
  847. $dataReturn['tableData'] = $arrTmp;
  848. common::echo_json_encode(200, $dataReturn);
  849. exit();
  850. exit;
  851. }
  852. if ($operate == "report_schedule_save"){
  853. $serial_no = common::check_input($_POST ['serial_no']);
  854. $validity_type = common::check_input($_POST ['validityPeriodType']);
  855. $valid_from = "null";
  856. $valid_to = "null";
  857. if($validity_type == "custom"){
  858. $valid_from = "'".common::check_input($_POST ['validityPeriodStartDate'])."'";
  859. $valid_to = "'".common::check_input($_POST ['validityPeriodEndDate'])."'";
  860. }
  861. $data_reference_field = strtolower(common::check_input($_POST ['fieldType']));
  862. $data_range_type = common::check_input($_POST ['type']);
  863. if($data_range_type == "dynamic_rolling"){
  864. $dynamic_start_offset = "'".common::check_input($_POST ['startDate'])."'";
  865. $dynamic_end_offset = "'".common::check_input($_POST ['endDate'])."'";
  866. $fixed_start_date = "null";
  867. $fixed_end_date = "null";
  868. }else{
  869. $dynamic_start_offset = "null";
  870. $dynamic_end_offset = "null";
  871. $fixed_start_date = "'".common::check_input($_POST ['startDate'])."'";
  872. $fixed_end_date = "'".common::check_input($_POST ['endDate'])."'";
  873. }
  874. $schedule_order_field = common::check_input($_POST ['orderBy']);
  875. if(empty($schedule_order_field)){
  876. $schedule_order_field = "ETD";
  877. }
  878. $email_recipients = common::check_input($_POST ['emailRecipients']);
  879. $timezone = common::check_input($_POST ['timezone']);
  880. $daily_time = "null";
  881. $weekly_day = "null";
  882. $weekly_time = "null";
  883. $monthly_day = "null";
  884. $monthly_time = "null";
  885. $quarterly_month= "null";
  886. $quarterly_day= "null";
  887. $quarterly_time = "null";
  888. $yearly_month = "null";
  889. $yearly_day = "null";
  890. $yearly_time = "null";
  891. $delivery_frequency = common::check_input($_POST ['deliveryFrequency']);
  892. if($delivery_frequency == 'daily'){
  893. $daily_time = "'".common::check_input($_POST ['time'])."'";
  894. }elseif($delivery_frequency == 'weekly'){
  895. $weekly_day= common::toPgTextArrayLiteral($_POST ['week']);
  896. $weekly_time = "'".common::check_input($_POST ['time'])."'";
  897. }elseif($delivery_frequency == 'monthly'){
  898. $monthly_day= common::toPgTextArrayLiteral($_POST ['monthlyDay']);
  899. $monthly_time = "'".common::check_input($_POST ['time'])."'";
  900. }elseif($delivery_frequency == 'quarterly'){
  901. //检查数组是否有值
  902. $quarterly_month = "'".common::check_input($_POST ['quarterMonth'])."'";
  903. $quarterly_day = "'".common::check_input($_POST ['day'])."'";
  904. $quarterly_time = "'".common::check_input($_POST ['time'])."'";
  905. }elseif($delivery_frequency == 'yearly'){
  906. $yearly_month= common::toPgTextArrayLiteral($_POST ['yearlyMonth']);
  907. $yearly_day = "'".common::check_input($_POST ['day'])."'";
  908. $yearly_time = "'".common::check_input($_POST ['time'])."'";
  909. }
  910. $sql = "";
  911. $klnOceanSearchKLN = ' where ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  912. if (!empty($serial_no)){
  913. $exist = common::excuteObjectSql("select serial_no from public.kln_report_schedule where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."'");
  914. if (!empty($exist['serial_no'])) {
  915. $updateSqlSet = " schedule_order_field = '".$schedule_order_field."',
  916. validity_type = '".$validity_type."',
  917. valid_from = ".$valid_from.",
  918. valid_to = ".$valid_to.",
  919. data_reference_field = '".$data_reference_field."',
  920. data_range_type = '".$data_range_type."',
  921. dynamic_start_offset = ".$dynamic_start_offset.",
  922. dynamic_end_offset = ".$dynamic_end_offset.",
  923. fixed_start_date = ".$fixed_start_date.",
  924. fixed_end_date = ".$fixed_end_date.",
  925. delivery_frequency = '".$delivery_frequency."',
  926. daily_time = ".$daily_time.",
  927. weekly_day = ".$weekly_day.",
  928. weekly_time = ".$weekly_time.",
  929. monthly_day = ".$monthly_day.",
  930. monthly_time = ".$monthly_time.",
  931. quarterly_month = ".$quarterly_month.",
  932. quarterly_day = ".$quarterly_day.",
  933. quarterly_time = ".$quarterly_time.",
  934. yearly_month = ".$yearly_month.",
  935. yearly_day = ".$yearly_day.",
  936. yearly_time = ".$yearly_time.",
  937. timezone = '".$timezone."',
  938. email_recipients = '".$email_recipients."',
  939. next_run_time = null,
  940. search_extend_hand = '".common::check_input($klnOceanSearchKLN)."',
  941. create_by = '"._getLoginName()."',
  942. created_time = now()";
  943. //代表update
  944. $sql .= "update public.kln_report_schedule set ".$updateSqlSet."
  945. where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."';";
  946. } else {
  947. $sql .= "INSERT INTO public.kln_report_schedule(
  948. serial_no, search_extend_hand, schedule_order_field,
  949. validity_type, valid_from, valid_to, data_reference_field, data_range_type,
  950. dynamic_start_offset, dynamic_end_offset, fixed_start_date, fixed_end_date,
  951. delivery_frequency, daily_time, weekly_day, weekly_time, monthly_day,
  952. monthly_time, quarterly_month, quarterly_day, quarterly_time,
  953. yearly_month, yearly_day, yearly_time, timezone, email_recipients,
  954. next_run_time, create_by, created_time)
  955. VALUES ('$serial_no', '".common::check_input($klnOceanSearchKLN)."', '".$schedule_order_field."',
  956. '".$validity_type."', ".$valid_from.", ".$valid_to.", '".$data_reference_field."', '".$data_range_type."',
  957. ".$dynamic_start_offset.", ".$dynamic_end_offset.", ".$fixed_start_date.", ".$fixed_end_date.",
  958. '".$delivery_frequency."', ".$daily_time.", ".$weekly_day.", ".$weekly_time.", ".$monthly_day.",
  959. ".$monthly_time.", ".$quarterly_month.", ".$quarterly_day.", ".$quarterly_time.",
  960. ".$yearly_month.", ".$yearly_day.", ".$yearly_time.", '".$timezone."', '".$email_recipients."',
  961. null, '"._getLoginName()."',now());";
  962. }
  963. }
  964. if (!empty($sql)){
  965. common::excuteUpdateSql($sql);
  966. //执行成功后,处理next_run_time
  967. $config = common::excuteObjectSql("select delivery_frequency,daily_time,
  968. array_to_json(weekly_day) as weekly_day_json,weekly_time,
  969. array_to_json(monthly_day) as monthly_day_json,monthly_time,
  970. quarterly_month,quarterly_day,quarterly_time,
  971. array_to_json(yearly_month) as yearly_month_json,yearly_day,yearly_time,timezone
  972. from public.kln_report_schedule where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."';");
  973. $config["weekly_day"] = json_decode($config["weekly_day_json"],true);
  974. $config["monthly_day"] = json_decode($config["monthly_day_json"],true);
  975. $config["yearly_month"] = json_decode($config["yearly_month_json"],true);
  976. $next = common::calculateNextRunTime($config);
  977. $next_run_time = $next->format('Y-m-d H:i:s');
  978. 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())."';");
  979. $data = array("msg" =>"success");
  980. }
  981. common::echo_json_encode(200,$data);
  982. exit();
  983. }
  984. }
  985. /**
  986. * 根据提交的参数动态的拼接filter sql
  987. */
  988. public function returnFilterSql($filtersList){
  989. $klnVipDb = common::getReportRealDBFiled();
  990. $vvSearchKLN = " where 1=1 ";
  991. $klnOceanSearchKLN = " where created_time > CURRENT_DATE - INTERVAL '1 years' and " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  992. //$klnOceanSearchKLN = " where " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  993. $ocItemSearchKLN = " where 1=1 ";
  994. foreach($filtersList as $fiter){
  995. if(!empty($_POST[$fiter['field']])){
  996. $key = array_search($fiter['field'], $klnVipDb);
  997. if($key !== false){
  998. //找到给key
  999. $temp_sql_where = "";
  1000. if ($fiter['data_type'] == "string"){
  1001. $temp_sql_where .= " and ".$key." = '". common::check_input($_POST[$fiter['field']])."'";
  1002. } elseif ($fiter['data_type'] == "number"){
  1003. $temp_arr = $_POST [$fiter['field']];
  1004. if(!empty($temp_arr[0])){
  1005. $temp_sql_where .= " and ".$key."::integer >= '". common::check_input($temp_arr[0])."'";
  1006. }
  1007. if(!empty($temp_arr[1])){
  1008. $temp_sql_where .= " and ".$key."::integer <= '". common::check_input($temp_arr[1])."'";
  1009. }
  1010. } elseif ($fiter['data_type'] == "date"){
  1011. $temp_arr = $_POST [$fiter['field']];
  1012. if(!empty($temp_arr[0])){
  1013. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1014. $temp_sql_where .= " and ".$key." >= '". $date_from."'";
  1015. }
  1016. if(!empty($temp_arr[1])){
  1017. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1018. $temp_sql_where .= " and ".$key." <= '". $date_to."'";
  1019. }
  1020. }
  1021. if(utils::startWith($key,"oc") || utils::startWith($key,"oi")){
  1022. $ocItemSearchKLN .= $temp_sql_where;
  1023. } else {
  1024. $klnOceanSearchKLN .= $temp_sql_where;
  1025. }
  1026. } else {
  1027. //获取POST name 用户去别名得字段,放在vvSearchKLN上
  1028. $_post_field = $fiter['field'];
  1029. $_post_field = strtolower($_post_field);
  1030. $_post_field = preg_replace('/[^a-z0-9]+/', '_', $_post_field); // 非字母数字 → _
  1031. $_post_field = trim($_post_field, '_');
  1032. if ($fiter['data_type'] == "string"){
  1033. $vvSearchKLN .= " and \"".$fiter['field_real']."\" ilike '%". common::check_input($_POST [$_post_field])."%'";
  1034. } elseif ($fiter['data_type'] == "number"){
  1035. $temp_arr = $_POST [$_post_field];
  1036. if(!empty($temp_arr[0])){
  1037. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::integer >= '". common::check_input($temp_arr[0])."'";
  1038. }
  1039. if(!empty($temp_arr[1])){
  1040. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::integer <= '". common::check_input($temp_arr[1])."'";
  1041. }
  1042. } elseif ($fiter['data_type'] == "date"){
  1043. $temp_arr = $_POST [$_post_field];
  1044. //先判断日期字符串是否为空,这里则有做 是因为sql 整合了柜子315时间,和 milestone的时间, 只能text转date
  1045. if(!empty($temp_arr[0])){
  1046. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1047. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1048. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') >= '". $date_from."'";
  1049. }
  1050. if(!empty($temp_arr[1])){
  1051. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1052. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1053. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') <= '". $date_to."'";
  1054. }
  1055. }
  1056. }
  1057. }
  1058. }
  1059. return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN);
  1060. }
  1061. /**
  1062. * 根据提交的参数动态的拼接Count sql
  1063. */
  1064. public function returnFilterSql_v1($filtersList){
  1065. $klnVipDb = common::getReportRealDBFiled();
  1066. $vvSearchKLN = " where 1=1 ";
  1067. $klnOceanSearchKLN = " where created_time > CURRENT_DATE - INTERVAL '1 years' and " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1068. //$klnOceanSearchKLN = " where " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1069. $ocItemSearchKLN = " where 1=1 ";
  1070. $filterFields = array();
  1071. foreach($filtersList as $fiter){
  1072. if(!empty($_POST[$fiter['field']])){
  1073. //这里其实可以改成field_real
  1074. $key = array_search($fiter['field'], $klnVipDb);
  1075. $filterFields[] = $fiter['field_real'];
  1076. if($key !== false){
  1077. //找到给key
  1078. $temp_sql_where = "";
  1079. if ($fiter['data_type'] == "string"){
  1080. $temp_sql_where .= " and ".$key." ilike '%". common::check_input($_POST[$fiter['field']])."%'";
  1081. } elseif ($fiter['data_type'] == "number"){
  1082. $temp_arr = $_POST [$fiter['field']];
  1083. if(!empty($temp_arr[0])){
  1084. $temp_sql_where .= " and ".$key."::numeric >= '". common::check_input($temp_arr[0])."'";
  1085. }
  1086. if(!empty($temp_arr[1])){
  1087. $temp_sql_where .= " and ".$key."::numeric <= '". common::check_input($temp_arr[1])."'";
  1088. }
  1089. } elseif ($fiter['data_type'] == "date"){
  1090. $temp_arr = $_POST [$fiter['field']];
  1091. if(!empty($temp_arr[0])){
  1092. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1093. $temp_sql_where .= " and ".$key." >= '". $date_from."'";
  1094. }
  1095. if(!empty($temp_arr[1])){
  1096. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1097. $temp_sql_where .= " and ".$key." <= '". $date_to."'";
  1098. }
  1099. }
  1100. if (utils::startWith($key,"oc") || utils::startWith($key,"oi") || utils::startWith($key,"oe") || utils::startWith($key,"co2_r")
  1101. || $fiter['field'] == "total_distance"
  1102. || $fiter['field'] == "last_mile_delivery"
  1103. || $key == "COALESCE(oe.import_po_no,oo.po_no)"
  1104. || $key == "oo._voyage"
  1105. || $key == "oo._vessel"
  1106. || $key == "oo.new_status"){
  1107. $ocItemSearchKLN .= $temp_sql_where;
  1108. } else {
  1109. $klnOceanSearchKLN .= $temp_sql_where;
  1110. }
  1111. } else {
  1112. //获取POST name 用户去别名得字段,放在vvSearchKLN上
  1113. $_post_field = $fiter['field'];
  1114. $_post_field = strtolower($_post_field);
  1115. $_post_field = preg_replace('/[^a-z0-9]+/', '_', $_post_field); // 非字母数字 → _
  1116. $_post_field = trim($_post_field, '_');
  1117. if ($fiter['data_type'] == "string"){
  1118. $vvSearchKLN .= " and \"".$fiter['field_real']."\" ilike '%". common::check_input($_POST [$_post_field])."%'";
  1119. } elseif ($fiter['data_type'] == "number"){
  1120. $temp_arr = $_POST [$_post_field];
  1121. if(!empty($temp_arr[0])){
  1122. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::numeric >= '". common::check_input($temp_arr[0])."'";
  1123. }
  1124. if(!empty($temp_arr[1])){
  1125. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::numeric <= '". common::check_input($temp_arr[1])."'";
  1126. }
  1127. } elseif ($fiter['data_type'] == "date"){
  1128. $temp_arr = $_POST [$_post_field];
  1129. //先判断日期字符串是否为空,这里则有做 是因为sql 整合了柜子315时间,和 milestone的时间, 只能text转date
  1130. if(!empty($temp_arr[0])){
  1131. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1132. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1133. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') >= '". $date_from."'";
  1134. }
  1135. if(!empty($temp_arr[1])){
  1136. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1137. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1138. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') <= '". $date_to."'";
  1139. }
  1140. }
  1141. }
  1142. }
  1143. }
  1144. return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN,"filterFields"=>$filterFields);
  1145. }
  1146. /**
  1147. * 根据提交的参数动态的拼接sort by sql
  1148. */
  1149. public function returnSortBySql(){
  1150. $sortByField = $_POST['sortByField'];
  1151. $sortByOrder = $_POST['sortByOrder'];
  1152. $sort_sql_temp = " ";
  1153. if(!empty($sortByField) && !empty($sortByOrder)){
  1154. $sort_sql_temp = " order by \"".$sortByField."\" ". $sortByOrder;
  1155. }
  1156. return $sort_sql_temp;
  1157. }
  1158. }
  1159. ?>