utils.class.php 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  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. /**
  331. * reset password link email sendEmailByResetPassword
  332. */
  333. public static function sendEmailByResetPassword($data, $email) {
  334. $sql = "select subject, ra_content as content from ra_online_email_tpl where lower(ra_type) = 'kln_reset'";
  335. $rs = common::excuteObjectSql($sql);
  336. if (!empty($rs)) {
  337. $subject = $rs['subject'];
  338. $content = $rs['content'];
  339. }
  340. if (!empty($subject) && !empty($content)) {
  341. $verifcation_code = utils::AES_128_CBC_Encrypt($data['user_login'],"USAIandy20244Q9X","0123456123456789");
  342. //http://localhost:8080/k_new_online/login?state=reset&verifcation_code=XXX
  343. $encoded = rawurlencode($verifcation_code);
  344. $link = SERVER_Vue_PAHT."login?state=reset&name=".$data['user_login']."&verifcation_code=".$encoded;
  345. $tplData = array("username"=>$data['user_login'],
  346. "creation_date"=>$data['current_time'],
  347. "link" =>$link);
  348. // 动态构建替换数组(格式:[key] => value)
  349. $replacements = [];
  350. foreach ($tplData as $key => $value) {
  351. $replacements["{{$key}}"] = $value;
  352. $replacements["{{{$key}}}"] = $value;
  353. }
  354. $content = strtr($content, $replacements);
  355. $content = common::check_input($content);
  356. common::excuteUpdateSql("INSERT INTO public.email_record_forgotpassword(type, title, from_email, to_email, content, insert_date,
  357. cc_email) VALUES ('forgot_password', '" . common::check_input($subject) . "', 'US.KApex.Online@kerryapex.com', '" .
  358. common::check_input($email) . "', '" . $content . "', now(), '');
  359. INSERT INTO public.customer_service_secret_key(secret_key, create_time) VALUES('".$verifcation_code."',now())");
  360. return "success";
  361. //return Mail::sendMail($email, $subject, $content);
  362. } else
  363. return null;
  364. }
  365. /**
  366. * reset password link email sendEmailByResetPassword
  367. */
  368. public static function sendEmailWithPasswordUpdate($user_login, $user_type) {
  369. $sql = "select subject, ra_content as content from ra_online_email_tpl where lower(ra_type) = 'kln_passwordchange'";
  370. $rs = common::excuteObjectSql($sql);
  371. if (!empty($rs)) {
  372. $subject = $rs['subject'];
  373. $content = $rs['content'];
  374. }
  375. if (!empty($subject) && !empty($content)) {
  376. if(strtolower($user_type) == "employee"){
  377. $sql = "SELECT lower(ra_name) as ra_name, ra_value from ra_online_config where lower(ra_name) in ('employee_password_change_cycle')";
  378. } else {
  379. $sql = "SELECT lower(ra_name) as ra_name, ra_value from ra_online_config where lower(ra_name) in ('customer_password_change_cycle')";
  380. }
  381. $PASSWORD_CHANGE_CYCLE = 0;
  382. $rs1s = common::excuteListSql($sql);
  383. foreach ($rs1s as $rs1) {
  384. $PASSWORD_CHANGE_CYCLE = $rs1['ra_value'];
  385. }
  386. $dateInfo = common::excuteObjectSql("select
  387. to_char(now(), 'Mon-DD-YYYY') as current_date,
  388. to_char(now(), 'Mon-DD-YYYY HH:mm:ss') as current_time,
  389. to_char((current_date + INTERVAL '".$PASSWORD_CHANGE_CYCLE." days'),'Mon-DD-YYYY') as expiry_date ;");
  390. $tplData = array("username"=>$user_login,
  391. "creation_date"=>$dateInfo['current_time'],
  392. "update_date"=>$dateInfo['current_date'],
  393. "expiry_date"=>$dateInfo['expiry_date']);
  394. // 动态构建替换数组(格式:[key] => value)
  395. $replacements = [];
  396. foreach ($tplData as $key => $value) {
  397. $replacements["{{$key}}"] = $value;
  398. $replacements["{{{$key}}}"] = $value;
  399. }
  400. $content = strtr($content, $replacements);
  401. $content = common::check_input($content);
  402. $email = _getLoginEamil();
  403. $sql = "INSERT INTO email_record(type, title, from_email, to_email, content, insert_date, cc_email, attachment_path)
  404. VALUES ('kln_passwordChange', '" . common::check_input($subject) . "', 'US.KApex.Online@kerryapex.com', '" .
  405. common::check_input($email) . "', '" . common::check_input($content) . "', now(), '', '');";
  406. common::excuteUpdateSql($sql);
  407. return "success";
  408. } else
  409. return null;
  410. }
  411. public static function operation_log_records(){
  412. //排除opreation_log操作
  413. if( empty($_REQUEST["operate"])
  414. || ($_REQUEST["action"] == "login" && $_REQUEST["operate"] == "verifcation_code")
  415. || ($_REQUEST["action"] == "login" && $_REQUEST["operate"] == "check_uname")
  416. || ($_REQUEST["action"] == "ocean_order" && $_REQUEST["operate"] == "setting_ocean_order_display")
  417. || ($_REQUEST["action"] == "ocean_booking" && $_REQUEST["operate"] == "setting_display")){
  418. return;
  419. }
  420. //排除robot的相关的记录
  421. if((stripos($_REQUEST["action"], "robot") === 0)){
  422. return;
  423. }
  424. if($_REQUEST["action"] == "login" && $_REQUEST["operate"] == "tracking_checked"){
  425. //public tracking_checked 的user name 记录对应IP 地址
  426. $user_type = "Customer";
  427. $user_name = common::ip();
  428. } elseif($_REQUEST["action"] == "login" && $_REQUEST["operate"] == "do_login"){
  429. //移除do_login 因为在登录的过程中,是没有用户信息的
  430. $user_name = $_REQUEST["uname"];
  431. } else{
  432. $user_name = _getLoginName();
  433. }
  434. $user_type = _isApexLogin() ? "Employee" : "Customer";
  435. //如果在没有登录前,没有登录信息,指定用户
  436. if(!isset($_SESSION['ONLINE_USER'])){
  437. $user_type = common::excuteOneSql("select user_type from public.ra_online_user u where lower(user_login) = '" . strtolower($user_name) . "'");
  438. }
  439. $operateInfo = utils::getPageByAction($_REQUEST["action"],$_REQUEST["operate"]);
  440. $page = $operateInfo["page"];
  441. $operation = $operateInfo["operate"];
  442. $operation_detail = utils::analyzeOperationDetail($_REQUEST["action"],$_REQUEST["operate"]);
  443. if(empty($operation_detail)){
  444. $operation_detail = common::check_input(utils::jsonFiltration("null", "\"\"", json_encode($_REQUEST)));
  445. }
  446. //过滤一分钟以内,相同用户的重复请求
  447. $exist_sql = "select count(1) from public.customer_service_operation_log
  448. where user_name = '$user_name'
  449. and page = '$page' and operation = '$operation' and operation_detail = '$operation_detail'
  450. and operation_time > NOW() - INTERVAL '1 minute' limit 1;";
  451. $exist_obj = common::excuteOneSql($exist_sql);
  452. if(empty($exist_obj)){
  453. $sql = "INSERT INTO public.customer_service_operation_log(user_type, user_name, page, operation, operation_detail,
  454. operation_time)
  455. VALUES ('$user_type', '$user_name', '$page', '$operation', '$operation_detail', now())";
  456. common::excuteUpdateSql($sql);
  457. }
  458. }
  459. public static function getPageByAction($action,$operate){
  460. //取消
  461. $operationConvertName = array(
  462. "login=do_login" => array("page" =>"Login","operate"=>"Login"),
  463. "login=forgot_password" => array("page" =>"Login","operate"=>"Forgot_PPassword"),
  464. "login=logout" => array("page" =>"logout","operate"=>"logout"),
  465. "login=update_pwd_expires" => array("page" =>"Login","operate"=>"Reset password"),
  466. "ocean_booking=search" => array("page" =>"Booking","operate"=>"Search"),
  467. "Booking_Search=save_setting_display" => array("page" =>"Booking","operate"=>"Customize Coulumns"),
  468. "booking=autody" => array("page" =>"Booking","operate"=>"More Filter"),
  469. "booking=autoport" => array("page" =>"Booking","operate"=>"More Filter"),
  470. "ocean_booking=detail" => array("page" =>"Booking","operate"=>"Open Detailed Page"),
  471. "ocean_booking=excel" => array("page" =>"Booking","operate"=>"Download"),
  472. "ocean_booking=save_communication" => array("page" =>"Booking","operate"=>"Send Email"),
  473. "opreation_log=search" => array("page" =>"Opreation_log","operate"=>"Search"),
  474. "login=tracking_checked" => array("page" =>"Tracking","operate"=>"Public tracking"),
  475. "ocean_order=search" => array("page" =>"Tracking","operate"=>"Search"),
  476. "Ocean_Search=save_setting_display" => array("page" =>"Tracking","operate"=>"Customize Coulumns"),
  477. "tracking=autody" => array("page" =>"Tracking","operate"=>"More Filter"),
  478. "tracking=autoport" => array("page" =>"Tracking","operate"=>"More Filter"),
  479. "ocean_order=detail" => array("page" =>"Tracking","operate"=>"Open Detailed Page"),
  480. "ocean_order=excel" => array("page" =>"Tracking","operate"=>"Download"),
  481. "ocean_order=download" => array("page" =>"Tracking","operate"=>"Download"),
  482. "ocean_order=save_communication" => array("page" =>"Booking","operate"=>"Send Email"),
  483. "ocean_order=ams_isf_log" => array("page" =>"Tracking","operate"=>"AMS/ISF"),
  484. "ocean_order=ocean_vgm" => array("page" =>"Tracking","operate"=>"Enter VGM"),
  485. "ocean_order=save_ocean_vgm" => array("page" =>"Tracking","operate"=>"Save VGM"),
  486. "ocean_order=share_shipment" => array("page" =>"Tracking","operate"=>"Share shipment"),
  487. "ocean_order=document_upload" => array("page" =>"Tracking","operate"=>"document_upload"),
  488. "ocean_order=document_upload_do" => array("page" =>"Tracking","operate"=>"document_upload_do"),
  489. "tools=mark_save" => array("page" =>"Tools","operate"=>"Mark_Save"),
  490. "password=" => array("page" =>"Profile","operate"=>"Change password"));
  491. if($action == "ajax" && $operate == "save_setting_display"){
  492. $model_name = $_REQUEST['model_name'];
  493. return $operationConvertName[$model_name."=".$operate];
  494. }
  495. if($action == "ajax" && ($operate == "autody" || $operate == "autoport")){
  496. $model_name = $_REQUEST['search_mode'];
  497. return $operationConvertName[$model_name."=".$operate];
  498. }
  499. return $operationConvertName[$action."=".$operate];
  500. }
  501. public static function analyzeOperationDetail($action,$operate){
  502. $detail = "";
  503. if($action == "login" && $operate == "do_login"){
  504. $detail = 'System Account';
  505. if($_REQUEST['token']){
  506. $detail = 'From Apex Online';
  507. }
  508. }
  509. if($action == "login" && $operate == "logout"){
  510. $detail = 'User Logout';
  511. }
  512. if($action == "login" && $operate == "tracking_checked"){
  513. $detail = 'Join public tracking action,Public tracking number:'.$_POST['reference_number'];
  514. }
  515. if($action == "password"){
  516. $detail = 'User Change password';
  517. }
  518. if(($action == "ocean_booking" || $action == "ocean_order") && $operate == "search"){
  519. $detail = "";
  520. //还有一个同以分钟内,不记录相同的查询 这个需要建表查询
  521. //{"action":"ocean_booking","operate":"search","_ntype":"ocean_booking","cp":"1","ps":"100","rc":"-1","other_filed":"","uname":"ra.admin","psw":"abc123456789"}
  522. $filter_common_field = array("action","operate","_ntype","cp","ps","rc","other_filed","uname","psw");
  523. foreach($_REQUEST as $selected_key => $selected){
  524. if(!utils::in_array($selected_key, $filter_common_field)){
  525. if(is_array($selected)){
  526. $selected = utils::implode(",",$selected);
  527. }
  528. $detail .="$selected_key:".$selected."; ";
  529. }
  530. }
  531. if(empty($detail)){
  532. $detail .="No search condition";
  533. }
  534. }
  535. if($action == "ajax" && $operate == "save_setting_display"){
  536. $detail = "";
  537. $type = $_REQUEST['model_name'] == "Booking_Search" ? "Booking_Search" : "Ocean_Search";
  538. //记录最终save 和 default 字段相比的结果
  539. // $default_ids = common::excuteListSql("select id,display_name from public.ra_online_search_display_cso where model_name = '$type'
  540. // and display_name in('Booking No.','MBL No.','HBL No.','Mode','Status',
  541. // 'Shipper','Consignee','Origin Agent','Destination Agent','Creation Time','ETD','ETA',
  542. // 'Voyage','Vessel','Week','Created by') order by default_order");
  543. $default_ids = common::excuteListSql("select id,display_name from public.ra_online_search_display_cso where model_name = '$type'
  544. and default_display = true order by default_order");
  545. $ids = utils::implode(";", $_POST['ids']);
  546. $save_ids = common::excuteListSql("select id,display_name from public.ra_online_search_display_cso where model_name = '$type'
  547. and id::text = any(regexp_split_to_array('$ids', ';')) order by default_order");
  548. $detele_detail = "";
  549. foreach($default_ids as $did){
  550. if(!utils::exist_array($did['id'],$save_ids)){
  551. $detele_detail .=$did['display_name']."/";
  552. }
  553. }
  554. $add_detail = "";
  555. foreach($save_ids as $sid){
  556. if(!utils::exist_array($sid['id'],$default_ids)){
  557. $add_detail .=$sid['display_name']."/";
  558. }
  559. }
  560. if(!empty($detele_detail)){
  561. $detail.="Detele fields: (".$detele_detail."). ";
  562. }
  563. if(!empty($add_detail)){
  564. $detail.="Add fields: (".$add_detail."). ";
  565. }
  566. if(empty($detail)){
  567. $detail = "The default field has not changed";
  568. }
  569. }
  570. if(($action == "ocean_booking" || $action == "ocean_order") && $operate == "detail"){
  571. $tabel = $action == "ocean_booking" ? "kln_booking" : "kln_ocean";
  572. $serial_no = common::deCode($_GET['a'], 'D');
  573. $sql = "SELECT booking_no,h_bol from public.$tabel where serial_no = '$serial_no' limit 1";
  574. $data = common::excuteObjectSql($sql);
  575. if(!empty($data['booking_no'])){
  576. $detail = 'Booking No.: '.$data['booking_no'];
  577. }else{
  578. $detail = 'HBOL: '.$data['h_bol'];
  579. }
  580. }
  581. if(($action == "ocean_booking" || $action == "ocean_order") && $operate == "save_communication"){
  582. $text = $_POST["text"];
  583. $detail = urldecode($text);
  584. }
  585. if(($action == "ocean_order") && $operate == "ams_isf_log"){
  586. $detail = "Enter AMS/ISF Page";
  587. }
  588. if(($action == "ocean_booking" || $action == "ocean_order") && $operate == "excel"){
  589. $detail = "Filter_condition:" . $_REQUEST['excel_filter_condition']." Selected Fields:". $_REQUEST['selected_fields'];
  590. }
  591. //Tracking詳情頁download的file(顯示file名稱)
  592. if(($action == "ocean_order") && $operate == "download"){
  593. $filename = common::deCode($_GET['url'], 'D');
  594. $filename = str_replace("/", DIRECTORY_SEPARATOR, $filename);
  595. $filename = str_replace("\\", DIRECTORY_SEPARATOR, $filename);
  596. $display_name = basename($filename);
  597. if (!file_exists($filename)){
  598. $detail = "Tracking Detail Attachment Download But File Not Exist : $display_name";
  599. }else{
  600. $detail = "Tracking Detail Attachment Download: $display_name";
  601. }
  602. }
  603. //Tracking詳情頁Upload Files(顯示file名稱)
  604. if(($action == "ocean_order") && $operate == "document_upload"){
  605. $detail = "Enter Upload Files page";
  606. }
  607. return $detail;
  608. }
  609. public static function calculateTicks($minValue, $maxValue, $targetTickCount = 10) {
  610. $tickSpacing = ($maxValue - $minValue);
  611. $tickSpacing = intval($tickSpacing);
  612. $interval = ceil($tickSpacing / $targetTickCount);
  613. $len = strlen($interval);
  614. if ($len >1){
  615. $interval = ceil($interval/pow(10,$len-1)) *pow(10,$len-1);
  616. }
  617. return $interval;
  618. }
  619. //只记录Public tracking
  620. public static function single_operation_log_save($user_type,$user_name,$page,$operation,$operation_detail){
  621. $sql = "INSERT INTO public.customer_service_operation_log(user_type, user_name, page, operation, operation_detail,
  622. operation_time)
  623. VALUES ('$user_type', '$user_name', '$page', '$operation', '$operation_detail', now())";
  624. common::excuteUpdateSql($sql);
  625. }
  626. public static function uuid() {
  627. return strtoupper(md5(uniqid("", TRUE) . mt_rand()));
  628. }
  629. public static function count($variable){
  630. if (is_array($variable)) {
  631. $count = count($variable);
  632. } else {
  633. $count = 0;
  634. }
  635. return $count;
  636. }
  637. public static function implode($sp,$variable){
  638. $variable = isset($variable) && is_array($variable) ? $variable : array();
  639. return implode($sp, $variable);
  640. }
  641. public static function in_array($str, $arr){
  642. if (is_array($arr)) {
  643. return in_array($str, $arr);
  644. } else {
  645. return false;
  646. }
  647. }
  648. public static function exist_array($key,$arr){
  649. $flag = false;
  650. foreach($arr as $v){
  651. if($v['id'] == $key ){
  652. $flag = true;
  653. }
  654. }
  655. return $flag;
  656. }
  657. public static function getConpanyForNotify($_schemas,$type){
  658. //如果有多個就留空
  659. $company = "";
  660. if($type == 'ocean'){
  661. $company = $_SESSION['ONLINE_USER']['company_name'];
  662. $company_arr = explode(";",$company);
  663. $temp = array();
  664. foreach($company_arr as $v){
  665. if(!empty($v)){
  666. $temp[] = $v;
  667. }
  668. }
  669. if(utils::count($temp) <= 1){
  670. return $company;
  671. }
  672. }
  673. if($type == 'air'){
  674. $company_id = $_SESSION['ONLINE_USER']['air_customers'];
  675. $company_id_arr = explode(";",$company_id);
  676. $temp = array();
  677. foreach($company_id_arr as $v){
  678. if(!empty($v)){
  679. $temp[] = $v;
  680. }
  681. }
  682. if(utils::count($temp) == 1){
  683. if ($_schemas == "public") {//apex ocean和air 分开
  684. $sql = "SELECT company from ocean.contacts where contact_id = '" . common::check_input($temp[0]) . "' ";
  685. } else {
  686. $sql = "SELECT company from $_schemas.contacts where contact_id = '" . common::check_input($temp[0]) . "' ";
  687. }
  688. $company = common::excuteOneSql($sql);
  689. }
  690. return $company;
  691. }
  692. }
  693. public static function getKlnDocNotifyContent($bol,$file_type,$upload_user_name,$upload_user_email,$company,$date_time){
  694. $report_setting = common::excuteObjectSql("select * from ra_online_auto_report_config where report_type = 'KLN_DOC_Notify' ");
  695. $report_content = $report_setting['report_content'];
  696. $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'");
  697. $missing_packing_th = "<tr>";
  698. foreach ($columns as $colk => $colvalue) {
  699. $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">
  700. <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>
  701. </td>';
  702. }
  703. $missing_packing_th .= "</tr>";
  704. $report_content = str_replace('<{missing_packing_th}>', $missing_packing_th, $report_content);
  705. $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)"));
  706. $missing_packing_tr = "";
  707. foreach ($data as $rk => $rv) {
  708. $missing_packing_tr .= "<tr>";
  709. foreach ($columns as $ck => $cv) {
  710. if(utils::endWith($cv['display_name'], "email")){
  711. $missing_packing_tr.='<td style="font-size:8.0pt;font-family:&quot;Arial&quot;,sans-serif;color:black;border-top:none;
  712. 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">
  713. <a href="mailto:'.$rv[$cv['database_column_name']].'">'.$rv[$cv['database_column_name']].'</a>
  714. </td>';
  715. }else{
  716. $missing_packing_tr.='<td style="font-size:8.0pt;font-family:&quot;Arial&quot;,sans-serif;color:black;'
  717. . '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>';
  718. }
  719. }
  720. $missing_packing_tr .= "</tr>";
  721. }
  722. $report_content = str_replace('<{missing_packing_tr}>', $missing_packing_tr, $report_content);
  723. return $report_content;
  724. }
  725. public static function _getSql($ids, $type,$shipment_mode,$sqlWhere) {
  726. $ids_arr = explode(',', $ids);
  727. $sql = "";
  728. if($type == "co2e_orgin"){
  729. $str = "SUM(COALESCE(carbon_emission,0)) as catnum ";
  730. $filed = "shippr_uncode";
  731. } else {
  732. $str = "SUM(COALESCE(carbon_emission,0)) as catnum ";
  733. $filed = "consignee_uncode";
  734. }
  735. $shipment_mode_where = " 1=1 ";
  736. //这里处理为空,目前没有数据
  737. $shipment_mode_where = " transport_mode = '$shipment_mode' ";
  738. $shipment_mode_where .= $sqlWhere;
  739. foreach ($ids_arr as $value) {
  740. if (!empty($value)) {
  741. if (empty($sql)) {
  742. $sql .= "SELECT $str FROM public.kln_ocean where $shipment_mode_where and $filed = '$value'";
  743. } else {
  744. $sql .= " union all SELECT $str from public.kln_ocean where $shipment_mode_where and $filed = '$value'";
  745. }
  746. }
  747. }
  748. return $sql;
  749. }
  750. public static function removeDuplicateArray($array){
  751. $result = array();
  752. foreach ($array as $value) {
  753. //过滤可能的空值,会引起前端页面有数据但无法显示
  754. if(!empty($value)){
  755. if (!utils::in_array($value, $result)) {
  756. $result[] = $value;
  757. }
  758. }
  759. }
  760. return $result;
  761. }
  762. public static function hasMacros($filePath) {
  763. $extension = pathinfo($filePath, PATHINFO_EXTENSION);
  764. if ($extension === 'xlsx') {
  765. // 检查 .xlsx 文件
  766. $zip = new ZipArchive();
  767. if ($zip->open($filePath) === TRUE) {
  768. // 检查是否存在 vbaProject.bin 文件
  769. $hasMacros = $zip->locateName('xl/vbaProject.bin') !== false;
  770. $zip->close();
  771. return $hasMacros;
  772. } else {
  773. return false; // 无法打开文件
  774. }
  775. } elseif ($extension === 'docx') {
  776. // 检查 .docx 文件
  777. $zip = new ZipArchive();
  778. if ($zip->open($filePath) === TRUE) {
  779. // 检查是否存在 vbaProject.bin 文件
  780. $hasMacros = $zip->locateName('word/vbaProject.bin') !== false;
  781. $zip->close();
  782. return $hasMacros;
  783. } else {
  784. return false; // 无法打开文件
  785. }
  786. } else {
  787. return false; // 不是支持的文件类型
  788. }
  789. }
  790. public static function arrayKeyToInt($arr){
  791. $ret = array();
  792. foreach($arr as $key => $val){
  793. $ret[] = $val;
  794. }
  795. return $ret;
  796. }
  797. public static function getDailyAndweeklyFrist($arr){
  798. $numericRecords = count($arr);
  799. $ret = array();
  800. $numericRecords_one = 0;
  801. $numericRecords_two = 0;
  802. foreach($arr as $key => $val){
  803. if($key == 0){
  804. $val["numericRecords"] = $numericRecords;
  805. $ret = $val;
  806. }
  807. if($val["notifiation_type"] == "Departure/Arrival_Delay"){
  808. if(utils::checkExist($val["delay_name"],"Departure_Delay")){
  809. $numericRecords_one +=1;
  810. }
  811. if(utils::checkExist($val["delay_name"],"Arrival_Delay")){
  812. $numericRecords_two +=1;
  813. }
  814. }
  815. if($val["notifiation_type"] == "ETD/ETA_Change"){
  816. if(utils::checkExist($val["date_change_name"],"ETD Change")){
  817. $numericRecords_one +=1;
  818. }
  819. if(utils::checkExist($val["date_change_name"],"ETA Change")){
  820. $numericRecords_two +=1;
  821. }
  822. }
  823. }
  824. //对Delay and change 特殊处理
  825. $ret["numericRecords_one"]= $numericRecords_one;
  826. $ret["numericRecords_two"]= $numericRecords_two;
  827. return $ret;
  828. }
  829. /**
  830. * ocean ->sea
  831. */
  832. public static function converModeToDB($shipment_transport_mode_arr){
  833. $converMode = array();
  834. foreach($shipment_transport_mode_arr as $model){
  835. if (strtolower($model) == "ocean"){
  836. $converMode[] = 'sea';
  837. }else{
  838. $converMode[] = strtolower($model);
  839. }
  840. }
  841. return utils::implode(";",$converMode);
  842. }
  843. /**
  844. * sea ->ocean
  845. */
  846. public static function converModeToDisplay($shipment_transport_mode){
  847. //数据转换前端需要的
  848. $converMode = array();
  849. $shipment_transport_mode_arr = explode(";", $shipment_transport_mode);
  850. foreach($shipment_transport_mode_arr as $model){
  851. if (strtolower($model) == "sea"){
  852. $converMode[] = 'Ocean';
  853. }else{
  854. $converMode[] = ucfirst($model);
  855. }
  856. }
  857. return utils::implode(";",$converMode);
  858. }
  859. public static function compareArrayEq($array1,$array2){
  860. $array1 = empty($array1) ? array():$array1;
  861. $array2 = empty($array2) ? array():$array2;
  862. // 使用array_diff比较并重置键名
  863. $diff1 = array_diff($array1, $array2);
  864. $diff2 = array_diff($array2, $array1);
  865. // 如果结果为空,说明两个数组一样
  866. if (empty($diff1) && empty($diff2)) {
  867. return true;
  868. } else {
  869. return false;
  870. }
  871. }
  872. public static function comvertutcinfo($time_zone){
  873. if(!empty($time_zone)){
  874. if(utils::checkExist($time_zone,"+")){
  875. $time_zone = str_replace('+', '-', $time_zone);
  876. }else{
  877. $time_zone = str_replace('-', '+', $time_zone);
  878. }
  879. }
  880. return $time_zone;
  881. }
  882. public static function arrayOrderBykeys($order,$data_kd,$key){
  883. $orderedData = []; // 用于存储按$order排序后的数据
  884. foreach ($order as $name) {
  885. foreach ($data_kd as $item) {
  886. if ($item[$key] == $name) {
  887. $orderedData[] = $item; // 将找到的元素添加到新数组中
  888. break; // 找到后跳出内层循环,继续外层循环处理下一个id
  889. }
  890. }
  891. }
  892. return $orderedData;
  893. }
  894. /**
  895. * 数组去掉null
  896. */
  897. public static function arrayRemoveNull($array){
  898. foreach ($array as &$value) {
  899. if (is_null($value)) {
  900. $value = '';
  901. }
  902. }
  903. unset($value); // 断开 $value 的引用
  904. return $array;
  905. }
  906. /**
  907. * public.kln_ocean 和 WHERE 的位置关系,进行条件拼接
  908. */
  909. public static function modifyString($input,$sqlWhere) {
  910. $search = 'public.kln_ocean';
  911. $pos = strpos($input, $search);
  912. if ($pos !== false) {
  913. $afterSearch = substr($input, $pos + strlen($search));
  914. $hasWhere = (stripos($afterSearch, 'WHERE') !== false);
  915. if ($hasWhere) {
  916. // 在 WHERE 后插入 1=1
  917. $wherePos = stripos($input, 'WHERE', $pos);
  918. $insertPos = $wherePos + strlen('WHERE');
  919. $sqlWhere =' ' .$sqlWhere.' and ';
  920. return substr_replace($input, $sqlWhere, $insertPos, 0);
  921. } else {
  922. // 在 public.kln_ocean 后插入 1=1
  923. $insertPos = $pos + strlen($search);
  924. $sqlWhere =' where ' .$sqlWhere.' ';
  925. return substr_replace($input, $sqlWhere, $insertPos, 0);
  926. }
  927. }
  928. return $input;
  929. }
  930. /**
  931. * LIMIT的处理,或者超过100
  932. * 如果有limit 给最后一个limit修改
  933. * 这个处理不了 写在字段里的子查询(select 1 from aa limit 1) as aa,sql会原样返回
  934. */
  935. public static function processLimitClause($sql,$limit = 100) {
  936. $is_limit = false;
  937. // 去除前后空白
  938. $sql = trim($sql);
  939. // 临时保存字符串内容,防止被误匹配
  940. $placeholder = '__SQL_STRING_PLACEHOLDER__';
  941. $strings = [];
  942. // 匹配字符串(包括单引号和 $$ 符号)
  943. $pattern = "/('(?:[^']|'')*')|(\$(?:.*?)\$)/is";
  944. // 替换所有字符串为占位符,并保存原内容
  945. $cleanSql = preg_replace_callback($pattern, function ($match) use (&$strings, $placeholder) {
  946. $str = $match[1] ?? $match[2];
  947. $index = count($strings);
  948. $strings[$index] = $str;
  949. return $placeholder . $index;
  950. }, $sql);
  951. // 正则匹配所有 LIMIT 子句(支持 LIMIT n 和 LIMIT n OFFSET m)
  952. $pattern = '/\s+LIMIT\s+\d+(\s+OFFSET\s+\d+)?/i';
  953. preg_match_all($pattern, $cleanSql, $matches, PREG_OFFSET_CAPTURE);
  954. if (!empty($matches[0])) {
  955. // 获取最后一个 LIMIT 的位置和内容
  956. $lastMatch = end($matches[0]);
  957. $limitStr = $lastMatch[0]; // 完整的 LIMIT 子句,如 " LIMIT 50" 或 " LIMIT 200 OFFSET 10"
  958. $pos = $lastMatch[1]; // 起始位置
  959. // 提取 LIMIT 的数字部分
  960. preg_match('/\d+/', $limitStr, $numMatch);
  961. $currentLimit = intval($numMatch[0]);
  962. if ($currentLimit < $limit) {
  963. // 当前 LIMIT 值更小,不做修改
  964. $is_limit = true;
  965. }else{
  966. // 构造新的 LIMIT 子句,保留可能存在的 OFFSET
  967. $offsetPart = '';
  968. if (preg_match('/(.*?)(\s+OFFSET\s+\d+)/i', $limitStr, $offsetMatches)) {
  969. $offsetPart = $offsetMatches[2]; // 例如 " OFFSET 10"
  970. }
  971. $newLimitClause = " LIMIT {$limit}{$offsetPart}";
  972. // 替换最后一个 LIMIT
  973. $before = substr($cleanSql, 0, $pos);
  974. $after = substr($cleanSql, $pos + strlen($limitStr));
  975. $cleanSql = $before . $newLimitClause . $after;
  976. }
  977. } else {
  978. // 没有 LIMIT,直接加上
  979. $cleanSql .= " LIMIT {$limit}";
  980. }
  981. // 最后恢复原来的字符串内容
  982. $finalSql = preg_replace_callback("/{$placeholder}(\d+)/", function ($match) use ($strings) {
  983. return $strings[(int)$match[1]];
  984. }, $cleanSql);
  985. return array("sql"=>$finalSql, "is_limit"=>$is_limit);
  986. }
  987. /**
  988. * 替换 single reference
  989. */
  990. public static function replacements($data, $template,$new_sql) {
  991. // 动态构建替换数组(格式:[key] => value)
  992. $replacements = [];
  993. foreach ($data as $key => $value) {
  994. $replacements["{{$key}}"] = $value;
  995. $replacements["{{{$key}}}"] = $value;
  996. }
  997. if(empty($data)){
  998. $fileds = common::extractSelectFields($new_sql);
  999. foreach($fileds as $key){
  1000. //如果遇到data没数据,但是有 total_count ,则处理成0
  1001. if($key == "total_count"){
  1002. $replacements["{{$key}}"] = "0";
  1003. $replacements["{{{$key}}}"] = "0";
  1004. } else {
  1005. $replacements["{{$key}}"] = "";
  1006. $replacements["{{{$key}}}"] = "";
  1007. }
  1008. }
  1009. }
  1010. // 执行替换
  1011. error_log("replacements_single:".json_encode($replacements));
  1012. error_log("template_single:".$template);
  1013. $result = strtr($template, $replacements);
  1014. // 输出结果
  1015. return $result;
  1016. }
  1017. /**
  1018. * 替换复杂的reference
  1019. *
  1020. */
  1021. public static function replacementsMultiline($data, $template,$new_sql) {
  1022. //行中所有 {{xxx}} 模板变量都必须在 SQL 查询字段中存在
  1023. //SQL 中可以有比 reference 多的字段,不影响匹配
  1024. //一旦找到第一个符合条件的
  1025. //不依赖任何 {{#EACH ROW}} 或其他模板语法
  1026. //| {{h_bol}} | {{m_bol}} | {{transport_mode}} | {{service}} | 格式
  1027. $explode_data = utils::findFirstTemplateRow($template,$new_sql);
  1028. $explode_str = $explode_data['line'];
  1029. $replaceTemplate = "";
  1030. //检查模板 是否已经带有特定表格的序列
  1031. if(!empty($explode_str) && strpos($template, $explode_str) !== false){
  1032. $spacing = utils::getMarkDownTableSpacing($template,$explode_str);
  1033. $parts = explode($explode_str, $template,2);
  1034. // 生成所有行
  1035. $generatedRows = [];
  1036. foreach ($data as $row) {
  1037. $replacements = [];
  1038. foreach ($row as $key => $value) {
  1039. $replacements["{{{$key}}}"] = $value;
  1040. }
  1041. $generatedRows[] = strtr($explode_str, $replacements);
  1042. }
  1043. if(empty($generatedRows) && empty($data)){
  1044. $generatedRows[] = "No Data";
  1045. }
  1046. //如果 SQL字段是有多余未匹配的字段 调用一次个体替换
  1047. $mapping = $explode_data['mapping'];
  1048. if(!$mapping){
  1049. $parts[0] = utils::replacements($data[0],$parts[0],$new_sql);
  1050. $parts[1] = utils::replacements($data[0],$parts[1],$new_sql);
  1051. }
  1052. $replaceTemplate = $parts[0] . implode($spacing, $generatedRows) . $parts[1];
  1053. }else{
  1054. //全文替换 上面统一有excuteListSql 这里的结果要变一下
  1055. $replaceTemplate = utils::replacements($data[0],$template,$new_sql);
  1056. }
  1057. return $replaceTemplate;
  1058. }
  1059. // 在 reference 中查找第一个符合要求的 | ... | 行
  1060. public static function findFirstTemplateRow($reference, $sql) {
  1061. $sqlFields = common::extractSelectFields($sql);
  1062. if (empty($sqlFields)) return null;
  1063. $lines = preg_split('/\r\n|\r|\n/', $reference);
  1064. foreach ($lines as $line) {
  1065. $line = trim($line);
  1066. // 检查是否是以 | 开头和结尾的表格行
  1067. if (strpos($line, '|') !== 0 || substr($line, -1) !== '|') continue;
  1068. // 提取该行中的所有 {{xxx}} 模板变量
  1069. preg_match_all('/\{\{(\w+)\}\}/', $line, $matches);
  1070. $templateVars = $matches[1];
  1071. preg_match_all('/(?<=\|)([^|]+)(?=\|)/', $line, $matchesTwo);
  1072. // 去除每个匹配项前后的空白字符
  1073. $cells = $matchesTwo[1];
  1074. if (empty($templateVars) || count($templateVars) <> count($cells)) continue;
  1075. // 检查每个变量是否都在 SQL 字段中:这里逻辑是无效的,这里是按模板取的,sql查询有多余字段不影响,也不影响单独去渲染
  1076. foreach ($templateVars as $var) {
  1077. if (!utils::in_array(strtolower($var), array_map('strtolower', $sqlFields))) {
  1078. continue; // 跳出当前循环,继续检查下一行
  1079. }
  1080. }
  1081. $mapping = true;
  1082. //检查 SQL 字段是否有未匹配的字段
  1083. if(count($sqlFields) <> count($templateVars)){
  1084. $mapping = false;
  1085. }
  1086. // 所有变量都匹配成功,返回这一行
  1087. return array("line"=>$line,"mapping" => $mapping);
  1088. }
  1089. return array("line"=>null,"mapping" =>true);; // 没有找到匹配行
  1090. }
  1091. /**
  1092. * 替换复杂的reference 固定问题 分开
  1093. */
  1094. public static function replacementsFixedMultilineForFixed($data, $template,$explode_str) {
  1095. //| {{h_bol}} | {{m_bol}} | {{transport_mode}} | {{service}} | 格式
  1096. $replaceTemplate = "";
  1097. //检查模板 是否已经带有特定表格的序列
  1098. if(strpos($template, $explode_str) !== false){
  1099. $spacing = utils::getMarkDownTableSpacing($template,$explode_str);
  1100. $parts = explode("$explode_str", $template,2);
  1101. // 生成所有行
  1102. $generatedRows = [];
  1103. foreach ($data as $row) {
  1104. $replacements = [];
  1105. foreach ($row as $key => $value) {
  1106. $replacements["{{{$key}}}"] = $value;
  1107. }
  1108. $generatedRows[] = strtr($explode_str, $replacements);
  1109. }
  1110. $replaceTemplate = $parts[0] . implode($spacing, $generatedRows) . $parts[1];
  1111. }else{
  1112. //有异常,模板原样返回
  1113. $replaceTemplate = $template;
  1114. }
  1115. return $replaceTemplate;
  1116. }
  1117. /**
  1118. * 替换 single reference Fixed
  1119. */
  1120. public static function replacementsFixed($data, $template,$fileds) {
  1121. // 动态构建替换数组(格式:[key] => value)
  1122. $replacements = [];
  1123. foreach ($data as $key => $value) {
  1124. $replacements["{{$key}}"] = $value;
  1125. $replacements["{{{$key}}}"] = $value;
  1126. }
  1127. if(empty($data)){
  1128. foreach($fileds as $key){
  1129. $replacements["{{$key}}"] = "";
  1130. $replacements["{{{$key}}}"] = "";
  1131. }
  1132. }
  1133. // 执行替换
  1134. $result = strtr($template, $replacements);
  1135. // 输出结果
  1136. return $result;
  1137. }
  1138. public static function getMarkDownTableSpacing($str,$search){
  1139. //$str = "|--------------|\n sdsds| E1205546127 | ";
  1140. //$search = "| E1205546127 |";
  1141. // 查找搜索字符串的位置
  1142. $pos = strpos($str, $search);
  1143. if ($pos !== false) {
  1144. // 从搜索字符串前面开始向前查找 "|" 的位置
  1145. for ($i = $pos - 1; $i >= 0; $i--) {
  1146. if ($str[$i] === '|') {
  1147. // 提取两个位置之间的内容
  1148. $result = substr($str, $i + 1, $pos - $i - 1);
  1149. return $result;
  1150. }
  1151. }
  1152. } else {
  1153. return "\n";
  1154. }
  1155. }
  1156. public static function uniqueGroupbyData($unique_filed,$groups_filed,$rows){
  1157. $uniqueData = [];
  1158. $hBolSeen = [];
  1159. //需要去重
  1160. if(!empty($unique_filed)){
  1161. foreach ($rows as $row) {
  1162. $hBol = $row[$unique_filed]."_".$row[$groups_filed];
  1163. if (!isset($hBolSeen[$hBol])) {
  1164. $uniqueData[] = $row;
  1165. $hBolSeen[$hBol] = true;
  1166. }
  1167. }
  1168. } else {
  1169. //不需要去重
  1170. $uniqueData = $rows;
  1171. }
  1172. //分组计数
  1173. $dateGroups = [];
  1174. if(!empty($groups_filed)){
  1175. foreach ($uniqueData as $item) {
  1176. $date = $item[$groups_filed];
  1177. if (!isset($dateGroups[$date])) {
  1178. $dateGroups[$date] = 0;
  1179. }
  1180. $dateGroups[$date]++;
  1181. }
  1182. }
  1183. return $dateGroups;
  1184. }
  1185. public static function getDmoeSqlForAi($type){
  1186. $data= array();
  1187. $data["Show shipments delayed in the last 30 days."] = "select count(*)
  1188. from public.kln_record kr
  1189. inner join LATERAL (select h_bol from public.kln_ocean oo where oo.serial_no = kr.serial_no and <{ExtendHand_KLN}> ) m on true
  1190. where kr.log_type like '%Delay'
  1191. and kr.log_time >= CURRENT_DATE - INTERVAL '30 day'
  1192. and kr.event_date is not null and kr.event_old_date is not null
  1193. 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,
  1194. kr.log_type,kr.event_old_date, kr.event_old_time,kr.event_date, kr.event_time,
  1195. (EXTRACT(DAY FROM ((event_date||' '||COALESCE(event_time,'00:00'))::timestamp - (event_old_date||' '||COALESCE(event_old_time,'00:00'))::timestamp))) as duration
  1196. from public.kln_record kr
  1197. inner join LATERAL (select h_bol, place_of_receipt_exp, place_of_delivery_exp,serial_no,order_from
  1198. from public.kln_ocean oo where oo.serial_no = kr.serial_no and <{ExtendHand_KLN}> ) oo on true
  1199. where kr.log_type like '%Delay'
  1200. and kr.log_time >= CURRENT_DATE - INTERVAL '30 day'
  1201. and kr.event_date is not null and kr.event_old_date is not null
  1202. and (kr.event_date||' '||COALESCE(kr.event_time,'00:00'))::timestamp >= (kr.event_old_date||' '||COALESCE(kr.event_old_time,'00:00'))::timestamp
  1203. order by kr.log_time desc limit 10";
  1204. $data["Shipments arriving in the next 7 days."] = "select count(*)
  1205. from (
  1206. SELECT oo.serial_no,h_bol, place_of_receipt_exp, place_of_delivery_exp,m.description,eta,order_from, o.cargo_type
  1207. FROM public.kln_ocean oo
  1208. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1209. from public.ocean o where o.serial_no = oo.serial_no) o on true
  1210. left join LATERAL (select a.code,a.description
  1211. from public.ocean_milestone a
  1212. inner join public.customer_service_milestone_sno s
  1213. on a.code = s.code
  1214. and s.type = 'sea'
  1215. and a.serial_no = oo.serial_no
  1216. and a.act_date is not null
  1217. order by s.sno desc limit 1) m on true
  1218. WHERE <{ExtendHand_KLN}> and oo.transport_mode = 'sea' and order_from = 'public' and m.code <> '' limit 10
  1219. ) t;select serial_no,h_bol,place_of_receipt_exp,place_of_delivery_exp,description,eta,order_from,cargo_type
  1220. from (
  1221. SELECT oo.serial_no,h_bol, place_of_receipt_exp, place_of_delivery_exp,m.description,eta,order_from, o.cargo_type
  1222. FROM public.kln_ocean oo
  1223. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1224. from public.ocean o where o.serial_no = oo.serial_no) o on true
  1225. left join LATERAL (select a.code,a.description
  1226. from public.ocean_milestone a
  1227. inner join public.customer_service_milestone_sno s
  1228. on a.code = s.code
  1229. and s.type = 'sea'
  1230. and a.serial_no = oo.serial_no
  1231. and a.act_date is not null
  1232. order by s.sno desc limit 1) m on true
  1233. WHERE <{ExtendHand_KLN}> and oo.transport_mode = 'sea' and order_from = 'public' and m.code <> '' limit 20
  1234. ) t order by eta";
  1235. $data["List shipments with milestone updates in the last 7 days."] = "select count(*)
  1236. from (
  1237. select serial_no
  1238. from (SELECT oo.serial_no from public.ocean_milestone a
  1239. inner join public.customer_service_milestone_sno s on a.code = s.code
  1240. inner join public.kln_ocean oo on oo.serial_no = a.serial_no
  1241. where s.type = 'sea'
  1242. and a.act_date is not null
  1243. ) po
  1244. )t;
  1245. select serial_no,order_from,h_bol, description,update_date_format,update_date,
  1246. COALESCE(m.jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1247. COALESCE(m.jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1248. from (
  1249. select serial_no,order_from,h_bol,description,to_char(update_date,'Mon DD') as update_date_format,update_date,code
  1250. 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
  1251. from public.ocean_milestone a
  1252. inner join public.customer_service_milestone_sno s on a.code = s.code
  1253. inner join public.kln_ocean oo on oo.serial_no = a.serial_no
  1254. where s.type = 'sea'
  1255. and a.act_date is not null
  1256. ) po
  1257. )t left join LATERAL (select public.getTimeAndLocationForKln(serial_no,code,''::text)::jsonb as jsonb_data) m on true
  1258. order by update_date limit 10;
  1259. select aa.update_date_format, COUNT(*) AS total_count
  1260. from (
  1261. select DISTINCT ON (h_bol) h_bol, update_date_format
  1262. from (
  1263. select h_bol,to_char(update_date,'Mon DD') as update_date_format
  1264. from (SELECT oo.h_bol,COALESCE(a.update_date, a.create_date) as update_date
  1265. from public.ocean_milestone a
  1266. inner join public.kln_ocean oo on oo.serial_no = a.serial_no
  1267. where a.act_date is not null
  1268. ) po
  1269. )t order by h_bol
  1270. ) aa
  1271. group by aa.update_date_format order by aa.update_date_format ";
  1272. $data["What is the current status of my active shipments?"] ="SELECT count(*)
  1273. FROM public.kln_ocean oo
  1274. WHERE <{ExtendHand_KLN}> and ((oo.ata is not null and oo.ata >= CURRENT_DATE - INTERVAL '3 months' AND oo.ata < CURRENT_DATE)
  1275. 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(
  1276. SELECT h_bol, place_of_receipt_exp, place_of_delivery_exp,serial_no,transport_mode,order_from
  1277. FROM public.kln_ocean oo
  1278. WHERE <{ExtendHand_KLN}> and ((oo.ata is not null and oo.ata >= CURRENT_DATE - INTERVAL '3 months' AND oo.ata < CURRENT_DATE)
  1279. 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
  1280. )
  1281. SELECT oo.*,mil.description,mil.act_date,mil.act_time,o.cargo_type,
  1282. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1283. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1284. from oo
  1285. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1286. from public.ocean o where o.serial_no = oo.serial_no) o on true
  1287. left join LATERAL (select a.code,s.description,to_char(a.act_date, 'YYYY-MM-DD') as act_date ,a.act_time
  1288. from public.ocean_milestone a
  1289. left join public.customer_service_milestone_sno s on a.code = s.code
  1290. and s.type = 'sea'
  1291. and a.serial_no = oo.serial_no
  1292. and a.act_date is not null
  1293. order by s.sno desc limit 1) mil on true
  1294. left join LATERAL (select public.getTimeAndLocationForKln(oo.serial_no,mil.code,''::text)::jsonb as jsonb_data) lt on true
  1295. where oo.transport_mode = 'sea' and order_from = 'public'
  1296. union all
  1297. SELECT oo.*,mil.description,mil.act_date,mil.act_time,o.cargo_type,
  1298. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1299. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1300. from oo
  1301. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1302. from sfs.ocean o where o.serial_no = oo.serial_no) o on true
  1303. left join LATERAL (select a.code,s.description,to_char(a.act_date, 'YYYY-MM-DD') as act_date ,a.act_time
  1304. from public.ocean_milestone a
  1305. left join public.customer_service_milestone_sno s on a.code = s.code
  1306. and s.type = 'air'
  1307. and a.serial_no = oo.serial_no
  1308. and a.act_date is not null
  1309. order by s.sno desc limit 1) mil on true
  1310. left join LATERAL (select public.getTimeAndLocationForKln(oo.serial_no,mil.code,''::text)::jsonb as jsonb_data) lt on true
  1311. where oo.transport_mode = 'sea' and order_from = 'sfs'
  1312. union all
  1313. SELECT oo.*,mil.description,mil.act_date,mil.act_time,o.cargo_type,
  1314. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1315. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1316. from oo
  1317. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1318. from public.ocean o where o.serial_no = oo.serial_no) o on true
  1319. left join LATERAL (select a.code,s.description,to_char(a.act_date, 'YYYY-MM-DD') as act_date ,a.act_time
  1320. from public.air_milestone a
  1321. left join public.customer_service_milestone_sno s on a.code = s.code
  1322. and s.type = 'air'
  1323. and a.serial_no = oo.serial_no
  1324. and a.act_date is not null
  1325. order by s.sno desc limit 1) mil on true
  1326. left join LATERAL (select public.getTimeAndLocationForKln(oo.serial_no,mil.code,''::text)::jsonb as jsonb_data) lt on true
  1327. where oo.transport_mode = 'air' and order_from = 'public'
  1328. union all
  1329. SELECT oo.*,mil.description,mil.act_date,mil.act_time,o.cargo_type,
  1330. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1331. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1332. from oo
  1333. inner join LATERAL (select case when is_hazardous = 't' then 'Dangerous Goods'::text else 'General'::text end as cargo_type
  1334. from sfs.ocean o where o.serial_no = oo.serial_no) o on true
  1335. left join LATERAL (select a.code,s.description,to_char(a.act_date, 'YYYY-MM-DD') as act_date ,a.act_time
  1336. from sfs.air_milestone a
  1337. left join public.customer_service_milestone_sno s on a.code = s.code
  1338. and s.type = 'air'
  1339. and a.serial_no = oo.serial_no
  1340. and a.act_date is not null
  1341. order by s.sno desc limit 1) mil on true
  1342. left join LATERAL (select public.getTimeAndLocationForKln(oo.serial_no,mil.code,''::text)::jsonb as jsonb_data) lt on true
  1343. where oo.transport_mode = 'air' and order_from = 'sfs'";
  1344. $data["List shipments with container status updates in the last 7 days."] = "select count(*)
  1345. FROM ra_online_container_status s
  1346. LEFT JOIN oc_container oc ON s.status_id = oc.status_id
  1347. LEFT JOIN ocean o ON o.serial_no::text = oc.serial_no::text
  1348. LEFT JOIN public.ra_online_edi_event e on s.event_base = e.ra_name
  1349. WHERE o.status::text <> 'Cancelled'::text
  1350. and is_display = true
  1351. and s.insert_date <= CURRENT_DATE AND s.insert_date >='2023-02-23'
  1352. 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,
  1353. to_char(to_timestamp(s.event_date, 'YYYYMMDD'), 'YYYY-MM-DD') as eventdate,
  1354. to_char(to_timestamp(s.event_date, 'YYYYMMDD'),'Mon DD') as _eventdate,
  1355. to_char(to_timestamp(s.event_time, 'HH24MI'), 'HH24:MI') as eventtime,
  1356. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1357. e.description,
  1358. s.event_city as uncity
  1359. FROM ra_online_container_status s
  1360. LEFT JOIN oc_container oc ON s.status_id = oc.status_id
  1361. LEFT JOIN ocean o ON o.serial_no::text = oc.serial_no::text
  1362. LEFT JOIN public.ra_online_edi_event e on s.event_base = e.ra_name
  1363. LEFT JOIN public.kln_ocean oo ON oo.serial_no::text = o.serial_no::text
  1364. WHERE o.status::text <> 'Cancelled'::text
  1365. and is_display = true
  1366. and s.insert_date <= CURRENT_DATE AND s.insert_date >='2023-02-23'
  1367. 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
  1368. from (select DISTINCT ON (s.container_no) s.container_no,
  1369. to_char(to_timestamp(s.event_date, 'YYYYMMDD'),'Mon DD') as _eventdate
  1370. FROM ra_online_container_status s
  1371. LEFT JOIN oc_container oc ON s.status_id = oc.status_id
  1372. LEFT JOIN ocean o ON o.serial_no::text = oc.serial_no::text
  1373. LEFT JOIN public.ra_online_edi_event e on s.event_base = e.ra_name
  1374. WHERE o.status::text <> 'Cancelled'::text
  1375. and is_display = true
  1376. and s.insert_date <= CURRENT_DATE AND s.insert_date >='2023-02-23'
  1377. and exists(select 1 from kln_ocean oo where <{ExtendHand_KLN}> and oo.serial_no = o.serial_no)
  1378. order by s.container_no
  1379. )aa group by _eventdate order by _eventdate";
  1380. $data["Today's shipments summary."] = "select count(*)
  1381. from (
  1382. select oo.serial_no
  1383. from (
  1384. select t.serial_no from (
  1385. SELECT
  1386. a.serial_no,
  1387. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1388. from public.ocean_milestone a
  1389. left join public.customer_service_milestone_sno s on a.code = s.code
  1390. where s.type = 'sea'
  1391. and a.act_date is not null
  1392. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1393. )t WHERE rn = 1
  1394. ) po inner join public.kln_ocean oo on oo.serial_no = po.serial_no and (<{ExtendHand_KLN}>)
  1395. union all
  1396. select oo.serial_no
  1397. from (
  1398. select t.serial_no from (
  1399. SELECT
  1400. a.code,a.serial_no,
  1401. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1402. from public.air_milestone a
  1403. left join public.customer_service_milestone_sno s on a.code = s.code
  1404. where s.type = 'sea'
  1405. and a.act_date is not null
  1406. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1407. )t WHERE rn = 1
  1408. ) pa inner join public.kln_ocean oo on oo.serial_no = pa.serial_no and (<{ExtendHand_KLN}>)
  1409. union all
  1410. select oo.serial_no
  1411. from (
  1412. select t.serial_no from (
  1413. SELECT
  1414. a.serial_no,
  1415. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1416. from sfs.air_milestone a
  1417. left join public.customer_service_milestone_sno s on a.code = s.code
  1418. where s.type = 'sea'
  1419. and a.act_date is not null
  1420. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1421. )t WHERE rn = 1
  1422. ) sa inner join public.kln_ocean oo on oo.serial_no = sa.serial_no and (<{ExtendHand_KLN}>)
  1423. )t;select *
  1424. from (
  1425. select *,oo.serial_no,oo.order_from,oo.h_bol,oo.transport_mode,oo.place_of_receipt_exp, oo.place_of_delivery_exp,
  1426. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1427. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1428. from (
  1429. select *,public.getTimeAndLocationForKln(t.serial_no,t.code,''::text)::jsonb as jsonb_data
  1430. from (
  1431. SELECT
  1432. case when a.code = 'IFFDEP' then 'Departure'
  1433. when a.code = 'IFFARR' then 'Arrived'
  1434. when a.code = 'IFFDEL' then 'Delivered'
  1435. else s.description end as action_type,
  1436. a.update_date,a.code,a.serial_no,
  1437. to_char(a.update_date, 'Mon_DD_YYYY') as _update_date,
  1438. to_char(a.act_date, 'YYYY-MM-DD') as act_date ,
  1439. a.act_time,
  1440. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1441. from public.ocean_milestone a
  1442. left join public.customer_service_milestone_sno s on a.code = s.code
  1443. where s.type = 'sea'
  1444. and a.act_date is not null
  1445. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1446. )t WHERE rn = 1
  1447. ) po inner join public.kln_ocean oo on oo.serial_no = po.serial_no
  1448. union all
  1449. select *,oo.serial_no,oo.order_from,oo.h_bol,oo.transport_mode,oo.place_of_receipt_exp, oo.place_of_delivery_exp,
  1450. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1451. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1452. from (
  1453. select *,public.getTimeAndLocationForKln(t.serial_no,t.code,''::text)::jsonb as jsonb_data
  1454. from (
  1455. SELECT
  1456. case when a.code = 'IFFDEP' then 'Departure'
  1457. when a.code = 'IFFARR' then 'Arrived'
  1458. when a.code = 'IFFDEL' then 'Delivered'
  1459. else s.description end as action_type,
  1460. a.update_date,a.code,a.serial_no,
  1461. to_char(a.update_date, 'Mon_DD_YYYY') as _update_date,
  1462. to_char(a.act_date, 'YYYY-MM-DD') as act_date ,
  1463. a.act_time,
  1464. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1465. from public.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. ) pa inner join public.kln_ocean oo on oo.serial_no = pa.serial_no
  1472. union all
  1473. select *,oo.serial_no,oo.order_from,oo.h_bol,oo.transport_mode,oo.place_of_receipt_exp, oo.place_of_delivery_exp,
  1474. COALESCE(jsonb_data->>'milestone','')::jsonb->>'timezone' as timezone,
  1475. COALESCE(jsonb_data->>'milestone','')::jsonb->>'locations' as locations
  1476. from (
  1477. select *,public.getTimeAndLocationForKln(t.serial_no,t.code,''::text)::jsonb as jsonb_data
  1478. from (
  1479. SELECT
  1480. case when a.code = 'IFFDEP' then 'Departure'
  1481. when a.code = 'IFFARR' then 'Arrived'
  1482. when a.code = 'IFFDEL' then 'Delivered'
  1483. else s.description end as action_type,
  1484. a.update_date,a.code,a.serial_no,
  1485. to_char(a.update_date, 'Mon_DD_YYYY') as _update_date,
  1486. to_char(a.act_date, 'YYYY-MM-DD') as act_date ,
  1487. a.act_time,
  1488. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1489. from sfs.air_milestone a
  1490. left join public.customer_service_milestone_sno s on a.code = s.code
  1491. where s.type = 'sea'
  1492. and a.act_date is not null
  1493. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1494. )t WHERE rn = 1
  1495. ) sa inner join public.kln_ocean oo on oo.serial_no = sa.serial_no
  1496. )t limit 10;select sum(case when (action_type='Departure') then 1 else 0 end) as dep,
  1497. sum(case when (action_type='Arrived') then 1 else 0 end) as arr,
  1498. sum(case when (action_type='Delivered') then 1 else 0 end) as del
  1499. from (
  1500. select action_type
  1501. from (
  1502. select t.action_type,t.serial_no from (
  1503. SELECT
  1504. case when a.code = 'IFFDEP' then 'Departure'
  1505. when a.code = 'IFFARR' then 'Arrived'
  1506. when a.code = 'IFFDEL' then 'Delivered'
  1507. else s.description end as action_type,
  1508. a.serial_no,
  1509. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1510. from public.ocean_milestone a
  1511. left join public.customer_service_milestone_sno s on a.code = s.code
  1512. where s.type = 'sea'
  1513. and a.act_date is not null
  1514. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1515. )t WHERE rn = 1
  1516. ) po inner join public.kln_ocean oo on oo.serial_no = po.serial_no and (<{ExtendHand_KLN}>)
  1517. union all
  1518. select action_type
  1519. from (
  1520. select t.action_type,t.serial_no from (
  1521. SELECT
  1522. case when a.code = 'IFFDEP' then 'Departure'
  1523. when a.code = 'IFFARR' then 'Arrived'
  1524. when a.code = 'IFFDEL' then 'Delivered'
  1525. else s.description end as action_type,
  1526. a.serial_no,
  1527. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1528. from public.air_milestone a
  1529. left join public.customer_service_milestone_sno s on a.code = s.code
  1530. where s.type = 'sea'
  1531. and a.act_date is not null
  1532. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1533. )t WHERE rn = 1
  1534. ) pa inner join public.kln_ocean oo on oo.serial_no = pa.serial_no and (<{ExtendHand_KLN}>)
  1535. union all
  1536. select action_type
  1537. from (
  1538. select t.action_type,t.serial_no from (
  1539. SELECT
  1540. case when a.code = 'IFFDEP' then 'Departure'
  1541. when a.code = 'IFFARR' then 'Arrived'
  1542. when a.code = 'IFFDEL' then 'Delivered'
  1543. else s.description end as action_type,
  1544. a.serial_no,
  1545. ROW_NUMBER() OVER(PARTITION BY a.serial_no ORDER BY s.sno DESC) AS rn
  1546. from sfs.air_milestone a
  1547. left join public.customer_service_milestone_sno s on a.code = s.code
  1548. where s.type = 'sea'
  1549. and a.act_date is not null
  1550. --and a.update_date >= CURRENT_DATE AND a.update_date < CURRENT_DATE + INTERVAL '1 day'
  1551. )t WHERE rn = 1
  1552. ) sa inner join public.kln_ocean oo on oo.serial_no = sa.serial_no and (<{ExtendHand_KLN}>)
  1553. )t";
  1554. $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,
  1555. case when oo.eta - CURRENT_DATE <= 0 then '< 1 days'::text
  1556. else (oo.eta - CURRENT_DATE)||' days'::text end as day_to_arr
  1557. from public.kln_ocean oo where 1=1 order by eta limit 10";
  1558. return $data[$type];
  1559. }
  1560. //AES 加密
  1561. public static function AES_128_CBC_Encrypt($data,$key = "fT5!R1k$7Mv@4Q9X",$iv = '1234567890123456'){
  1562. //$key = 'fT5!R1k$7Mv@4Q9X'; // 密钥应该是16字节(128位),24字节(192位)或32字节(256位)
  1563. $method = 'AES-128-CBC';
  1564. //$iv = '1234567890123456';
  1565. // 加密
  1566. $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
  1567. // 编码为可打印的字符串,如Base64
  1568. $encrypted = base64_encode($encrypted);
  1569. return $encrypted;
  1570. }
  1571. /**
  1572. * 解密decrypt
  1573. */
  1574. public static function AES_encrypted($encrypted_string,$isbase64_encode = true,$key = "fT5!R1k$7Mv@4Q9X",$iv = '1234567890123456'){
  1575. //$key = 'fT5!R1k$7Mv@4Q9X'; // 16 bytes key
  1576. //$iv = '1234567890123456'; // 16 bytes IV
  1577. if($isbase64_encode){
  1578. $decrypted = openssl_decrypt(base64_decode($encrypted_string), 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  1579. }else{
  1580. $decrypted = openssl_decrypt($encrypted_string, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  1581. }
  1582. return $decrypted;
  1583. }
  1584. }
  1585. ?>