report.class.php 65 KB

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