utils.class.php 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. <?php
  2. if (!defined('IN_ONLINE')) {
  3. exit('Access Denied');
  4. }
  5. /**
  6. * Description of utilsclass
  7. *
  8. * @author Administrator
  9. */
  10. class utils {
  11. public static function checkPassword($password,$rule="",$user_login="") {
  12. $str ="";
  13. if (!empty($rule)) {
  14. //是否校验大小写
  15. if (!empty($rule["hasOneUpperChar"])&&$rule["hasOneUpperChar"]) {
  16. if (!preg_match('/[A-Z]/',$password)) {
  17. $str ="Password must contain uppercase letters";
  18. }
  19. }
  20. //是否校验小写
  21. if (!empty($rule["hasOneLowerChar"])&&$rule["hasOneLowerChar"]) {
  22. if (!preg_match('/[a-z]/',$password)) {
  23. $str ="Password must contain lowercase letters";
  24. }
  25. }
  26. //是否存在数字
  27. if (!empty($rule["hasOneNumberChar"])&&$rule["hasOneNumberChar"]) {
  28. if (!preg_match('/[0-9]/',$password)) {
  29. $str ="Password must contain numbers";
  30. }
  31. }
  32. $sql = "select user_type from ra_online_user_roles_rel where upper(user_login)=upper('".$user_login."') and exists(select count(0) from ra_online_user where upper(user_login)=upper('".$user_login."') and is_desktop=true) order by id desc limit 1;";
  33. $user_type = common::excuteOneSql($sql);
  34. if (!empty($user_type)&&$user_type=="Super User") {
  35. if (strlen($password)<$rule["SuperMinLen"]||strlen($password)>$rule["SuperMaxLen"]) {
  36. $str ="Super user password length between ".$rule["SuperMinLen"]." and ".$rule["SuperMaxLen"];
  37. }
  38. }else{
  39. //校验密码长度
  40. if (strlen($password)<$rule["MinLen"]||strlen($password)>$rule["MaxLen"]) {
  41. $str ="Password length between ".$rule["MinLen"]." and ".$rule["MaxLen"];
  42. }
  43. }
  44. return $str;
  45. }else{
  46. if (preg_match('/^\d*$/', $password) || preg_match('/^[a-zA-Z]+$/', $password)) {
  47. $str ="Must include letters and numbers";
  48. }
  49. $len = strlen($password);
  50. $t = substr($password, 0, 1);
  51. for ($i = 1; $i < $len; $i++) {
  52. $t1 = substr($password, $i, 1);
  53. if ($t != $t1) {
  54. return "";
  55. }
  56. }
  57. return "error";
  58. }
  59. }
  60. //隐藏邮箱地址
  61. public static function maskEmail($email) {
  62. $idex = strlen($email) - strrpos($email, ".");
  63. $mask = substr($email, 0, 1) . str_repeat('*', 6) . "@" . str_repeat('*', 3) . substr($email, -$idex);
  64. return $mask;
  65. }
  66. public static function getInSql($str, $not = false, $sep = ";") {
  67. $str = trim($str);
  68. $str = trim($str, $sep);
  69. $str = trim($str);
  70. if (empty($str) && $str !== "0" && $str !== 0)
  71. return "1<>1";
  72. $str = strtolower($str);
  73. if (utils::checkExist($str, $sep)) {
  74. $aa = explode($sep, $str);
  75. $msg = "";
  76. foreach ($aa as $value) {
  77. $value = trim($value);
  78. if (empty($value))
  79. continue;
  80. if (empty($msg))
  81. $msg = "'" . common::check_input($value) . "'";
  82. else
  83. $msg .= ",'" . common::check_input($value) . "'";
  84. }
  85. if ($not !== FALSE)
  86. return " not in (" . $msg . ")";
  87. else
  88. return " in (" . $msg . ")";
  89. } else {
  90. if ($not !== FALSE)
  91. return " != '" . common::check_input(trim($str)) . "'";
  92. else
  93. return " = '" . common::check_input(trim($str)) . "'";
  94. }
  95. }
  96. public static function checkExist($string, $search, $u = TRUE) {
  97. if ($u === TRUE) {
  98. if (stripos($string, $search) !== false)
  99. return TRUE;
  100. }else {
  101. if (strpos($string, $search) !== false)
  102. return TRUE;
  103. }
  104. return FALSE;
  105. }
  106. public static function endWith($string, $end, $u = TRUE) {
  107. if ($u === TRUE) {
  108. $string = strtolower($string);
  109. $end = strtolower($end);
  110. return strrchr($string, $end) == $end;
  111. }
  112. return strrchr($string, $end) == $end;
  113. }
  114. public static function _get($str) {
  115. $rs = isset($_POST[$str]) ? $_POST[$str] : null;
  116. if (empty($rs))
  117. $rs = isset($_GET[$str]) ? $_GET[$str] : null;
  118. return $rs;
  119. }
  120. public static function startWith($string, $start, $u = TRUE) {
  121. if ($u === TRUE)
  122. return stripos($string, $start) === 0;
  123. return strpos($string, $start) === 0;
  124. }
  125. public static function outDisplay($content, $is_time = 'f', $is_first = 'f', $is_boolean = 'f', $excel_export = FALSE) {
  126. if (empty($content) && $content !== 0 && $content !== "0")
  127. return "";
  128. if (strtolower($is_time) == 't')
  129. return utils::dealTimeDisplay($content);
  130. if (strtolower($is_first) == 't') {
  131. if ($excel_export !== FALSE)
  132. return utils::getCompanyName($content);
  133. else
  134. return '<span title="' . $content . '">' . utils::getCompanyName($content) . '</span>';
  135. }
  136. if (strtolower($is_boolean) == 't')
  137. return utils::outTrue($content);
  138. return nl2br($content);
  139. }
  140. public static function _output($value) {
  141. if (empty($value))
  142. return "&nbsp;";
  143. else
  144. return $value;
  145. }
  146. public static function dealTimeDisplay($date) {
  147. if (empty($date))
  148. return "";
  149. if (strlen($date) > 10)
  150. return date("m/d/Y H:i:s", strtotime($date));
  151. return date("m/d/Y", strtotime($date));
  152. }
  153. public static function outDisplayForMerge($frist,$last,$split = "/") {
  154. if($frist == $last){
  155. return $frist;
  156. }
  157. if (!empty($frist)){
  158. if(!empty($last)){
  159. return $frist.$split.$last;
  160. }else{
  161. return $frist;
  162. }
  163. }else{
  164. return $last;
  165. }
  166. }
  167. public static function outTrue($r) {
  168. if (empty($r))
  169. return "No";
  170. $r = strtolower($r);
  171. if ($r == "t")
  172. return "Yes";
  173. elseif ($r == "f")
  174. return "No";
  175. else
  176. return $r;
  177. }
  178. public static function getCompanyName($detail) {
  179. $detail = nl2br($detail);
  180. if (strpos($detail, '<br />') === FALSE)
  181. return $detail;
  182. return substr($detail, 0, strpos($detail, '<br />'));
  183. }
  184. public static function getEmail($serial_no) {
  185. $ocean = common::excuteObjectSql("select sales_rep, last_user, created_by, order_from, h_bol, consignee, dest_op, agent from public.kln_ocean where md5(serial_no)=md5('$serial_no') "
  186. . "order by schem_not_display nulls last limit 1");
  187. $schema = $ocean["order_from"] . ".";
  188. $dest_op_from_agent = common::excuteOneSql("select dest_op_from_agent from " . $schema . "ocean where md5(serial_no)=md5('$serial_no')");
  189. if ($ocean["agent"] == "KYMTL" || $ocean["agent"] == "KYYYZ") {
  190. $email = array();
  191. $email["email"] = "";
  192. if (!empty($dest_op_from_agent)) {
  193. $so_email = common::excuteOneSql("select email from " . $schema . "employee where employee_id='" . $dest_op_from_agent . "' and active=true");
  194. }
  195. if (!empty($so_email)) {
  196. if (empty($email["email"])) {
  197. $email["email"] = $so_email;
  198. } else {
  199. $email["email"] .= ";" . $so_email;
  200. }
  201. }
  202. if (!empty($ocean["sales_rep"])) {
  203. $rep_email = common::excuteOneSql("select email from " . $schema . "employee where lower(salesopcode)='" . strtolower($ocean["sales_rep"]) . "' and active=true");
  204. if (!empty($rep_email)) {
  205. if (empty($email["email"])) {
  206. $email["email"] = $rep_email;
  207. } else {
  208. $email["email"] .= ";" . $rep_email;
  209. }
  210. }
  211. }
  212. } else {
  213. $email = common::excuteObjectSql("select string_agg(e.email, ';') as email, string_agg(e.first_name, ';') as name from " . $schema . "ra_online_user u, " . $schema . "employee e WHERE u.employee_id = e.employee_id and "
  214. . "lower(u.user_login) in ('" . strtolower($ocean["created_by"]) . "', '" . strtolower($ocean["last_user"]) . "')");
  215. if (empty($dest_op_from_agent)) {
  216. if (!empty($ocean["dest_op"])) {
  217. $so_email = common::excuteOneSql("select email from " . $schema . "employee where employee_id='" . $ocean["dest_op"] . "' and active=true");
  218. }
  219. } else {
  220. $so_email = common::excuteOneSql("select email from " . $schema . "employee where employee_id='" . $dest_op_from_agent . "' and active=true");
  221. }
  222. if (empty($so_email)) {
  223. if ($ocean["agent"] == "APEXSFO") {
  224. $so_email = "oid2@apexshipping.com";
  225. }
  226. if ($ocean["agent"] == "APEXLAX") {
  227. $so_email = "laxoid@apexshipping.com";
  228. }
  229. if ($ocean["agent"] == "APEXNYC") {
  230. $so_email = "NYCOID@APEXSHIPPING.COM";
  231. }
  232. if ($ocean["agent"] == "APEXPNW") {
  233. $so_email = "pnwoid@apexshipping.com";
  234. }
  235. if ($ocean["agent"] == "STLUTA") {
  236. $so_email = "starlinkOID@apexshipping.com ";
  237. }
  238. if ($ocean["agent"] == "APEXORD") {
  239. $so_email = "ordoid@apexshipping.com";
  240. }
  241. }
  242. if (!empty($so_email)) {
  243. if (empty($email["email"])) {
  244. $email["email"] = $so_email;
  245. } else {
  246. $email["email"] .= ";" . $so_email;
  247. }
  248. }
  249. if (!empty($ocean["sales_rep"])) {
  250. $rep_email = common::excuteOneSql("select email from " . $schema . "employee where lower(salesopcode)='" . strtolower($ocean["sales_rep"]) . "' and active=true");
  251. if (!empty($rep_email)) {
  252. if (empty($email["email"])) {
  253. $email["email"] = $rep_email;
  254. } else {
  255. $email["email"] .= ";" . $rep_email;
  256. }
  257. }
  258. }
  259. }
  260. $email["h_bol"] = $ocean["h_bol"];
  261. $email["consignee"] = $ocean["consignee"];
  262. return $email;
  263. }
  264. /***
  265. * 过滤json中的某个数据
  266. * @param unknown $json
  267. * @param unknown $search
  268. * @param unknown $replace
  269. * @return mixed
  270. */
  271. public static function jsonFiltration($search,$replace,$json){
  272. //处理json中将斜杠转义问题
  273. $json = str_replace("\\/", "/", $json);
  274. return str_replace($search, $replace, $json);
  275. }
  276. /*
  277. * calculate eta destination by etd port
  278. */
  279. public static function calculate_ETA_Des($serial_no) {
  280. $sql = "SELECT m_eta as eat, mport_of_discharge as poul, place_of_delivery as pod,service from ocean where lower(serial_no) = '" . strtolower($serial_no) . "'";
  281. $rs = common::excuteObjectSql($sql);
  282. $date = "";
  283. if (!empty($rs['eat'])) {
  284. $date = utils::calculate_ETA_Dest($rs['eat'], $rs['poul'], $rs['pod'], $rs['service']);
  285. }
  286. return $date;
  287. }
  288. public static function calculate_ETA_Dest($eta, $poul, $pod, $service) {
  289. if (empty($poul) || empty($pod))
  290. return $eta;
  291. $sql = "SELECT door_days, cy_days
  292. FROM eta_dest
  293. WHERE eta_dest.state::text = ((( SELECT unlocode.state
  294. FROM ports, unlocode
  295. WHERE ports.uncode::text = unlocode.uncode::text AND ports.code::text = '" . common::check_input($pod) . "'
  296. LIMIT 1))::text) AND (','::text || eta_dest.pod::text) ~~* (('%,'::text || '" . common::check_input($poul) . "') || '%'::text)
  297. LIMIT 1";
  298. //$sql = "select door_days, cy_days from eta_dest where state = (select state from ports where code = '" . common::check_input($poul) . "' limit 1) and ','||pod ilike '%," . common::check_input($pod) . "%'";
  299. $rs = common::excuteObjectSql($sql);
  300. if (empty($rs))
  301. return $eta;
  302. if (utils::endWith($service, "cy"))
  303. return common::addDays($eta, $rs['cy_days']);
  304. else
  305. return common::addDays($eta, $rs['door_days']);
  306. }
  307. /*
  308. * password change, email alert
  309. */
  310. public static function sendEmailByPassword($username, $password, $email, $companyname='') {
  311. $sql = "select subject, ra_content as content from ra_online_email_tpl where lower(ra_type) = 'forgotpw'";
  312. $rs = common::excuteObjectSql($sql);
  313. if (!empty($rs)) {
  314. $subject = $rs['subject'];
  315. $content = $rs['content'];
  316. }
  317. if (!empty($subject) && !empty($content)) {
  318. $content = str_replace('<{username}>', $username, $content);
  319. $content = str_replace('<{password}>', $password, $content);
  320. $content = str_replace('<{companyname}>', $companyname, $content);
  321. global $db;
  322. common::excuteUpdateSql("INSERT INTO public.email_record_forgotpassword(type, title, from_email, to_email, content, insert_date,
  323. cc_email) VALUES ('forgot_password', '" . common::check_input($subject) . "', 'US.KApex.Online@kerryapex.com', '" .
  324. common::check_input($email) . "', '" . common::check_input($content) . "', now(), '');");
  325. return "success";
  326. //return Mail::sendMail($email, $subject, $content);
  327. } else
  328. return null;
  329. }
  330. public static function operation_log_records(){
  331. //排除opreation_log操作
  332. if( empty($_REQUEST["operate"])
  333. || ($_REQUEST["action"] == "login" && $_REQUEST["operate"] == "verifcation_code")
  334. || ($_REQUEST["action"] == "login" && $_REQUEST["operate"] == "check_uname")
  335. || ($_REQUEST["action"] == "ocean_order" && $_REQUEST["operate"] == "setting_ocean_order_display")
  336. || ($_REQUEST["action"] == "ocean_booking" && $_REQUEST["operate"] == "setting_display")){
  337. return;
  338. }
  339. //排除robot的相关的记录
  340. if((stripos($_REQUEST["action"], "robot") === 0)){
  341. return;
  342. }
  343. if($_REQUEST["action"] == "login" && $_REQUEST["operate"] == "tracking_checked"){
  344. //public tracking_checked 的user name 记录对应IP 地址
  345. $user_type = "Customer";
  346. $user_name = common::ip();
  347. } elseif($_REQUEST["action"] == "login" && $_REQUEST["operate"] == "do_login"){
  348. //移除do_login 因为在登录的过程中,是没有用户信息的
  349. $user_name = $_REQUEST["uname"];
  350. } else{
  351. $user_name = _getLoginName();
  352. }
  353. $user_type = _isApexLogin() ? "Employee" : "Customer";
  354. //如果在没有登录前,没有登录信息,指定用户
  355. if(!isset($_SESSION['ONLINE_USER'])){
  356. $user_type = common::excuteOneSql("select user_type from public.ra_online_user u where lower(user_login) = '" . strtolower($user_name) . "'");
  357. }
  358. $operateInfo = utils::getPageByAction($_REQUEST["action"],$_REQUEST["operate"]);
  359. $page = $operateInfo["page"];
  360. $operation = $operateInfo["operate"];
  361. $operation_detail = utils::analyzeOperationDetail($_REQUEST["action"],$_REQUEST["operate"]);
  362. if(empty($operation_detail)){
  363. $operation_detail = common::check_input(utils::jsonFiltration("null", "\"\"", json_encode($_REQUEST)));
  364. }
  365. //过滤一分钟以内,相同用户的重复请求
  366. $exist_sql = "select count(1) from public.customer_service_operation_log
  367. where user_name = '$user_name'
  368. and page = '$page' and operation = '$operation' and operation_detail = '$operation_detail'
  369. and operation_time > NOW() - INTERVAL '1 minute' limit 1;";
  370. $exist_obj = common::excuteOneSql($exist_sql);
  371. if(empty($exist_obj)){
  372. $sql = "INSERT INTO public.customer_service_operation_log(user_type, user_name, page, operation, operation_detail,
  373. operation_time)
  374. VALUES ('$user_type', '$user_name', '$page', '$operation', '$operation_detail', now())";
  375. common::excuteUpdateSql($sql);
  376. }
  377. }
  378. public static function getPageByAction($action,$operate){
  379. //取消
  380. $operationConvertName = array(
  381. "login=do_login" => array("page" =>"Login","operate"=>"Login"),
  382. "login=forgot_password" => array("page" =>"Login","operate"=>"Forgot_PPassword"),
  383. "login=logout" => array("page" =>"logout","operate"=>"logout"),
  384. "login=update_pwd_expires" => array("page" =>"Login","operate"=>"Reset password"),
  385. "ocean_booking=search" => array("page" =>"Booking","operate"=>"Search"),
  386. "Booking_Search=save_setting_display" => array("page" =>"Booking","operate"=>"Customize Coulumns"),
  387. "booking=autody" => array("page" =>"Booking","operate"=>"More Filter"),
  388. "booking=autoport" => array("page" =>"Booking","operate"=>"More Filter"),
  389. "ocean_booking=detail" => array("page" =>"Booking","operate"=>"Open Detailed Page"),
  390. "ocean_booking=excel" => array("page" =>"Booking","operate"=>"Download"),
  391. "ocean_booking=save_communication" => array("page" =>"Booking","operate"=>"Send Email"),
  392. "opreation_log=search" => array("page" =>"Opreation_log","operate"=>"Search"),
  393. "login=tracking_checked" => array("page" =>"Tracking","operate"=>"Public tracking"),
  394. "ocean_order=search" => array("page" =>"Tracking","operate"=>"Search"),
  395. "Ocean_Search=save_setting_display" => array("page" =>"Tracking","operate"=>"Customize Coulumns"),
  396. "tracking=autody" => array("page" =>"Tracking","operate"=>"More Filter"),
  397. "tracking=autoport" => array("page" =>"Tracking","operate"=>"More Filter"),
  398. "ocean_order=detail" => array("page" =>"Tracking","operate"=>"Open Detailed Page"),
  399. "ocean_order=excel" => array("page" =>"Tracking","operate"=>"Download"),
  400. "ocean_order=download" => array("page" =>"Tracking","operate"=>"Download"),
  401. "ocean_order=save_communication" => array("page" =>"Booking","operate"=>"Send Email"),
  402. "ocean_order=ams_isf_log" => array("page" =>"Tracking","operate"=>"AMS/ISF"),
  403. "ocean_order=ocean_vgm" => array("page" =>"Tracking","operate"=>"Enter VGM"),
  404. "ocean_order=save_ocean_vgm" => array("page" =>"Tracking","operate"=>"Save VGM"),
  405. "ocean_order=share_shipment" => array("page" =>"Tracking","operate"=>"Share shipment"),
  406. "ocean_order=document_upload" => array("page" =>"Tracking","operate"=>"document_upload"),
  407. "ocean_order=document_upload_do" => array("page" =>"Tracking","operate"=>"document_upload_do"),
  408. "tools=mark_save" => array("page" =>"Tools","operate"=>"Mark_Save"),
  409. "password=" => array("page" =>"Profile","operate"=>"Change password"));
  410. if($action == "ajax" && $operate == "save_setting_display"){
  411. $model_name = $_REQUEST['model_name'];
  412. return $operationConvertName[$model_name."=".$operate];
  413. }
  414. if($action == "ajax" && ($operate == "autody" || $operate == "autoport")){
  415. $model_name = $_REQUEST['search_mode'];
  416. return $operationConvertName[$model_name."=".$operate];
  417. }
  418. return $operationConvertName[$action."=".$operate];
  419. }
  420. public static function analyzeOperationDetail($action,$operate){
  421. $detail = "";
  422. if($action == "login" && $operate == "do_login"){
  423. $detail = 'System Account';
  424. if($_REQUEST['token']){
  425. $detail = 'From Apex Online';
  426. }
  427. }
  428. if($action == "login" && $operate == "logout"){
  429. $detail = 'User Logout';
  430. }
  431. if($action == "login" && $operate == "tracking_checked"){
  432. $detail = 'Join public tracking action,Public tracking number:'.$_POST['reference_number'];
  433. }
  434. if($action == "password"){
  435. $detail = 'User Change password';
  436. }
  437. if(($action == "ocean_booking" || $action == "ocean_order") && $operate == "search"){
  438. $detail = "";
  439. //还有一个同以分钟内,不记录相同的查询 这个需要建表查询
  440. //{"action":"ocean_booking","operate":"search","_ntype":"ocean_booking","cp":"1","ps":"100","rc":"-1","other_filed":"","uname":"ra.admin","psw":"abc123456789"}
  441. $filter_common_field = array("action","operate","_ntype","cp","ps","rc","other_filed","uname","psw");
  442. foreach($_REQUEST as $selected_key => $selected){
  443. if(!utils::in_array($selected_key, $filter_common_field)){
  444. if(is_array($selected)){
  445. $selected = utils::implode(",",$selected);
  446. }
  447. $detail .="$selected_key:".$selected."; ";
  448. }
  449. }
  450. if(empty($detail)){
  451. $detail .="No search condition";
  452. }
  453. }
  454. if($action == "ajax" && $operate == "save_setting_display"){
  455. $detail = "";
  456. $type = $_REQUEST['model_name'] == "Booking_Search" ? "Booking_Search" : "Ocean_Search";
  457. //记录最终save 和 default 字段相比的结果
  458. // $default_ids = common::excuteListSql("select id,display_name from public.ra_online_search_display_cso where model_name = '$type'
  459. // and display_name in('Booking No.','MBL No.','HBL No.','Mode','Status',
  460. // 'Shipper','Consignee','Origin Agent','Destination Agent','Creation Time','ETD','ETA',
  461. // 'Voyage','Vessel','Week','Created by') order by default_order");
  462. $default_ids = common::excuteListSql("select id,display_name from public.ra_online_search_display_cso where model_name = '$type'
  463. and default_display = true order by default_order");
  464. $ids = utils::implode(";", $_POST['ids']);
  465. $save_ids = common::excuteListSql("select id,display_name from public.ra_online_search_display_cso where model_name = '$type'
  466. and id::text = any(regexp_split_to_array('$ids', ';')) order by default_order");
  467. $detele_detail = "";
  468. foreach($default_ids as $did){
  469. if(!utils::exist_array($did['id'],$save_ids)){
  470. $detele_detail .=$did['display_name']."/";
  471. }
  472. }
  473. $add_detail = "";
  474. foreach($save_ids as $sid){
  475. if(!utils::exist_array($sid['id'],$default_ids)){
  476. $add_detail .=$sid['display_name']."/";
  477. }
  478. }
  479. if(!empty($detele_detail)){
  480. $detail.="Detele fields: (".$detele_detail."). ";
  481. }
  482. if(!empty($add_detail)){
  483. $detail.="Add fields: (".$add_detail."). ";
  484. }
  485. if(empty($detail)){
  486. $detail = "The default field has not changed";
  487. }
  488. }
  489. if(($action == "ocean_booking" || $action == "ocean_order") && $operate == "detail"){
  490. $tabel = $action == "ocean_booking" ? "kln_booking" : "kln_ocean";
  491. $serial_no = common::deCode($_GET['a'], 'D');
  492. $sql = "SELECT booking_no,h_bol from public.$tabel where serial_no = '$serial_no' limit 1";
  493. $data = common::excuteObjectSql($sql);
  494. if(!empty($data['booking_no'])){
  495. $detail = 'Booking No.: '.$data['booking_no'];
  496. }else{
  497. $detail = 'HBOL: '.$data['h_bol'];
  498. }
  499. }
  500. if(($action == "ocean_booking" || $action == "ocean_order") && $operate == "save_communication"){
  501. $text = $_POST["text"];
  502. $detail = urldecode($text);
  503. }
  504. if(($action == "ocean_order") && $operate == "ams_isf_log"){
  505. $detail = "Enter AMS/ISF Page";
  506. }
  507. if(($action == "ocean_booking" || $action == "ocean_order") && $operate == "excel"){
  508. $detail = "Filter_condition:" . $_REQUEST['excel_filter_condition']." Selected Fields:". $_REQUEST['selected_fields'];
  509. }
  510. //Tracking詳情頁download的file(顯示file名稱)
  511. if(($action == "ocean_order") && $operate == "download"){
  512. $filename = common::deCode($_GET['url'], 'D');
  513. $filename = str_replace("/", DIRECTORY_SEPARATOR, $filename);
  514. $filename = str_replace("\\", DIRECTORY_SEPARATOR, $filename);
  515. $display_name = basename($filename);
  516. if (!file_exists($filename)){
  517. $detail = "Tracking Detail Attachment Download But File Not Exist : $display_name";
  518. }else{
  519. $detail = "Tracking Detail Attachment Download: $display_name";
  520. }
  521. }
  522. //Tracking詳情頁Upload Files(顯示file名稱)
  523. if(($action == "ocean_order") && $operate == "document_upload"){
  524. $detail = "Enter Upload Files page";
  525. }
  526. return $detail;
  527. }
  528. public static function calculateTicks($minValue, $maxValue, $targetTickCount = 10) {
  529. $tickSpacing = ($maxValue - $minValue);
  530. $tickSpacing = intval($tickSpacing);
  531. $interval = ceil($tickSpacing / $targetTickCount);
  532. $len = strlen($interval);
  533. if ($len >1){
  534. $interval = ceil($interval/pow(10,$len-1)) *pow(10,$len-1);
  535. }
  536. return $interval;
  537. }
  538. //只记录Public tracking
  539. public static function single_operation_log_save($user_type,$user_name,$page,$operation,$operation_detail){
  540. $sql = "INSERT INTO public.customer_service_operation_log(user_type, user_name, page, operation, operation_detail,
  541. operation_time)
  542. VALUES ('$user_type', '$user_name', '$page', '$operation', '$operation_detail', now())";
  543. common::excuteUpdateSql($sql);
  544. }
  545. public static function uuid() {
  546. return strtoupper(md5(uniqid("", TRUE) . mt_rand()));
  547. }
  548. public static function count($variable){
  549. if (is_array($variable)) {
  550. $count = count($variable);
  551. } else {
  552. $count = 0;
  553. }
  554. return $count;
  555. }
  556. public static function implode($sp,$variable){
  557. $variable = isset($variable) && is_array($variable) ? $variable : array();
  558. return implode($sp, $variable);
  559. }
  560. public static function in_array($str, $arr){
  561. if (is_array($arr)) {
  562. return in_array($str, $arr);
  563. } else {
  564. return false;
  565. }
  566. }
  567. public static function exist_array($key,$arr){
  568. $flag = false;
  569. foreach($arr as $v){
  570. if($v['id'] == $key ){
  571. $flag = true;
  572. }
  573. }
  574. return $flag;
  575. }
  576. public static function getConpanyForNotify($_schemas,$type){
  577. //如果有多個就留空
  578. $company = "";
  579. if($type == 'ocean'){
  580. $company = $_SESSION['ONLINE_USER']['company_name'];
  581. $company_arr = explode(";",$company);
  582. $temp = array();
  583. foreach($company_arr as $v){
  584. if(!empty($v)){
  585. $temp[] = $v;
  586. }
  587. }
  588. if(utils::count($temp) <= 1){
  589. return $company;
  590. }
  591. }
  592. if($type == 'air'){
  593. $company_id = $_SESSION['ONLINE_USER']['air_customers'];
  594. $company_id_arr = explode(";",$company_id);
  595. $temp = array();
  596. foreach($company_id_arr as $v){
  597. if(!empty($v)){
  598. $temp[] = $v;
  599. }
  600. }
  601. if(utils::count($temp) == 1){
  602. if ($_schemas == "public") {//apex ocean和air 分开
  603. $sql = "SELECT company from ocean.contacts where contact_id = '" . common::check_input($temp[0]) . "' ";
  604. } else {
  605. $sql = "SELECT company from $_schemas.contacts where contact_id = '" . common::check_input($temp[0]) . "' ";
  606. }
  607. $company = common::excuteOneSql($sql);
  608. }
  609. return $company;
  610. }
  611. }
  612. public static function getKlnDocNotifyContent($bol,$file_type,$upload_user_name,$upload_user_email,$company,$date_time){
  613. $report_setting = common::excuteObjectSql("select * from ra_online_auto_report_config where report_type = 'KLN_DOC_Notify' ");
  614. $report_content = $report_setting['report_content'];
  615. $columns = common::excuteListSql("select display_name,model_name,database_column_name,excel_width,order_by from public.ra_online_search_display_cso where model_name = 'KLN_DOC_Notify'");
  616. $missing_packing_th = "<tr>";
  617. foreach ($columns as $colk => $colvalue) {
  618. $missing_packing_th.='<td style="width:'.$colvalue['excel_width'].'pt;border:solid black 1.0pt;background:#1F4E78;padding:0cm 5.4pt 0cm 5.4pt;height:14.25pt">
  619. <p class="MsoNormal" align="left" style="text-align:left"><b><span lang="EN-US" style="font-size:8.0pt;font-family:&quot;Arial&quot;,sans-serif;color:white">'.$colvalue['display_name'].'</span></b></p>
  620. </td>';
  621. }
  622. $missing_packing_th .= "</tr>";
  623. $report_content = str_replace('<{missing_packing_th}>', $missing_packing_th, $report_content);
  624. $data = array(array("h_bol"=>$bol,"file_type"=>$file_type,"upload_by"=>$upload_user_name,"email"=>$upload_user_email,"company"=>$company,"upload_time"=>$date_time."(US/Pacific)"));
  625. $missing_packing_tr = "";
  626. foreach ($data as $rk => $rv) {
  627. $missing_packing_tr .= "<tr>";
  628. foreach ($columns as $ck => $cv) {
  629. if(utils::endWith($cv['display_name'], "email")){
  630. $missing_packing_tr.='<td style="font-size:8.0pt;font-family:&quot;Arial&quot;,sans-serif;color:black;border-top:none;
  631. border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:0cm 5.4pt 0cm 5.4pt;height:14.25pt">
  632. <a href="mailto:'.$rv[$cv['database_column_name']].'">'.$rv[$cv['database_column_name']].'</a>
  633. </td>';
  634. }else{
  635. $missing_packing_tr.='<td style="font-size:8.0pt;font-family:&quot;Arial&quot;,sans-serif;color:black;'
  636. . 'border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:0cm 5.4pt 0cm 5.4pt;height:14.25pt">'.$rv[$cv['database_column_name']].'</td>';
  637. }
  638. }
  639. $missing_packing_tr .= "</tr>";
  640. }
  641. $report_content = str_replace('<{missing_packing_tr}>', $missing_packing_tr, $report_content);
  642. return $report_content;
  643. }
  644. public static function _getSql($ids, $type,$shipment_mode,$sqlWhere) {
  645. $ids_arr = explode(',', $ids);
  646. $sql = "";
  647. if($type == "co2e_orgin"){
  648. $str = "SUM(COALESCE(carbon_emission,0)) as catnum ";
  649. $filed = "shippr_uncode";
  650. } else {
  651. $str = "SUM(COALESCE(carbon_emission,0)) as catnum ";
  652. $filed = "consignee_uncode";
  653. }
  654. $shipment_mode_where = " 1=1 ";
  655. //这里处理为空,目前没有数据
  656. $shipment_mode_where = " transport_mode = '$shipment_mode' ";
  657. $shipment_mode_where .= $sqlWhere;
  658. foreach ($ids_arr as $value) {
  659. if (!empty($value)) {
  660. if (empty($sql)) {
  661. $sql .= "SELECT $str FROM public.kln_ocean where $shipment_mode_where and $filed = '$value'";
  662. } else {
  663. $sql .= " union all SELECT $str from public.kln_ocean where $shipment_mode_where and $filed = '$value'";
  664. }
  665. }
  666. }
  667. return $sql;
  668. }
  669. public static function removeDuplicateArray($array){
  670. $result = array();
  671. foreach ($array as $value) {
  672. //过滤可能的空值,会引起前端页面有数据但无法显示
  673. if(!empty($value)){
  674. if (!utils::in_array($value, $result)) {
  675. $result[] = $value;
  676. }
  677. }
  678. }
  679. return $result;
  680. }
  681. public static function hasMacros($filePath) {
  682. $extension = pathinfo($filePath, PATHINFO_EXTENSION);
  683. if ($extension === 'xlsx') {
  684. // 检查 .xlsx 文件
  685. $zip = new ZipArchive();
  686. if ($zip->open($filePath) === TRUE) {
  687. // 检查是否存在 vbaProject.bin 文件
  688. $hasMacros = $zip->locateName('xl/vbaProject.bin') !== false;
  689. $zip->close();
  690. return $hasMacros;
  691. } else {
  692. return false; // 无法打开文件
  693. }
  694. } elseif ($extension === 'docx') {
  695. // 检查 .docx 文件
  696. $zip = new ZipArchive();
  697. if ($zip->open($filePath) === TRUE) {
  698. // 检查是否存在 vbaProject.bin 文件
  699. $hasMacros = $zip->locateName('word/vbaProject.bin') !== false;
  700. $zip->close();
  701. return $hasMacros;
  702. } else {
  703. return false; // 无法打开文件
  704. }
  705. } else {
  706. return false; // 不是支持的文件类型
  707. }
  708. }
  709. public static function arrayKeyToInt($arr){
  710. $ret = array();
  711. foreach($arr as $key => $val){
  712. $ret[] = $val;
  713. }
  714. return $ret;
  715. }
  716. public static function getDailyAndweeklyFrist($arr){
  717. $numericRecords = count($arr);
  718. $ret = array();
  719. $numericRecords_one = 0;
  720. $numericRecords_two = 0;
  721. foreach($arr as $key => $val){
  722. if($key == 0){
  723. $val["numericRecords"] = $numericRecords;
  724. $ret = $val;
  725. }
  726. if($val["notifiation_type"] == "Departure/Arrival_Delay"){
  727. if(utils::checkExist($val["delay_name"],"Departure_Delay")){
  728. $numericRecords_one +=1;
  729. }
  730. if(utils::checkExist($val["delay_name"],"Arrival_Delay")){
  731. $numericRecords_two +=1;
  732. }
  733. }
  734. if($val["notifiation_type"] == "ETD/ETA_Change"){
  735. if(utils::checkExist($val["date_change_name"],"ETD Change")){
  736. $numericRecords_one +=1;
  737. }
  738. if(utils::checkExist($val["date_change_name"],"ETA Change")){
  739. $numericRecords_two +=1;
  740. }
  741. }
  742. }
  743. //对Delay and change 特殊处理
  744. $ret["numericRecords_one"]= $numericRecords_one;
  745. $ret["numericRecords_two"]= $numericRecords_two;
  746. return $ret;
  747. }
  748. /**
  749. * ocean ->sea
  750. */
  751. public static function converModeToDB($shipment_transport_mode_arr){
  752. $converMode = array();
  753. foreach($shipment_transport_mode_arr as $model){
  754. if (strtolower($model) == "ocean"){
  755. $converMode[] = 'sea';
  756. }else{
  757. $converMode[] = strtolower($model);
  758. }
  759. }
  760. return utils::implode(";",$converMode);
  761. }
  762. /**
  763. * sea ->ocean
  764. */
  765. public static function converModeToDisplay($shipment_transport_mode){
  766. //数据转换前端需要的
  767. $converMode = array();
  768. $shipment_transport_mode_arr = explode(";", $shipment_transport_mode);
  769. foreach($shipment_transport_mode_arr as $model){
  770. if (strtolower($model) == "sea"){
  771. $converMode[] = 'Ocean';
  772. }else{
  773. $converMode[] = ucfirst($model);
  774. }
  775. }
  776. return utils::implode(";",$converMode);
  777. }
  778. public static function compareArrayEq($array1,$array2){
  779. $array1 = empty($array1) ? array():$array1;
  780. $array2 = empty($array2) ? array():$array2;
  781. // 使用array_diff比较并重置键名
  782. $diff1 = array_diff($array1, $array2);
  783. $diff2 = array_diff($array2, $array1);
  784. // 如果结果为空,说明两个数组一样
  785. if (empty($diff1) && empty($diff2)) {
  786. return true;
  787. } else {
  788. return false;
  789. }
  790. }
  791. public static function comvertutcinfo($time_zone){
  792. if(!empty($time_zone)){
  793. if(utils::checkExist($time_zone,"+")){
  794. $time_zone = str_replace('+', '-', $time_zone);
  795. }else{
  796. $time_zone = str_replace('-', '+', $time_zone);
  797. }
  798. }
  799. return $time_zone;
  800. }
  801. public static function arrayOrderBykeys($order,$data_kd,$key){
  802. $orderedData = []; // 用于存储按$order排序后的数据
  803. foreach ($order as $name) {
  804. foreach ($data_kd as $item) {
  805. if ($item[$key] == $name) {
  806. $orderedData[] = $item; // 将找到的元素添加到新数组中
  807. break; // 找到后跳出内层循环,继续外层循环处理下一个id
  808. }
  809. }
  810. }
  811. return $orderedData;
  812. }
  813. /**
  814. * 数组去掉null
  815. */
  816. public static function arrayRemoveNull($array){
  817. foreach ($array as &$value) {
  818. if (is_null($value)) {
  819. $value = '';
  820. }
  821. }
  822. unset($value); // 断开 $value 的引用
  823. return $array;
  824. }
  825. /**
  826. * public.kln_ocean 和 WHERE 的位置关系,进行条件拼接
  827. */
  828. public static function modifyString($input,$sqlWhere) {
  829. $search = 'public.kln_ocean';
  830. $pos = strpos($input, $search);
  831. if ($pos !== false) {
  832. $afterSearch = substr($input, $pos + strlen($search));
  833. $hasWhere = (stripos($afterSearch, 'WHERE') !== false);
  834. if ($hasWhere) {
  835. // 在 WHERE 后插入 1=1
  836. $wherePos = stripos($input, 'WHERE', $pos);
  837. $insertPos = $wherePos + strlen('WHERE');
  838. $sqlWhere =' ' .$sqlWhere.' and ';
  839. return substr_replace($input, $sqlWhere, $insertPos, 0);
  840. } else {
  841. // 在 public.kln_ocean 后插入 1=1
  842. $insertPos = $pos + strlen($search);
  843. $sqlWhere =' where ' .$sqlWhere.' ';
  844. return substr_replace($input, $sqlWhere, $insertPos, 0);
  845. }
  846. }
  847. return $input;
  848. }
  849. /**
  850. * LIMIT的处理,或者超过100
  851. * 如果有limit 给最后一个limit修改
  852. * 这个处理不了 写在字段里的子查询(select 1 from aa limit 1) as aa,sql会原样返回
  853. */
  854. public static function processLimitClause($sql,$limit = 100) {
  855. $is_limit = false;
  856. // 去除前后空白
  857. $sql = trim($sql);
  858. // 临时保存字符串内容,防止被误匹配
  859. $placeholder = '__SQL_STRING_PLACEHOLDER__';
  860. $strings = [];
  861. // 匹配字符串(包括单引号和 $$ 符号)
  862. $pattern = "/('(?:[^']|'')*')|(\$(?:.*?)\$)/is";
  863. // 替换所有字符串为占位符,并保存原内容
  864. $cleanSql = preg_replace_callback($pattern, function ($match) use (&$strings, $placeholder) {
  865. $str = $match[1] ?? $match[2];
  866. $index = count($strings);
  867. $strings[$index] = $str;
  868. return $placeholder . $index;
  869. }, $sql);
  870. // 正则匹配所有 LIMIT 子句(支持 LIMIT n 和 LIMIT n OFFSET m)
  871. $pattern = '/\s+LIMIT\s+\d+(\s+OFFSET\s+\d+)?/i';
  872. preg_match_all($pattern, $cleanSql, $matches, PREG_OFFSET_CAPTURE);
  873. if (!empty($matches[0])) {
  874. // 获取最后一个 LIMIT 的位置和内容
  875. $lastMatch = end($matches[0]);
  876. $limitStr = $lastMatch[0]; // 完整的 LIMIT 子句,如 " LIMIT 50" 或 " LIMIT 200 OFFSET 10"
  877. $pos = $lastMatch[1]; // 起始位置
  878. // 提取 LIMIT 的数字部分
  879. preg_match('/\d+/', $limitStr, $numMatch);
  880. $currentLimit = intval($numMatch[0]);
  881. if ($currentLimit < $limit) {
  882. // 当前 LIMIT 值更小,不做修改
  883. $is_limit = true;
  884. }else{
  885. // 构造新的 LIMIT 子句,保留可能存在的 OFFSET
  886. $offsetPart = '';
  887. if (preg_match('/(.*?)(\s+OFFSET\s+\d+)/i', $limitStr, $offsetMatches)) {
  888. $offsetPart = $offsetMatches[2]; // 例如 " OFFSET 10"
  889. }
  890. $newLimitClause = " LIMIT {$limit}{$offsetPart}";
  891. // 替换最后一个 LIMIT
  892. $before = substr($cleanSql, 0, $pos);
  893. $after = substr($cleanSql, $pos + strlen($limitStr));
  894. $cleanSql = $before . $newLimitClause . $after;
  895. }
  896. } else {
  897. // 没有 LIMIT,直接加上
  898. $cleanSql .= " LIMIT {$limit}";
  899. }
  900. // 最后恢复原来的字符串内容
  901. $finalSql = preg_replace_callback("/{$placeholder}(\d+)/", function ($match) use ($strings) {
  902. return $strings[(int)$match[1]];
  903. }, $cleanSql);
  904. return array("sql"=>$finalSql, "is_limit"=>$is_limit);
  905. }
  906. /**
  907. * 替换 single reference
  908. */
  909. public static function replacements($data, $template,$new_sql) {
  910. // 动态构建替换数组(格式:[key] => value)
  911. $replacements = [];
  912. foreach ($data as $key => $value) {
  913. $replacements["{{$key}}"] = $value;
  914. $replacements["{{{$key}}}"] = $value;
  915. }
  916. if(empty($data)){
  917. $fileds = common::extractSelectFields($new_sql);
  918. foreach($fileds as $key){
  919. //如果遇到data没数据,但是有 total_count ,则处理成0
  920. if($key == "total_count"){
  921. $replacements["{{$key}}"] = "0";
  922. $replacements["{{{$key}}}"] = "0";
  923. } else {
  924. $replacements["{{$key}}"] = "";
  925. $replacements["{{{$key}}}"] = "";
  926. }
  927. }
  928. }
  929. // 执行替换
  930. error_log("replacements_single:".json_encode($replacements));
  931. error_log("template_single:".$template);
  932. $result = strtr($template, $replacements);
  933. // 输出结果
  934. return $result;
  935. }
  936. /**
  937. * 替换复杂的reference
  938. *
  939. */
  940. public static function replacementsMultiline($data, $template,$new_sql) {
  941. //行中所有 {{xxx}} 模板变量都必须在 SQL 查询字段中存在
  942. //SQL 中可以有比 reference 多的字段,不影响匹配
  943. //一旦找到第一个符合条件的
  944. //不依赖任何 {{#EACH ROW}} 或其他模板语法
  945. //| {{h_bol}} | {{m_bol}} | {{transport_mode}} | {{service}} | 格式
  946. $explode_data = utils::findFirstTemplateRow($template,$new_sql);
  947. $explode_str = $explode_data['line'];
  948. $replaceTemplate = "";
  949. //检查模板 是否已经带有特定表格的序列
  950. if(!empty($explode_str) && strpos($template, $explode_str) !== false){
  951. $spacing = utils::getMarkDownTableSpacing($template,$explode_str);
  952. $parts = explode($explode_str, $template,2);
  953. // 生成所有行
  954. $generatedRows = [];
  955. foreach ($data as $row) {
  956. $replacements = [];
  957. foreach ($row as $key => $value) {
  958. $replacements["{{{$key}}}"] = $value;
  959. }
  960. $generatedRows[] = strtr($explode_str, $replacements);
  961. }
  962. if(empty($generatedRows) && empty($data)){
  963. $generatedRows[] = "No Data";
  964. }
  965. //如果 SQL字段是有多余未匹配的字段 调用一次个体替换
  966. $mapping = $explode_data['mapping'];
  967. if(!$mapping){
  968. $parts[0] = utils::replacements($data[0],$parts[0],$new_sql);
  969. $parts[1] = utils::replacements($data[0],$parts[1],$new_sql);
  970. }
  971. $replaceTemplate = $parts[0] . implode($spacing, $generatedRows) . $parts[1];
  972. }else{
  973. //全文替换 上面统一有excuteListSql 这里的结果要变一下
  974. $replaceTemplate = utils::replacements($data[0],$template,$new_sql);
  975. }
  976. return $replaceTemplate;
  977. }
  978. // 在 reference 中查找第一个符合要求的 | ... | 行
  979. public static function findFirstTemplateRow($reference, $sql) {
  980. $sqlFields = common::extractSelectFields($sql);
  981. if (empty($sqlFields)) return null;
  982. $lines = preg_split('/\r\n|\r|\n/', $reference);
  983. foreach ($lines as $line) {
  984. $line = trim($line);
  985. // 检查是否是以 | 开头和结尾的表格行
  986. if (strpos($line, '|') !== 0 || substr($line, -1) !== '|') continue;
  987. // 提取该行中的所有 {{xxx}} 模板变量
  988. preg_match_all('/\{\{(\w+)\}\}/', $line, $matches);
  989. $templateVars = $matches[1];
  990. preg_match_all('/(?<=\|)([^|]+)(?=\|)/', $line, $matchesTwo);
  991. // 去除每个匹配项前后的空白字符
  992. $cells = $matchesTwo[1];
  993. if (empty($templateVars) || count($templateVars) <> count($cells)) continue;
  994. // 检查每个变量是否都在 SQL 字段中:这里逻辑是无效的,这里是按模板取的,sql查询有多余字段不影响,也不影响单独去渲染
  995. foreach ($templateVars as $var) {
  996. if (!utils::in_array(strtolower($var), array_map('strtolower', $sqlFields))) {
  997. continue; // 跳出当前循环,继续检查下一行
  998. }
  999. }
  1000. $mapping = true;
  1001. //检查 SQL 字段是否有未匹配的字段
  1002. if(count($sqlFields) <> count($templateVars)){
  1003. $mapping = false;
  1004. }
  1005. // 所有变量都匹配成功,返回这一行
  1006. return array("line"=>$line,"mapping" => $mapping);
  1007. }
  1008. return array("line"=>null,"mapping" =>true);; // 没有找到匹配行
  1009. }
  1010. /**
  1011. * 替换复杂的reference 固定问题 分开
  1012. */
  1013. public static function replacementsFixedMultilineForFixed($data, $template,$explode_str) {
  1014. //| {{h_bol}} | {{m_bol}} | {{transport_mode}} | {{service}} | 格式
  1015. $replaceTemplate = "";
  1016. //检查模板 是否已经带有特定表格的序列
  1017. if(strpos($template, $explode_str) !== false){
  1018. $spacing = utils::getMarkDownTableSpacing($template,$explode_str);
  1019. $parts = explode("$explode_str", $template,2);
  1020. // 生成所有行
  1021. $generatedRows = [];
  1022. foreach ($data as $row) {
  1023. $replacements = [];
  1024. foreach ($row as $key => $value) {
  1025. $replacements["{{{$key}}}"] = $value;
  1026. }
  1027. $generatedRows[] = strtr($explode_str, $replacements);
  1028. }
  1029. $replaceTemplate = $parts[0] . implode($spacing, $generatedRows) . $parts[1];
  1030. }else{
  1031. //有异常,模板原样返回
  1032. $replaceTemplate = $template;
  1033. }
  1034. return $replaceTemplate;
  1035. }
  1036. /**
  1037. * 替换 single reference Fixed
  1038. */
  1039. public static function replacementsFixed($data, $template,$fileds) {
  1040. // 动态构建替换数组(格式:[key] => value)
  1041. $replacements = [];
  1042. foreach ($data as $key => $value) {
  1043. $replacements["{{$key}}"] = $value;
  1044. $replacements["{{{$key}}}"] = $value;
  1045. }
  1046. if(empty($data)){
  1047. foreach($fileds as $key){
  1048. $replacements["{{$key}}"] = "";
  1049. $replacements["{{{$key}}}"] = "";
  1050. }
  1051. }
  1052. // 执行替换
  1053. $result = strtr($template, $replacements);
  1054. // 输出结果
  1055. return $result;
  1056. }
  1057. public static function getMarkDownTableSpacing($str,$search){
  1058. //$str = "|--------------|\n sdsds| E1205546127 | ";
  1059. //$search = "| E1205546127 |";
  1060. // 查找搜索字符串的位置
  1061. $pos = strpos($str, $search);
  1062. if ($pos !== false) {
  1063. // 从搜索字符串前面开始向前查找 "|" 的位置
  1064. for ($i = $pos - 1; $i >= 0; $i--) {
  1065. if ($str[$i] === '|') {
  1066. // 提取两个位置之间的内容
  1067. $result = substr($str, $i + 1, $pos - $i - 1);
  1068. return $result;
  1069. }
  1070. }
  1071. } else {
  1072. return "\n";
  1073. }
  1074. }
  1075. public static function uniqueGroupbyData($unique_filed,$groups_filed,$rows){
  1076. $uniqueData = [];
  1077. $hBolSeen = [];
  1078. //需要去重
  1079. if(!empty($unique_filed)){
  1080. foreach ($rows as $row) {
  1081. $hBol = $row[$unique_filed]."_".$row[$groups_filed];
  1082. if (!isset($hBolSeen[$hBol])) {
  1083. $uniqueData[] = $row;
  1084. $hBolSeen[$hBol] = true;
  1085. }
  1086. }
  1087. } else {
  1088. //不需要去重
  1089. $uniqueData = $rows;
  1090. }
  1091. //分组计数
  1092. $dateGroups = [];
  1093. if(!empty($groups_filed)){
  1094. foreach ($uniqueData as $item) {
  1095. $date = $item[$groups_filed];
  1096. if (!isset($dateGroups[$date])) {
  1097. $dateGroups[$date] = 0;
  1098. }
  1099. $dateGroups[$date]++;
  1100. }
  1101. }
  1102. return $dateGroups;
  1103. }
  1104. public static function getDmoeSqlForAi($type){
  1105. $data= array();
  1106. $data["Show shipments delayed in the last 30 days."] = "select count(*)
  1107. from public.kln_record kr
  1108. inner join LATERAL (select h_bol from public.kln_ocean oo where oo.serial_no = kr.serial_no and <{ExtendHand_KLN}> ) m on true
  1109. where kr.log_type like '%Delay'
  1110. and kr.log_time >= CURRENT_DATE - INTERVAL '30 day'
  1111. and kr.event_date is not null and kr.event_old_date is not null
  1112. and (kr.event_date||' '||COALESCE(kr.event_time,'00:00'))::timestamp >= (kr.event_old_date||' '||COALESCE(kr.event_old_time,'00:00'))::timestamp;select oo.h_bol,oo.place_of_receipt_exp,oo.place_of_delivery_exp,oo.serial_no,oo.order_from,
  1113. kr.log_type,kr.event_old_date, kr.event_old_time,kr.event_date, kr.event_time,
  1114. (EXTRACT(DAY FROM ((event_date||' '||COALESCE(event_time,'00:00'))::timestamp - (event_old_date||' '||COALESCE(event_old_time,'00:00'))::timestamp))) as duration
  1115. from public.kln_record kr
  1116. inner join LATERAL (select h_bol, place_of_receipt_exp, place_of_delivery_exp,serial_no,order_from
  1117. from public.kln_ocean oo where oo.serial_no = kr.serial_no and <{ExtendHand_KLN}> ) oo on true
  1118. where kr.log_type like '%Delay'
  1119. and kr.log_time >= CURRENT_DATE - INTERVAL '30 day'
  1120. and kr.event_date is not null and kr.event_old_date is not null
  1121. and (kr.event_date||' '||COALESCE(kr.event_time,'00:00'))::timestamp >= (kr.event_old_date||' '||COALESCE(kr.event_old_time,'00:00'))::timestamp
  1122. order by kr.log_time desc limit 10";
  1123. $data["Shipments arriving in the next 7 days."] = "select count(*)
  1124. from (
  1125. SELECT oo.serial_no,h_bol, place_of_receipt_exp, place_of_delivery_exp,m.description,eta,order_from, o.cargo_type
  1126. FROM public.kln_ocean oo
  1127. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1128. from public.ocean o where o.serial_no = oo.serial_no) o on true
  1129. left join LATERAL (select a.code,a.description
  1130. from public.ocean_milestone a
  1131. inner join public.customer_service_milestone_sno s
  1132. on a.code = s.code
  1133. and s.type = 'sea'
  1134. and a.serial_no = oo.serial_no
  1135. and a.act_date is not null
  1136. order by s.sno desc limit 1) m on true
  1137. WHERE <{ExtendHand_KLN}> and oo.transport_mode = 'sea' and order_from = 'public' and m.code <> '' limit 10
  1138. ) t;select serial_no,h_bol,place_of_receipt_exp,place_of_delivery_exp,description,eta,order_from,cargo_type
  1139. from (
  1140. SELECT oo.serial_no,h_bol, place_of_receipt_exp, place_of_delivery_exp,m.description,eta,order_from, o.cargo_type
  1141. FROM public.kln_ocean oo
  1142. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1143. from public.ocean o where o.serial_no = oo.serial_no) o on true
  1144. left join LATERAL (select a.code,a.description
  1145. from public.ocean_milestone a
  1146. inner join public.customer_service_milestone_sno s
  1147. on a.code = s.code
  1148. and s.type = 'sea'
  1149. and a.serial_no = oo.serial_no
  1150. and a.act_date is not null
  1151. order by s.sno desc limit 1) m on true
  1152. WHERE <{ExtendHand_KLN}> and oo.transport_mode = 'sea' and order_from = 'public' and m.code <> '' limit 20
  1153. ) t order by eta";
  1154. $data["List shipments with milestone updates in the last 7 days."] = "select count(*)
  1155. from (
  1156. select serial_no
  1157. from (SELECT oo.serial_no from public.ocean_milestone a
  1158. inner join public.customer_service_milestone_sno s on a.code = s.code
  1159. inner join public.kln_ocean oo on oo.serial_no = a.serial_no
  1160. where s.type = 'sea'
  1161. and a.act_date is not null
  1162. ) po
  1163. )t;
  1164. select serial_no,order_from,h_bol, description,update_date_format,update_date,
  1165. COALESCE(m.jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1166. COALESCE(m.jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1167. from (
  1168. select serial_no,order_from,h_bol,description,to_char(update_date,'Mon DD') as update_date_format,update_date,code
  1169. from (SELECT oo.serial_no,oo.order_from,oo.h_bol,s.description,COALESCE(a.update_date, a.create_date) as update_date,a.code
  1170. from public.ocean_milestone a
  1171. inner join public.customer_service_milestone_sno s on a.code = s.code
  1172. inner join public.kln_ocean oo on oo.serial_no = a.serial_no
  1173. where s.type = 'sea'
  1174. and a.act_date is not null
  1175. ) po
  1176. )t left join LATERAL (select public.getTimeAndLocationForKln(serial_no,code,''::text)::jsonb as jsonb_data) m on true
  1177. order by update_date limit 10;
  1178. select aa.update_date_format, COUNT(*) AS total_count
  1179. from (
  1180. select DISTINCT ON (h_bol) h_bol, update_date_format
  1181. from (
  1182. select h_bol,to_char(update_date,'Mon DD') as update_date_format
  1183. from (SELECT oo.h_bol,COALESCE(a.update_date, a.create_date) as update_date
  1184. from public.ocean_milestone a
  1185. inner join public.kln_ocean oo on oo.serial_no = a.serial_no
  1186. where a.act_date is not null
  1187. ) po
  1188. )t order by h_bol
  1189. ) aa
  1190. group by aa.update_date_format order by aa.update_date_format ";
  1191. $data["What is the current status of my active shipments?"] ="SELECT count(*)
  1192. FROM public.kln_ocean oo
  1193. WHERE <{ExtendHand_KLN}> and ((oo.ata is not null and oo.ata >= CURRENT_DATE - INTERVAL '3 months' AND oo.ata < CURRENT_DATE)
  1194. or not exists( select 1 from public.ocean_milestone a where a.serial_no = oo.serial_no and a.act_date is not null and a.code = 'IFFDEL')) and oo.transport_mode = 'sea' and order_from = 'public';with oo as(
  1195. SELECT h_bol, place_of_receipt_exp, place_of_delivery_exp,serial_no,transport_mode,order_from
  1196. FROM public.kln_ocean oo
  1197. WHERE <{ExtendHand_KLN}> and ((oo.ata is not null and oo.ata >= CURRENT_DATE - INTERVAL '3 months' AND oo.ata < CURRENT_DATE)
  1198. or not exists( select 1 from public.ocean_milestone a where a.serial_no = oo.serial_no and a.act_date is not null and a.code = 'IFFDEL')) and oo.transport_mode = 'sea' and order_from = 'public' order by id limit 10
  1199. )
  1200. SELECT oo.*,mil.description,mil.act_date,mil.act_time,o.cargo_type,
  1201. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1202. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1203. from oo
  1204. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1205. from public.ocean o where o.serial_no = oo.serial_no) o on true
  1206. left join LATERAL (select a.code,s.description,to_char(a.act_date, 'YYYY-MM-DD') as act_date ,a.act_time
  1207. from public.ocean_milestone a
  1208. left join public.customer_service_milestone_sno s on a.code = s.code
  1209. and s.type = 'sea'
  1210. and a.serial_no = oo.serial_no
  1211. and a.act_date is not null
  1212. order by s.sno desc limit 1) mil on true
  1213. left join LATERAL (select public.getTimeAndLocationForKln(oo.serial_no,mil.code,''::text)::jsonb as jsonb_data) lt on true
  1214. where oo.transport_mode = 'sea' and order_from = 'public'
  1215. union all
  1216. SELECT oo.*,mil.description,mil.act_date,mil.act_time,o.cargo_type,
  1217. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1218. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1219. from oo
  1220. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1221. from sfs.ocean o where o.serial_no = oo.serial_no) o on true
  1222. left join LATERAL (select a.code,s.description,to_char(a.act_date, 'YYYY-MM-DD') as act_date ,a.act_time
  1223. from public.ocean_milestone a
  1224. left join public.customer_service_milestone_sno s on a.code = s.code
  1225. and s.type = 'air'
  1226. and a.serial_no = oo.serial_no
  1227. and a.act_date is not null
  1228. order by s.sno desc limit 1) mil on true
  1229. left join LATERAL (select public.getTimeAndLocationForKln(oo.serial_no,mil.code,''::text)::jsonb as jsonb_data) lt on true
  1230. where oo.transport_mode = 'sea' and order_from = 'sfs'
  1231. union all
  1232. SELECT oo.*,mil.description,mil.act_date,mil.act_time,o.cargo_type,
  1233. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1234. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1235. from oo
  1236. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1237. from public.ocean o where o.serial_no = oo.serial_no) o on true
  1238. left join LATERAL (select a.code,s.description,to_char(a.act_date, 'YYYY-MM-DD') as act_date ,a.act_time
  1239. from public.air_milestone a
  1240. left join public.customer_service_milestone_sno s on a.code = s.code
  1241. and s.type = 'air'
  1242. and a.serial_no = oo.serial_no
  1243. and a.act_date is not null
  1244. order by s.sno desc limit 1) mil on true
  1245. left join LATERAL (select public.getTimeAndLocationForKln(oo.serial_no,mil.code,''::text)::jsonb as jsonb_data) lt on true
  1246. where oo.transport_mode = 'air' and order_from = 'public'
  1247. union all
  1248. SELECT oo.*,mil.description,mil.act_date,mil.act_time,o.cargo_type,
  1249. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1250. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1251. from oo
  1252. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1253. from sfs.ocean o where o.serial_no = oo.serial_no) o on true
  1254. left join LATERAL (select a.code,s.description,to_char(a.act_date, 'YYYY-MM-DD') as act_date ,a.act_time
  1255. from sfs.air_milestone a
  1256. left join public.customer_service_milestone_sno s on a.code = s.code
  1257. and s.type = 'air'
  1258. and a.serial_no = oo.serial_no
  1259. and a.act_date is not null
  1260. order by s.sno desc limit 1) mil on true
  1261. left join LATERAL (select public.getTimeAndLocationForKln(oo.serial_no,mil.code,''::text)::jsonb as jsonb_data) lt on true
  1262. where oo.transport_mode = 'air' and order_from = 'sfs'";
  1263. $data["List shipments with container status updates in the last 7 days."] = "select count(*)
  1264. FROM ra_online_container_status s
  1265. LEFT JOIN oc_container oc ON s.status_id = oc.status_id
  1266. LEFT JOIN ocean o ON o.serial_no::text = oc.serial_no::text
  1267. LEFT JOIN public.ra_online_edi_event e on s.event_base = e.ra_name
  1268. WHERE o.status::text <> 'Cancelled'::text
  1269. and is_display = true
  1270. and s.insert_date <= CURRENT_DATE AND s.insert_date >='2023-02-23'
  1271. and exists(select 1 from kln_ocean oo where <{ExtendHand_KLN}> and oo.serial_no = o.serial_no);select oo.serial_no,oo.order_from,s.event_base as event,s.container_no,
  1272. to_char(to_timestamp(s.event_date, 'YYYYMMDD'), 'YYYY-MM-DD') as eventdate,
  1273. to_char(to_timestamp(s.event_date, 'YYYYMMDD'),'Mon DD') as _eventdate,
  1274. to_char(to_timestamp(s.event_time, 'HH24MI'), 'HH24:MI') as eventtime,
  1275. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1276. e.description,
  1277. s.event_city as uncity
  1278. FROM ra_online_container_status s
  1279. LEFT JOIN oc_container oc ON s.status_id = oc.status_id
  1280. LEFT JOIN ocean o ON o.serial_no::text = oc.serial_no::text
  1281. LEFT JOIN public.ra_online_edi_event e on s.event_base = e.ra_name
  1282. LEFT JOIN public.kln_ocean oo ON oo.serial_no::text = o.serial_no::text
  1283. WHERE o.status::text <> 'Cancelled'::text
  1284. and is_display = true
  1285. and s.insert_date <= CURRENT_DATE AND s.insert_date >='2023-02-23'
  1286. and exists(select 1 from kln_ocean oo where <{ExtendHand_KLN}> and oo.serial_no = o.serial_no) limit 10;select aa._eventdate, COUNT(*) AS total_count
  1287. from (select DISTINCT ON (s.container_no) s.container_no,
  1288. to_char(to_timestamp(s.event_date, 'YYYYMMDD'),'Mon DD') as _eventdate
  1289. FROM ra_online_container_status s
  1290. LEFT JOIN oc_container oc ON s.status_id = oc.status_id
  1291. LEFT JOIN ocean o ON o.serial_no::text = oc.serial_no::text
  1292. LEFT JOIN public.ra_online_edi_event e on s.event_base = e.ra_name
  1293. WHERE o.status::text <> 'Cancelled'::text
  1294. and is_display = true
  1295. and s.insert_date <= CURRENT_DATE AND s.insert_date >='2023-02-23'
  1296. and exists(select 1 from kln_ocean oo where <{ExtendHand_KLN}> and oo.serial_no = o.serial_no)
  1297. order by s.container_no
  1298. )aa group by _eventdate order by _eventdate";
  1299. $data["Today's shipments summary."] = "select count(*)
  1300. from (
  1301. select oo.serial_no
  1302. from (
  1303. select t.serial_no from (
  1304. SELECT
  1305. a.serial_no,
  1306. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1307. from public.ocean_milestone a
  1308. left join public.customer_service_milestone_sno s on a.code = s.code
  1309. where s.type = 'sea'
  1310. and a.act_date is not null
  1311. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1312. )t WHERE rn = 1
  1313. ) po inner join public.kln_ocean oo on oo.serial_no = po.serial_no and (<{ExtendHand_KLN}>)
  1314. union all
  1315. select oo.serial_no
  1316. from (
  1317. select t.serial_no from (
  1318. SELECT
  1319. a.code,a.serial_no,
  1320. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1321. from public.air_milestone a
  1322. left join public.customer_service_milestone_sno s on a.code = s.code
  1323. where s.type = 'sea'
  1324. and a.act_date is not null
  1325. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1326. )t WHERE rn = 1
  1327. ) pa inner join public.kln_ocean oo on oo.serial_no = pa.serial_no and (<{ExtendHand_KLN}>)
  1328. union all
  1329. select oo.serial_no
  1330. from (
  1331. select t.serial_no from (
  1332. SELECT
  1333. a.serial_no,
  1334. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1335. from sfs.air_milestone a
  1336. left join public.customer_service_milestone_sno s on a.code = s.code
  1337. where s.type = 'sea'
  1338. and a.act_date is not null
  1339. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1340. )t WHERE rn = 1
  1341. ) sa inner join public.kln_ocean oo on oo.serial_no = sa.serial_no and (<{ExtendHand_KLN}>)
  1342. )t;select *
  1343. from (
  1344. select *,oo.serial_no,oo.order_from,oo.h_bol,oo.transport_mode,oo.place_of_receipt_exp, oo.place_of_delivery_exp,
  1345. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1346. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1347. from (
  1348. select *,public.getTimeAndLocationForKln(t.serial_no,t.code,''::text)::jsonb as jsonb_data
  1349. from (
  1350. SELECT
  1351. case when a.code = 'IFFDEP' then 'Departure'
  1352. when a.code = 'IFFARR' then 'Arrived'
  1353. when a.code = 'IFFDEL' then 'Delivered'
  1354. else s.description end as action_type,
  1355. a.update_date,a.code,a.serial_no,
  1356. to_char(a.update_date, 'Mon_DD_YYYY') as _update_date,
  1357. to_char(a.act_date, 'YYYY-MM-DD') as act_date ,
  1358. a.act_time,
  1359. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1360. from public.ocean_milestone a
  1361. left join public.customer_service_milestone_sno s on a.code = s.code
  1362. where s.type = 'sea'
  1363. and a.act_date is not null
  1364. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1365. )t WHERE rn = 1
  1366. ) po inner join public.kln_ocean oo on oo.serial_no = po.serial_no
  1367. union all
  1368. select *,oo.serial_no,oo.order_from,oo.h_bol,oo.transport_mode,oo.place_of_receipt_exp, oo.place_of_delivery_exp,
  1369. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1370. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1371. from (
  1372. select *,public.getTimeAndLocationForKln(t.serial_no,t.code,''::text)::jsonb as jsonb_data
  1373. from (
  1374. SELECT
  1375. case when a.code = 'IFFDEP' then 'Departure'
  1376. when a.code = 'IFFARR' then 'Arrived'
  1377. when a.code = 'IFFDEL' then 'Delivered'
  1378. else s.description end as action_type,
  1379. a.update_date,a.code,a.serial_no,
  1380. to_char(a.update_date, 'Mon_DD_YYYY') as _update_date,
  1381. to_char(a.act_date, 'YYYY-MM-DD') as act_date ,
  1382. a.act_time,
  1383. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1384. from public.air_milestone a
  1385. left join public.customer_service_milestone_sno s on a.code = s.code
  1386. where s.type = 'sea'
  1387. and a.act_date is not null
  1388. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1389. )t WHERE rn = 1
  1390. ) pa inner join public.kln_ocean oo on oo.serial_no = pa.serial_no
  1391. union all
  1392. select *,oo.serial_no,oo.order_from,oo.h_bol,oo.transport_mode,oo.place_of_receipt_exp, oo.place_of_delivery_exp,
  1393. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1394. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1395. from (
  1396. select *,public.getTimeAndLocationForKln(t.serial_no,t.code,''::text)::jsonb as jsonb_data
  1397. from (
  1398. SELECT
  1399. case when a.code = 'IFFDEP' then 'Departure'
  1400. when a.code = 'IFFARR' then 'Arrived'
  1401. when a.code = 'IFFDEL' then 'Delivered'
  1402. else s.description end as action_type,
  1403. a.update_date,a.code,a.serial_no,
  1404. to_char(a.update_date, 'Mon_DD_YYYY') as _update_date,
  1405. to_char(a.act_date, 'YYYY-MM-DD') as act_date ,
  1406. a.act_time,
  1407. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1408. from sfs.air_milestone a
  1409. left join public.customer_service_milestone_sno s on a.code = s.code
  1410. where s.type = 'sea'
  1411. and a.act_date is not null
  1412. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1413. )t WHERE rn = 1
  1414. ) sa inner join public.kln_ocean oo on oo.serial_no = sa.serial_no
  1415. )t limit 10;select sum(case when (action_type='Departure') then 1 else 0 end) as dep,
  1416. sum(case when (action_type='Arrived') then 1 else 0 end) as arr,
  1417. sum(case when (action_type='Delivered') then 1 else 0 end) as del
  1418. from (
  1419. select action_type
  1420. from (
  1421. select t.action_type,t.serial_no from (
  1422. SELECT
  1423. case when a.code = 'IFFDEP' then 'Departure'
  1424. when a.code = 'IFFARR' then 'Arrived'
  1425. when a.code = 'IFFDEL' then 'Delivered'
  1426. else s.description end as action_type,
  1427. a.serial_no,
  1428. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1429. from public.ocean_milestone a
  1430. left join public.customer_service_milestone_sno s on a.code = s.code
  1431. where s.type = 'sea'
  1432. and a.act_date is not null
  1433. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1434. )t WHERE rn = 1
  1435. ) po inner join public.kln_ocean oo on oo.serial_no = po.serial_no and (<{ExtendHand_KLN}>)
  1436. union all
  1437. select action_type
  1438. from (
  1439. select t.action_type,t.serial_no from (
  1440. SELECT
  1441. case when a.code = 'IFFDEP' then 'Departure'
  1442. when a.code = 'IFFARR' then 'Arrived'
  1443. when a.code = 'IFFDEL' then 'Delivered'
  1444. else s.description end as action_type,
  1445. a.serial_no,
  1446. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1447. from public.air_milestone a
  1448. left join public.customer_service_milestone_sno s on a.code = s.code
  1449. where s.type = 'sea'
  1450. and a.act_date is not null
  1451. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1452. )t WHERE rn = 1
  1453. ) pa inner join public.kln_ocean oo on oo.serial_no = pa.serial_no and (<{ExtendHand_KLN}>)
  1454. union all
  1455. select action_type
  1456. from (
  1457. select t.action_type,t.serial_no from (
  1458. SELECT
  1459. case when a.code = 'IFFDEP' then 'Departure'
  1460. when a.code = 'IFFARR' then 'Arrived'
  1461. when a.code = 'IFFDEL' then 'Delivered'
  1462. else s.description end as action_type,
  1463. a.serial_no,
  1464. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1465. from sfs.air_milestone a
  1466. left join public.customer_service_milestone_sno s on a.code = s.code
  1467. where s.type = 'sea'
  1468. and a.act_date is not null
  1469. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1470. )t WHERE rn = 1
  1471. ) sa inner join public.kln_ocean oo on oo.serial_no = sa.serial_no and (<{ExtendHand_KLN}>)
  1472. )t";
  1473. $data["Sort my active shipments by earliest arrival date."] = "select to_char(oo.eta,'DD-Mon') as eta, oo.h_bol,oo.transport_mode, oo.place_of_receipt_exp, oo.place_of_delivery_exp,oo.serial_no,oo.order_from,
  1474. case when oo.eta - CURRENT_DATE <= 0 then '< 1 days'::text
  1475. else (oo.eta - CURRENT_DATE)||' days'::text end as day_to_arr
  1476. from public.kln_ocean oo where 1=1 order by eta limit 10";
  1477. return $data[$type];
  1478. }
  1479. }
  1480. ?>