report.class.php 72 KB

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