utils.class.php 86 KB

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