report.class.php 68 KB

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