report.class.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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 ".$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 ".$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('<{ocItemSearchKLNSFS}>', " ", $count_sql);
  751. $count_sql = str_replace('<{vvSearchKLN}>', " ", $count_sql);
  752. $count_sql = str_replace('<{orderby}>', "", $count_sql);
  753. error_log($schedule_search['name'].": report_schedule_count, ".$count_sql);
  754. $report_sql = str_replace('<{klnOceanSearchKLN}>', $klnOceanSearchKLN, $report_sql);
  755. $report_sql = str_replace('<{ocItemSearchKLN}>', " ", $report_sql);
  756. $report_sql = str_replace('<{ocItemSearchKLNSFS}>', " ", $report_sql);
  757. $report_sql = str_replace('<{CustomFiled}>', $CustomFiled, $report_sql);
  758. $report_sql = str_replace('<{vvSearchKLN}>', " ", $report_sql);
  759. $report_sql = str_replace('<{orderby}>', $orderby, $report_sql);
  760. //查询sql
  761. $cp = common::check_input($_POST ['cp']); //current_page
  762. $ps = common::check_input($_POST ['ps']); //ps
  763. if (empty($ps))
  764. $ps = 10;
  765. if (empty($cp))
  766. $cp = 1;
  767. $rc = $_POST ['rc'];
  768. if ($rc == -1) {
  769. $rc = common::excuteOneSql($count_sql);
  770. }
  771. $tp = ceil($rc / $ps);
  772. if ($rc > 0) {
  773. $tmp_search_without_limit = $report_sql;
  774. $report_sql .= " limit " . $ps . " offset " . ($cp - 1) * $ps;
  775. error_log($schedule_search['name'].": report_schedule_search, ".$report_sql);
  776. $rs = common::excuteListSql($report_sql);
  777. // 第一步:预处理 mapping,转为高效查找的哈希表
  778. $valueMapByField = [];
  779. foreach ($mappingConfig as $fieldName => $mapList) {
  780. $valueMapByField[$fieldName] = [];
  781. foreach ($mapList as $item) {
  782. // 将 system 值作为 key,converted 作为 value
  783. $valueMapByField[$fieldName][(string)$item['system']] = $item['converted'];
  784. }
  785. }
  786. // 第二步:遍历结果集,逐行、逐字段替换值
  787. $convertedRs = [];
  788. foreach ($rs as $row) {
  789. $newRow = [];
  790. foreach ($row as $field => $value) {
  791. // 如果该字段有配置映射,并且当前值在映射中,则替换
  792. if (isset($valueMapByField[$field]) && isset($valueMapByField[$field][(string)$value])) {
  793. $newRow[$field] = $valueMapByField[$field][(string)$value];
  794. } else {
  795. // 否则保留原值
  796. $newRow[$field] = $value;
  797. }
  798. }
  799. $convertedRs[] = $newRow;
  800. }
  801. $arrTmp = array('searchData' => $convertedRs,
  802. 'rc' => intval($rc),
  803. 'ps' => intval($ps),
  804. 'cp' => intval($cp),
  805. 'tp' => intval($tp));
  806. }else{
  807. $arrTmp = array('searchData' => array(),
  808. 'rc' => intval($rc),
  809. 'ps' => intval($ps),
  810. 'cp' => intval($cp),
  811. 'tp' => intval($tp));
  812. }
  813. $dataReturn['tableData'] = $arrTmp;
  814. common::echo_json_encode(200, $dataReturn);
  815. exit();
  816. exit;
  817. }
  818. if ($operate == "report_schedule_save"){
  819. $serial_no = common::check_input($_POST ['serial_no']);
  820. $validity_type = common::check_input($_POST ['validityPeriodType']);
  821. $valid_from = "null";
  822. $valid_to = "null";
  823. if($validity_type == "custom"){
  824. $valid_from = "'".common::check_input($_POST ['validityPeriodStartDate'])."'";
  825. $valid_to = "'".common::check_input($_POST ['validityPeriodEndDate'])."'";
  826. }
  827. $data_reference_field = strtolower(common::check_input($_POST ['fieldType']));
  828. $data_range_type = common::check_input($_POST ['type']);
  829. if($data_range_type == "dynamic_rolling"){
  830. $dynamic_start_offset = "'".common::check_input($_POST ['startDate'])."'";
  831. $dynamic_end_offset = "'".common::check_input($_POST ['endDate'])."'";
  832. $fixed_start_date = "null";
  833. $fixed_end_date = "null";
  834. }else{
  835. $dynamic_start_offset = "null";
  836. $dynamic_end_offset = "null";
  837. $fixed_start_date = "'".common::check_input($_POST ['startDate'])."'";
  838. $fixed_end_date = "'".common::check_input($_POST ['endDate'])."'";
  839. }
  840. $schedule_order_field = common::check_input($_POST ['orderBy']);
  841. if(empty($schedule_order_field)){
  842. $schedule_order_field = "ETD";
  843. }
  844. $email_recipients = common::check_input($_POST ['emailRecipients']);
  845. $timezone = common::check_input($_POST ['timezone']);
  846. $daily_time = "null";
  847. $weekly_day = "null";
  848. $weekly_time = "null";
  849. $monthly_day = "null";
  850. $monthly_time = "null";
  851. $quarterly_month= "null";
  852. $quarterly_day= "null";
  853. $quarterly_time = "null";
  854. $yearly_month = "null";
  855. $yearly_day = "null";
  856. $yearly_time = "null";
  857. $delivery_frequency = common::check_input($_POST ['deliveryFrequency']);
  858. if($delivery_frequency == 'daily'){
  859. $daily_time = "'".common::check_input($_POST ['time'])."'";
  860. }elseif($delivery_frequency == 'weekly'){
  861. $weekly_day= common::toPgTextArrayLiteral($_POST ['week']);
  862. $weekly_time = "'".common::check_input($_POST ['time'])."'";
  863. }elseif($delivery_frequency == 'monthly'){
  864. $monthly_day= common::toPgTextArrayLiteral($_POST ['monthlyDay']);
  865. $monthly_time = "'".common::check_input($_POST ['time'])."'";
  866. }elseif($delivery_frequency == 'quarterly'){
  867. //检查数组是否有值
  868. $quarterly_month = "'".common::check_input($_POST ['quarterMonth'])."'";
  869. $quarterly_day = "'".common::check_input($_POST ['day'])."'";
  870. $quarterly_time = "'".common::check_input($_POST ['time'])."'";
  871. }elseif($delivery_frequency == 'yearly'){
  872. $yearly_month= common::toPgTextArrayLiteral($_POST ['yearlyMonth']);
  873. $yearly_day = "'".common::check_input($_POST ['day'])."'";
  874. $yearly_time = "'".common::check_input($_POST ['time'])."'";
  875. }
  876. $sql = "";
  877. $klnOceanSearchKLN = ' where ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  878. if (!empty($serial_no)){
  879. $exist = common::excuteObjectSql("select serial_no from public.kln_report_schedule where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."'");
  880. if (!empty($exist['serial_no'])) {
  881. $updateSqlSet = " schedule_order_field = '".$schedule_order_field."',
  882. validity_type = '".$validity_type."',
  883. valid_from = ".$valid_from.",
  884. valid_to = ".$valid_to.",
  885. data_reference_field = '".$data_reference_field."',
  886. data_range_type = '".$data_range_type."',
  887. dynamic_start_offset = ".$dynamic_start_offset.",
  888. dynamic_end_offset = ".$dynamic_end_offset.",
  889. fixed_start_date = ".$fixed_start_date.",
  890. fixed_end_date = ".$fixed_end_date.",
  891. delivery_frequency = '".$delivery_frequency."',
  892. daily_time = ".$daily_time.",
  893. weekly_day = ".$weekly_day.",
  894. weekly_time = ".$weekly_time.",
  895. monthly_day = ".$monthly_day.",
  896. monthly_time = ".$monthly_time.",
  897. quarterly_month = ".$quarterly_month.",
  898. quarterly_day = ".$quarterly_day.",
  899. quarterly_time = ".$quarterly_time.",
  900. yearly_month = ".$yearly_month.",
  901. yearly_day = ".$yearly_day.",
  902. yearly_time = ".$yearly_time.",
  903. timezone = '".$timezone."',
  904. email_recipients = '".$email_recipients."',
  905. next_run_time = null,
  906. search_extend_hand = '".common::check_input($klnOceanSearchKLN)."',
  907. create_by = '"._getLoginName()."',
  908. created_time = now()";
  909. //代表update
  910. $sql .= "update public.kln_report_schedule set ".$updateSqlSet."
  911. where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."';";
  912. } else {
  913. $sql .= "INSERT INTO public.kln_report_schedule(
  914. serial_no, search_extend_hand, schedule_order_field,
  915. validity_type, valid_from, valid_to, data_reference_field, data_range_type,
  916. dynamic_start_offset, dynamic_end_offset, fixed_start_date, fixed_end_date,
  917. delivery_frequency, daily_time, weekly_day, weekly_time, monthly_day,
  918. monthly_time, quarterly_month, quarterly_day, quarterly_time,
  919. yearly_month, yearly_day, yearly_time, timezone, email_recipients,
  920. next_run_time, create_by, created_time)
  921. VALUES ('$serial_no', '".common::check_input($klnOceanSearchKLN)."', '".$schedule_order_field."',
  922. '".$validity_type."', ".$valid_from.", ".$valid_to.", '".$data_reference_field."', '".$data_range_type."',
  923. ".$dynamic_start_offset.", ".$dynamic_end_offset.", ".$fixed_start_date.", ".$fixed_end_date.",
  924. '".$delivery_frequency."', ".$daily_time.", ".$weekly_day.", ".$weekly_time.", ".$monthly_day.",
  925. ".$monthly_time.", ".$quarterly_month.", ".$quarterly_day.", ".$quarterly_time.",
  926. ".$yearly_month.", ".$yearly_day.", ".$yearly_time.", '".$timezone."', '".$email_recipients."',
  927. null, '"._getLoginName()."',now());";
  928. }
  929. }
  930. if (!empty($sql)){
  931. common::excuteUpdateSql($sql);
  932. //执行成功后,处理next_run_time
  933. $config = common::excuteObjectSql("select delivery_frequency,daily_time,
  934. array_to_json(weekly_day) as weekly_day_json,weekly_time,
  935. array_to_json(monthly_day) as monthly_day_json,monthly_time,
  936. quarterly_month,quarterly_day,quarterly_time,
  937. array_to_json(yearly_month) as yearly_month_json,yearly_day,yearly_time,timezone
  938. from public.kln_report_schedule where serial_no = '$serial_no' and lower(create_by) = '".strtolower(_getLoginName())."';");
  939. $config["weekly_day"] = json_decode($config["weekly_day_json"],true);
  940. $config["monthly_day"] = json_decode($config["monthly_day_json"],true);
  941. $config["yearly_month"] = json_decode($config["yearly_month_json"],true);
  942. $next = common::calculateNextRunTime($config);
  943. $next_run_time = $next->format('Y-m-d H:i:s');
  944. 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())."';");
  945. $data = array("msg" =>"success");
  946. }
  947. common::echo_json_encode(200,$data);
  948. exit();
  949. }
  950. }
  951. /**
  952. * 根据提交的参数动态的拼接filter sql
  953. */
  954. public function returnFilterSql($filtersList){
  955. $klnVipDb = common::getReportRealDBFiled();
  956. $vvSearchKLN = " where 1=1 ";
  957. $klnOceanSearchKLN = " where created_time > CURRENT_DATE - INTERVAL '1 years' and " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  958. //$klnOceanSearchKLN = " where " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  959. $ocItemSearchKLN = " where 1=1 ";
  960. foreach($filtersList as $fiter){
  961. if(!empty($_POST[$fiter['field']])){
  962. $key = array_search($fiter['field'], $klnVipDb);
  963. if($key !== false){
  964. //找到给key
  965. $temp_sql_where = "";
  966. if ($fiter['data_type'] == "string"){
  967. $temp_sql_where .= " and ".$key." = '". common::check_input($_POST[$fiter['field']])."'";
  968. } elseif ($fiter['data_type'] == "number"){
  969. $temp_arr = $_POST [$fiter['field']];
  970. if(!empty($temp_arr[0])){
  971. $temp_sql_where .= " and ".$key."::integer >= '". common::check_input($temp_arr[0])."'";
  972. }
  973. if(!empty($temp_arr[1])){
  974. $temp_sql_where .= " and ".$key."::integer <= '". common::check_input($temp_arr[1])."'";
  975. }
  976. } elseif ($fiter['data_type'] == "date"){
  977. $temp_arr = $_POST [$fiter['field']];
  978. if(!empty($temp_arr[0])){
  979. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  980. $temp_sql_where .= " and ".$key." >= '". $date_from."'";
  981. }
  982. if(!empty($temp_arr[1])){
  983. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  984. $temp_sql_where .= " and ".$key." <= '". $date_to."'";
  985. }
  986. }
  987. if(utils::startWith($key,"oc") || utils::startWith($key,"oi")){
  988. $ocItemSearchKLN .= $temp_sql_where;
  989. } else {
  990. $klnOceanSearchKLN .= $temp_sql_where;
  991. }
  992. } else {
  993. //获取POST name 用户去别名得字段,放在vvSearchKLN上
  994. $_post_field = $fiter['field'];
  995. $_post_field = strtolower($_post_field);
  996. $_post_field = preg_replace('/[^a-z0-9]+/', '_', $_post_field); // 非字母数字 → _
  997. $_post_field = trim($_post_field, '_');
  998. if ($fiter['data_type'] == "string"){
  999. $vvSearchKLN .= " and \"".$fiter['field_real']."\" ilike '%". common::check_input($_POST [$_post_field])."%'";
  1000. } elseif ($fiter['data_type'] == "number"){
  1001. $temp_arr = $_POST [$_post_field];
  1002. if(!empty($temp_arr[0])){
  1003. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::integer >= '". common::check_input($temp_arr[0])."'";
  1004. }
  1005. if(!empty($temp_arr[1])){
  1006. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::integer <= '". common::check_input($temp_arr[1])."'";
  1007. }
  1008. } elseif ($fiter['data_type'] == "date"){
  1009. $temp_arr = $_POST [$_post_field];
  1010. //先判断日期字符串是否为空,这里则有做 是因为sql 整合了柜子315时间,和 milestone的时间, 只能text转date
  1011. if(!empty($temp_arr[0])){
  1012. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1013. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1014. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') >= '". $date_from."'";
  1015. }
  1016. if(!empty($temp_arr[1])){
  1017. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1018. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1019. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') <= '". $date_to."'";
  1020. }
  1021. }
  1022. }
  1023. }
  1024. }
  1025. return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN);
  1026. }
  1027. /**
  1028. * 根据提交的参数动态的拼接Count sql
  1029. */
  1030. public function returnFilterSql_v1($filtersList){
  1031. $klnVipDb = common::getReportRealDBFiled();
  1032. $vvSearchKLN = " where 1=1 ";
  1033. //$klnOceanSearchKLN = " where created_time > CURRENT_DATE - INTERVAL '1 years' and " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1034. $klnOceanSearchKLN = " where " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1035. $ocItemSearchKLN = " where 1=1 ";
  1036. $ocItemSearchKLNSFS = " where 1=1 ";
  1037. $filterFields = array();
  1038. foreach($filtersList as $fiter){
  1039. if(!empty($_POST[$fiter['field']])){
  1040. //这里其实可以改成field_real
  1041. $key = array_search($fiter['field'], $klnVipDb);
  1042. //是数组,且为空,不加入
  1043. if(is_array($_POST[$fiter['field']]) && common::isArrayAllEmpty($_POST[$fiter['field']])){
  1044. }else{
  1045. $filterFields[] = $fiter['field_real'];
  1046. }
  1047. if($key !== false){
  1048. //找到给key
  1049. $temp_sql_where = "";
  1050. if ($fiter['data_type'] == "string" || $fiter['data_type'] == "select"){
  1051. $textSearch_arr = $_POST[$fiter['field']];
  1052. if($fiter['supportMultiple'] == 'true'){
  1053. $textSearch_arr = str_replace(",", ";", $textSearch_arr);
  1054. $more_param = common::getInNotInSqlForSearch(strtolower($textSearch_arr));
  1055. $temp_sql_where .= " and lower(".$key.") in ($more_param)";
  1056. }else{
  1057. $temp_sql_where .= " and ".$key." = '". common::check_input($_POST[$fiter['field']])."'";
  1058. }
  1059. } elseif ($fiter['data_type'] == "number"){
  1060. $temp_arr = $_POST [$fiter['field']];
  1061. if(trim((string)$temp_arr[0]) !== ''){
  1062. $temp_sql_where .= " and ".$key."::numeric >= '". common::check_input($temp_arr[0])."'";
  1063. }
  1064. if(trim((string)$temp_arr[1]) !== ''){
  1065. $temp_sql_where .= " and ".$key."::numeric <= '". common::check_input($temp_arr[1])."'";
  1066. }
  1067. } elseif ($fiter['data_type'] == "date"){
  1068. $temp_arr = $_POST [$fiter['field']];
  1069. if(!empty($temp_arr[0])){
  1070. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1071. $temp_sql_where .= " and ".$key." >= '". $date_from."'";
  1072. }
  1073. if(!empty($temp_arr[1])){
  1074. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1075. $temp_sql_where .= " and ".$key." <= '". $date_to."'";
  1076. }
  1077. }
  1078. if (utils::startWith($key,"oc") || utils::startWith($key,"oi") || utils::startWith($key,"oe") || utils::startWith($key,"co2_r")
  1079. || $fiter['field'] == "total_distance"
  1080. || $fiter['field'] == "shipment_po_no"
  1081. || $fiter['field'] == "pickup_postal_code"
  1082. || $fiter['field'] == "pickup_mode_type"
  1083. || $fiter['field'] == "last_mile_delivery_postal_code"
  1084. || $fiter['field'] == "last_mile_delivery_mode_type"
  1085. || $fiter['field'] == "last_mile_delivery_date"
  1086. || $fiter['field'] == "last_mile_delivery_time"
  1087. || $fiter['field'] == "last_mile_delivery_city"
  1088. || $fiter['field'] == "last_mile_delivery _address"
  1089. || $fiter['field'] == "co2e_intensity"){
  1090. $ocItemSearchKLN .= $temp_sql_where;
  1091. //sfs 移除这些条件筛选
  1092. if(!($fiter['field'] == "pickup_postal_code"
  1093. || $fiter['field'] == "pickup_mode_type"
  1094. || $fiter['field'] == "last_mile_delivery_postal_code"
  1095. || $fiter['field'] == "last_mile_delivery_mode_type"
  1096. || $fiter['field'] == "last_mile_delivery_date"
  1097. || $fiter['field'] == "last_mile_delivery_time"
  1098. || $fiter['field'] == "last_mile_delivery_city"
  1099. || $fiter['field'] == "last_mile_delivery _address")){
  1100. $ocItemSearchKLNSFS .= $temp_sql_where;
  1101. }
  1102. } else {
  1103. $klnOceanSearchKLN .= $temp_sql_where;
  1104. }
  1105. } else {
  1106. //获取POST name 用户去别名得字段,放在vvSearchKLN上
  1107. $_post_field = $fiter['field'];
  1108. $_post_field = strtolower($_post_field);
  1109. $_post_field = preg_replace('/[^a-z0-9]+/', '_', $_post_field); // 非字母数字 → _
  1110. $_post_field = trim($_post_field, '_');
  1111. if ($fiter['data_type'] == "string"){
  1112. $vvSearchKLN .= " and \"".$fiter['field_real']."\" ilike '%". common::check_input($_POST [$_post_field])."%'";
  1113. } elseif ($fiter['data_type'] == "number"){
  1114. $temp_arr = $_POST [$_post_field];
  1115. if(trim((string)$temp_arr[0]) !== ''){
  1116. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::numeric >= '". common::check_input($temp_arr[0])."'";
  1117. }
  1118. if(trim((string)$temp_arr[1]) !== ''){
  1119. $vvSearchKLN .= " and \"".$fiter['field_real']."\"::numeric <= '". common::check_input($temp_arr[1])."'";
  1120. }
  1121. } elseif ($fiter['data_type'] == "date"){
  1122. $temp_arr = $_POST [$_post_field];
  1123. //先判断日期字符串是否为空,这里则有做 是因为sql 整合了柜子315时间,和 milestone的时间, 只能text转date
  1124. if(!empty($temp_arr[0])){
  1125. $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
  1126. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1127. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') >= '". $date_from."'";
  1128. }
  1129. if(!empty($temp_arr[1])){
  1130. $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
  1131. $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";
  1132. $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') <= '". $date_to."'";
  1133. }
  1134. }
  1135. }
  1136. }
  1137. }
  1138. return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,
  1139. "ocItemSearchKLN"=>$ocItemSearchKLN,"ocItemSearchKLNSFS"=>$ocItemSearchKLNSFS,
  1140. "filterFields"=>$filterFields);
  1141. }
  1142. /**
  1143. * 根据提交的参数动态的拼接sort by sql
  1144. */
  1145. public function returnSortBySql(){
  1146. $sortByField = $_POST['sortByField'];
  1147. $sortByOrder = $_POST['sortByOrder'];
  1148. $sort_sql_temp = " ";
  1149. if(!empty($sortByField) && !empty($sortByOrder)){
  1150. $field_display_name = $sortByField;
  1151. $field_display_name = strtolower($field_display_name);
  1152. $field_display_name = preg_replace('/[^a-z0-9]+/', '_', $field_display_name); // 非字母数字 → _
  1153. $field_display_name = trim($field_display_name, '_');
  1154. $klnVipDb = common::getReportRealDBFiled();
  1155. $key = array_search($field_display_name, $klnVipDb);
  1156. if (utils::startWith($key,"kln_ocean.")
  1157. || $field_display_name == "voyage_flight"
  1158. || $field_display_name == "vessel_airline"
  1159. || $field_display_name == "vslvoy_flight"){
  1160. $sort_sql_temp = " order by ".$key." ". $sortByOrder;
  1161. }
  1162. }
  1163. return $sort_sql_temp;
  1164. }
  1165. }
  1166. ?>