report.class.php 68 KB

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