report.class.php 66 KB

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