utils.class.php 85 KB

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