common.class.php 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560
  1. <?php
  2. if (!defined('IN_ONLINE')) {
  3. exit('Access Denied');
  4. }
  5. /**
  6. * Description of common
  7. *
  8. * @author Administrator
  9. */
  10. class common {
  11. /*
  12. * mysql check input
  13. */
  14. public static function check_input($value, $boolean = FALSE, $toupper = FALSE) {
  15. if ($boolean !== FALSE) {
  16. if ($value == "t")
  17. return "'t'";
  18. else
  19. return "'f'";
  20. }
  21. $value = trim($value);
  22. if ($toupper !== FALSE)
  23. $value = mb_strtoupper($value);
  24. if (!is_numeric($value)) {
  25. $value = pg_escape_string($value);
  26. }
  27. return $value;
  28. }
  29. public static function excuteOneSql($sql, $exception = FALSE) {
  30. if ($exception) {
  31. global $db;
  32. $result = $db->GetOne($sql);
  33. return $result === FALSE ? null : $result;
  34. } else {
  35. if (empty($sql))
  36. exit(json_encode("Program encountered an error."));
  37. global $db;
  38. $result = $db->GetOne($sql) or ( (!$db->ErrorMsg()) or error_log(common::dbLog($db, $sql), 0));
  39. return $result === FALSE ? null : $result;
  40. }
  41. }
  42. public static function excuteObjectSql($sql) {
  43. if (empty($sql))
  44. exit(json_encode("Program encountered an error."));
  45. global $db;
  46. $result = $db->GetRow($sql) or ( (!$db->ErrorMsg()) or error_log(common::dbLog($db, $sql), 0));
  47. return $result === FALSE ? null : $result;
  48. }
  49. public static function excuteUpdateSql($sql, $req_id = FALSE) {
  50. if (empty($sql))
  51. exit(json_encode("Program encountered an error."));
  52. global $db;
  53. $rs = $db->Execute($sql) or ( (!$db->ErrorMsg()) or error_log(common::dbLog($db, $sql), 0));
  54. if ($rs && $req_id !== FALSE)
  55. return $db->PO_Insert_ID();
  56. else
  57. return $rs;
  58. }
  59. public static function excuteListSql($sql, $exception = FALSE) {
  60. if ($exception) {
  61. global $db;
  62. $result = $db->GetAll($sql);
  63. return $result === FALSE ? null : $result;
  64. } else {
  65. if (empty($sql))
  66. exit(json_encode("Program encountered an error."));
  67. global $db;
  68. $result = $db->GetAll($sql) or ( (!$db->ErrorMsg()) or error_log(common::dbLog($db, $sql), 0));
  69. return $result === FALSE ? null : $result;
  70. }
  71. }
  72. /*
  73. * Database log output
  74. */
  75. public static function dbLog($db, $sql) {
  76. $backMsg = $db->errorMsg() . ' sql=' . $sql;
  77. return $backMsg;
  78. }
  79. /*
  80. * get IP
  81. */
  82. public static function ip() {
  83. if (getenv("HTTP_X_FORWARDED_FOR"))
  84. return getenv("HTTP_X_FORWARDED_FOR");
  85. if (getenv("HTTP_CLIENT_IP"))
  86. return getenv("HTTP_CLIENT_IP");
  87. if (getenv("REMOTE_ADDR"))
  88. return getenv("REMOTE_ADDR");
  89. if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])
  90. return $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
  91. if ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])
  92. return $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
  93. if ($HTTP_SERVER_VARS["REMOTE_ADDR"])
  94. return $HTTP_SERVER_VARS["REMOTE_ADDR"];
  95. return "Unknown";
  96. }
  97. public static function getDBUuid() {
  98. global $db;
  99. $sql = "select uuid_generate_v1()";
  100. $uuid = $db->GetOne($sql);
  101. return $uuid;
  102. }
  103. public static function securityCheckHandNew($action) {
  104. if (strpos($action, "handset") === 0) {
  105. } elseif (strpos($action, "hand") === 0) {
  106. } else {
  107. common::sessionVerify();
  108. $httpAccept = $_SERVER['HTTP_ACCEPT']; // ajax request,is json or html
  109. $ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER
  110. ['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; // is ajax request?
  111. //暂时这么写,放开action = main的查询是为了在没有登录时获取信息。
  112. //tools是为了避免查询的用户,没有配置tools权限,但是新版mark_save需要进入
  113. if($action == "main" || $action == "tools" || $action == "save_layout"){
  114. return;
  115. }
  116. if (!isset($_SESSION['ONLINE_USER'])) {
  117. self::timeoutPrintInfor($httpAccept, $ajax, 'no');
  118. } else {
  119. $time = time() - $_SESSION["LAST_OPERATE_TIME"];
  120. $set_session_timeout = $_SESSION['SESSION_TIMEOUT'];
  121. if (_getLoginName() == "ra.admin") {
  122. $set_session_timeout = 4 * 3600;
  123. }
  124. if ($time > $set_session_timeout) {
  125. self::timeoutPrintInfor($httpAccept, $ajax, 'yes');
  126. } else {
  127. $_SESSION["LAST_OPERATE_TIME"] = time();
  128. if (!_isAdmin() && $_GET["action"] != "linkcrm") {
  129. if (!utils::checkExist($_SESSION['ONLINE_USER']['permission'], $action)
  130. && !(stripos($action, "main") === 0)
  131. && !(stripos($action, "user_guide") === 0)
  132. && !(stripos($action, "feature_update") === 0)
  133. && !(stripos($action, "ajax") === 0)
  134. && !(stripos($action, "opreation_log") === 0)
  135. && !(stripos($action, "robot") === 0)
  136. && !(stripos($action, "system_setting") === 0)
  137. && !(stripos($action, "monitoring_setting") === 0)
  138. && !(stripos($action, "notifications_rules") === 0)) {
  139. $data = array("msg"=>"Permission Denied");
  140. common::echo_json_encode(500, $data);
  141. exit();
  142. }
  143. }
  144. }
  145. }
  146. session_write_close();
  147. }
  148. }
  149. public static function getCompanySearch() {
  150. $sc_list = _get_schemas();
  151. if (utils::count($sc_list) == 1) {
  152. return "";
  153. }
  154. if (_isCustomerLogin()) {
  155. $msg = '<input type="hidden" name="_apex_or_sfs" value=""/>';
  156. } else {
  157. $msg = '<div class="modules">Apex/SFS/Kerry :&nbsp;<select name="_apex_or_sfs" class="sl"><option value="">All</option>';
  158. if ($_SESSION['ONLINE_USER']['main_schemas'] == "public") {
  159. $msg .= '<option value="public">Apex</option>';
  160. } else {
  161. $msg .= '<option value="public">Apex</option>';
  162. }
  163. if ($_SESSION['ONLINE_USER']['main_schemas'] == "sfs") {
  164. $msg .= '<option value="sfs">SFS</option>';
  165. } else {
  166. $msg .= '<option value="sfs">SFS</option>';
  167. }
  168. if ($_SESSION['ONLINE_USER']['main_schemas'] == "kyiff") {
  169. $msg .= '<option value="kyiff">Kerry</option>';
  170. } else {
  171. $msg .= '<option value="kyiff">Kerry</option>';
  172. }
  173. $msg .= '</select></div>';
  174. }
  175. return $msg;
  176. }
  177. public static function sessionVerify() {
  178. if (!isset($_SESSION['user_agent'])) {
  179. $_SESSION['user_agent'] = MD5($_SERVER['REMOTE_ADDR']
  180. . $_SERVER['HTTP_USER_AGENT']);
  181. } elseif ($_SESSION['user_agent'] != MD5($_SERVER['REMOTE_ADDR']
  182. . $_SERVER['HTTP_USER_AGENT'])) {
  183. session_regenerate_id();
  184. }
  185. }
  186. public static function searchExtendHand_KLN($type, $user, $company_name = "station_name") {
  187. $sqlWhere = " 1=1";
  188. if($type == "booking"){
  189. $ocean_booking_sqlWhere = self::searchExtendHandNew("booking",$user, $company_name);
  190. $air_booking_sqlWhere = self::searchExtendHandNew("air_booking",$user, $company_name);
  191. $sqlWhere = "((transport_mode ='sea' and ".$ocean_booking_sqlWhere.") or (transport_mode ='air' and ".$air_booking_sqlWhere."))";
  192. }
  193. if($type == "ocean"){
  194. $ocean_booking_sqlWhere = self::searchExtendHandNew("ocean",$user, $company_name);
  195. $air_booking_sqlWhere = self::searchExtendHandNew("air",$user, $company_name);
  196. $sqlWhere = "((transport_mode ='sea' and ".$ocean_booking_sqlWhere.") or (transport_mode ='air' and ".$air_booking_sqlWhere."))";
  197. }
  198. return $sqlWhere;
  199. }
  200. public static function searchExtendHandNew($type, $user, $company_name = "station_name") {
  201. if (_isAdminHandNew($user)) {
  202. if(strtolower($type) == "air_booking" )
  203. {
  204. return "1=1";
  205. }
  206. return " (COALESCE(schem_not_display,false) = false)";
  207. }
  208. if (_isDocAdmin($user["user_login"])) {
  209. if(strtolower($type) == "air_booking" )
  210. {
  211. return "1=1";
  212. }
  213. return ' (COALESCE(schem_not_display,false) = false)';
  214. }
  215. if (strtolower($type) != "ocean" && strtolower($type) != "booking" && strtolower($type) != "air_booking"&& strtolower($type) != "air") {
  216. return " 1<>1";
  217. }
  218. if (empty($user["schemas_list"])) {
  219. $user["schemas_list"] = $_SESSION["schemas_list"];
  220. }
  221. $schemas_list = $user["schemas_list"];
  222. if ($user["is_kerry_shipment"] == "t") {
  223. $sqlWhere = " is_kerry_shipment is not null and is_kerry_shipment=true";
  224. } else if ($user["is_kerry_shipment"] == "f") {
  225. $sqlWhere = " (COALESCE(is_kerry_shipment,false) = false)";
  226. } else {
  227. $sqlWhere = " 1=1 ";
  228. }
  229. if (!empty($_POST["_apex_or_sfs"])) {
  230. $sqlWhere .= " and order_from='" . $_POST["_apex_or_sfs"] . "'";
  231. }
  232. if (utils::count($schemas_list) == 1) {
  233. $schames = $schemas_list[0]["schemas_name"];
  234. if(strtolower($type) == "air_booking" ||strtolower($type) == "air")
  235. {
  236. }
  237. else
  238. $sqlWhere .= " and order_from='$schames'";
  239. if ($schames == "sfs" && empty($user["sfs_ONLINE_USER"])) {
  240. $user = $_SESSION["sfs_ONLINE_USER"];
  241. }
  242. if (strtolower($type) == "ocean") {
  243. $sqlWhere .= self::_oceanHandNew($user, $schames);
  244. if ($company_name == "doc") {
  245. if (empty($user["view_file_format"])) {
  246. if (strtolower($user["user_type"]) == "customer") {
  247. $sqlWhere .= " and serial_no in (SELECT serial_no from $schames.ra_online_file_format where active = true and client_display = true)";
  248. } else {
  249. $sqlWhere .= " and serial_no in (SELECT serial_no from $schames.ra_online_file_format where active = true)";
  250. }
  251. } else {
  252. $sqlWhere .= " and serial_no in (SELECT regexp_split_to_table('" . $user["view_file_format"] . "',';'))";
  253. }
  254. }
  255. }
  256. if (strtolower($type) == "booking") {
  257. $sqlWhere .= self::_bookingHandNew($user, $schames);
  258. }
  259. if (strtolower($type) == "air_booking") {
  260. $sqlWhere .= self::_air($schames);
  261. }
  262. if (strtolower($type) == "air") {
  263. $sqlWhere .= self::_air($schames);
  264. }
  265. } elseif (utils::count($schemas_list) == 2) {
  266. if(strtolower($type) == "air_booking" ){
  267. }else{
  268. $sqlWhere .= " and (COALESCE(schem_not_display,false) = false)";
  269. }
  270. if (strtolower($type) == "ocean") {
  271. $sqlWhere .= " and ((order_from='public' ";
  272. $sqlWhere .= self::_oceanHandNew($user, "public");
  273. if ($company_name == "doc") {
  274. if (empty($user["view_file_format"])) {
  275. if (strtolower($user["user_type"]) == "customer") {
  276. $sqlWhere .= " and serial_no in (SELECT serial_no from public.ra_online_file_format where active = true and client_display = true)";
  277. } else {
  278. $sqlWhere .= " and serial_no in (SELECT serial_no from public.ra_online_file_format where active = true)";
  279. }
  280. } else {
  281. $sqlWhere .= " and serial_no in (SELECT regexp_split_to_table('" . $user["view_file_format"] . "',';'))";
  282. }
  283. }
  284. $sqlWhere .= ") or (order_from='sfs' ";
  285. if (empty($user["sfs_ONLINE_USER"])) {
  286. $user = $_SESSION["sfs_ONLINE_USER"];
  287. }
  288. $sqlWhere .= self::_oceanHandNew($user, "sfs");
  289. if ($company_name == "doc") {
  290. if (empty($user["view_file_format"])) {
  291. if (strtolower($user["user_type"]) == "customer") {
  292. $sqlWhere .= " and serial_no in (SELECT serial_no from sfs.ra_online_file_format where active = true and client_display = true)";
  293. } else {
  294. $sqlWhere .= " and serial_no in (SELECT serial_no from sfs.ra_online_file_format where active = true)";
  295. }
  296. } else {
  297. $sqlWhere .= " and serial_no in (SELECT regexp_split_to_table('" . $user["view_file_format"] . "',';'))";
  298. }
  299. }
  300. $sqlWhere .= ") )";
  301. }
  302. if (strtolower($type) == "booking") {
  303. $sqlWhere .= " and ((order_from='public' ";
  304. $sqlWhere .= self::_bookingHandNew($user, "public");
  305. $sqlWhere .= ") or (order_from='sfs' ";
  306. if (empty($user["sfs_ONLINE_USER"])) {
  307. $user = $_SESSION["sfs_ONLINE_USER"];
  308. }
  309. $sqlWhere .= self::_bookingHandNew($user, "sfs");
  310. $sqlWhere .= "))";
  311. }
  312. if (strtolower($type) == "air_booking") {
  313. $sqlWhere .= " and ((order_from='public' ";
  314. $sqlWhere .= self::_air("public");
  315. $sqlWhere .= ") or (order_from='sfs' ";
  316. if (empty($user["sfs_ONLINE_USER"])) {
  317. $user = $_SESSION["sfs_ONLINE_USER"];
  318. }
  319. $sqlWhere .= self::_air("sfs");
  320. $sqlWhere .= "))";
  321. }
  322. if (strtolower($type) == "air") {
  323. $sqlWhere .= " and ((order_from='public' ";
  324. $sqlWhere .= self::_air($user, "public");
  325. $sqlWhere .= ") or (order_from='sfs' ";
  326. if (empty($user["sfs_ONLINE_USER"])) {
  327. $user = $_SESSION["sfs_ONLINE_USER"];
  328. }
  329. $sqlWhere .= self::_air($user, "sfs");
  330. $sqlWhere .= ") )";
  331. }
  332. } else {
  333. $sqlWhere = " 1<>1";
  334. }
  335. return $sqlWhere;
  336. }
  337. public static function getStatusStage($status) {
  338. if ($status == "EE" || $status == "I") {
  339. return 0;
  340. }
  341. if ($status == "AE" || $status == "VD" || $status == "VA_RELAY" || $status == "UV_RELAY" || $status == "AE_RELAY" || $status == "VD_RELAY") {
  342. return 1;
  343. }
  344. if ($status == "VA" || $status == "UV" || $status == "AL" || $status == "AR" || $status == "CU" || $status == "CT" || $status == "CR" || $status == "OA") {
  345. return 2;
  346. }
  347. if ($status == "AV" || $status == "D" || $status == "RD") {
  348. return 3;
  349. }
  350. return -1;
  351. }
  352. public static function getInNotInSql($contact_id, $type = 'in') {
  353. if (empty($contact_id))
  354. return " =''";
  355. $contact_id = trim($contact_id);
  356. $contact_id = trim($contact_id, ";");
  357. $contact_id = trim($contact_id);
  358. $contact_id = strtolower($contact_id);
  359. if ($type == 'in') {
  360. if (utils::checkExist($contact_id, ";")) {
  361. $ss = "";
  362. $aa = explode(";", $contact_id);
  363. foreach ($aa as $k => $v) {
  364. $v = trim($v);
  365. if (empty($ss))
  366. $ss = "'" . common::check_input($v) . "'";
  367. else
  368. $ss .= ",'" . common::check_input($v) . "'";
  369. }
  370. return " in (" . $ss . ")";
  371. } else {
  372. return " = '" . common::check_input($contact_id) . "'";
  373. }
  374. } else {
  375. if (utils::checkExist($contact_id, ";")) {
  376. $ss = "";
  377. $aa = explode(";", $contact_id);
  378. foreach ($aa as $k => $v) {
  379. $v = trim($v);
  380. if (empty($ss))
  381. $ss = "'" . common::check_input($v) . "'";
  382. else
  383. $ss .= ",'" . common::check_input($v) . "'";
  384. }
  385. return " in (" . $ss . ")";
  386. } else {
  387. return " != '" . common::check_input($contact_id) . "'";
  388. }
  389. }
  390. }
  391. public static function getInNotInSqlForSearch($contact_id, $type = 'in') {
  392. if (empty($contact_id))
  393. return " =''";
  394. $contact_id = trim($contact_id);
  395. $contact_id = trim($contact_id, ";");
  396. $contact_id = trim($contact_id);
  397. $contact_id = strtolower($contact_id);
  398. if ($type == 'in') {
  399. if (utils::checkExist($contact_id, ";")) {
  400. $ss = "";
  401. $aa = explode(";", $contact_id);
  402. foreach ($aa as $k => $v) {
  403. $v = trim($v);
  404. if (empty($ss))
  405. $ss = "'" . common::check_input($v) . "'";
  406. else
  407. $ss .= ",'" . common::check_input($v) . "'";
  408. }
  409. return $ss;
  410. } else {
  411. return "'" . common::check_input($contact_id) . "'";
  412. }
  413. }
  414. }
  415. /*
  416. * Encrypt a SQL query statement used to be passed as a parameter to get excel output
  417. encode :DeCode('str','E');
  418. decode :DeCode('enstr','D');
  419. */
  420. public static function deCode($string, $operation = "E") {
  421. $key = md5("uls_webwms");
  422. $key_length = strlen($key);
  423. if ($operation == "D")
  424. $string = rawurldecode($string);
  425. $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
  426. $string_length = strlen($string);
  427. $rndkey = $box = array();
  428. $result = '';
  429. for ($i = 0; $i <= 255; $i++) {
  430. $rndkey [$i] = ord($key [$i % $key_length]);
  431. $box [$i] = $i;
  432. }
  433. for ($j = $i = 0; $i < 256; $i++) {
  434. $j = ($j + $box [$i] + $rndkey [$i]) % 256;
  435. $tmp = $box [$i];
  436. $box [$i] = $box [$j];
  437. $box [$j] = $tmp;
  438. }
  439. for ($a = $j = $i = 0; $i < $string_length; $i++) {
  440. $a = ($a + 1) % 256;
  441. $j = ($j + $box [$a]) % 256;
  442. $tmp = $box [$a];
  443. $box [$a] = $box [$j];
  444. $box [$j] = $tmp;
  445. $result .= chr(ord($string [$i]) ^ ($box [($box [$a] + $box [$j]) % 256]));
  446. }
  447. if ($operation == 'D') {
  448. if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
  449. return substr($result, 8);
  450. } else {
  451. return '';
  452. }
  453. } else {
  454. return rawurlencode(str_replace('=', '', base64_encode($result)));
  455. }
  456. }
  457. public static function getStatusDesc($code) {
  458. if (strtoupper($code) == "EE") {
  459. return "Empty Equipment Dispatched";
  460. }
  461. if (strtoupper($code) == "I") {
  462. return "Gate in full for a booking";
  463. }
  464. if (strtoupper($code) == "AE") {
  465. return "Container loaded on vessel";
  466. }
  467. if (strtoupper($code) == "VD") {
  468. return "Vessel Departure";
  469. }
  470. if (strtoupper($code) == "VA_RELAY") {
  471. return "Arrive Relay Port";
  472. }
  473. if (strtoupper($code) == "VD_RELAY") {
  474. return "Depart Relay Port";
  475. }
  476. if (strtoupper($code) == "AE_RELAY") {
  477. return "Loaded at Relay Port";
  478. }
  479. if (strtoupper($code) == "UV_RELAY") {
  480. return "Unloaded at Relay Port";
  481. }
  482. if (strtoupper($code) == "VA") {
  483. return "Vessel Arrival";
  484. }
  485. if (strtoupper($code) == "UV") {
  486. return "Unloaded From Vessel";
  487. }
  488. if (strtoupper($code) == "AL") {
  489. return "Container loaded on Rail";
  490. }
  491. if (strtoupper($code) == "AR") {
  492. return "Container unloaded from Rail";
  493. }
  494. if (strtoupper($code) == "CU") {
  495. return "Carrier and Customs Release";
  496. }
  497. if (strtoupper($code) == "CT") {
  498. return "Customs release";
  499. }
  500. if (strtoupper($code) == "CR") {
  501. return "Carrier release";
  502. }
  503. if (strtoupper($code) == "OA") {
  504. return "Gate out full from final discharge port";
  505. }
  506. if (strtoupper($code) == "AV") {
  507. return "Shipment available for pickup or delivery";
  508. }
  509. if (strtoupper($code) == "RD") {
  510. return "Container returned empty";
  511. }
  512. if (strtoupper($code) == "D") {
  513. return "Gate out for delivery to customer";
  514. }
  515. }
  516. public static function _toString($msg) {
  517. if ($msg == "" || $msg == NULL) {
  518. return "";
  519. }
  520. return $msg . "";
  521. }
  522. /*
  523. * timeout output
  524. */
  525. public static function timeoutPrintInfor($httpAccept, $ajax, $login) {
  526. //记录系统因session过期 退出登录
  527. $data = array("msg"=>"session_time_out");
  528. self::echo_json_encode(403,$data);
  529. exit();
  530. }
  531. /**
  532. * _bookingHandNew 和 _oceanHandNew逻辑完全一样,只是ocean 多一个dest_op字段,在booking里没有的
  533. */
  534. private static function _oceanHandNew($user, $schemas = "public") {
  535. $o = $user['ocean_station'];
  536. $o_or = $user['ocean_station_or'];
  537. $d = $user['ocean_agent'];
  538. $d_or = $user['ocean_agent_or'];
  539. $sales = $user['ocean_sales'];
  540. $sales_or = $user['ocean_sales_or'];
  541. $op = $user['ocean_dest_op'];
  542. $op_or = $user['ocean_dest_op_or'];
  543. $follow = $user['ocean_following_sales'];
  544. $follow_or = $user['ocean_following_sales_or'];
  545. if (strtolower($o_or) == "all" || strtolower($d_or) == "all" || strtolower($sales_or) == "all" || strtolower($op_or) == "all") {
  546. return " and 1=1";
  547. }
  548. $sqlWhere = "";
  549. if (_isCustomerLoginHandNew($user)) {
  550. $sqlWhere .= " and " . _customerFilerSearchHandNew($user, $schemas);
  551. } else {
  552. if (empty($o) && empty($d) && empty($sales) && empty($op) && empty($follow)) {
  553. return " and 1<>1";
  554. }
  555. if ((strtolower($o) == 'all' || empty($o)) && (strtolower($d) == "all" || empty($d))) {
  556. } else {
  557. $sql = "1=1";
  558. if (!empty($o) && strtolower($o) != 'all') {
  559. $sql .= " and lower(origin)";
  560. $sql .= utils::getInSql($o);
  561. }
  562. if (!empty($d) && strtolower($d) != 'all') {
  563. $sql .= " and lower(agent)";
  564. $sql .= utils::getInSql($d);
  565. }
  566. $sqlWhere .= " and (" . $sql . ")";
  567. }
  568. if (strtolower($sales) == 'all' || empty($sales)) {
  569. } else {
  570. if (utils::checkExist($sales, ";")) {
  571. $sql = "1!=1";
  572. $tt = explode(";", $sales);
  573. foreach ($tt as $t) {
  574. $t = trim($t);
  575. if (!empty($t))
  576. $sql .= " or lower(sales_rep)='" . strtolower($t) . "'";
  577. }
  578. $sqlWhere .= " and ($sql)";
  579. } else
  580. $sqlWhere .= " and lower(sales_rep)='" . strtolower($sales) . "'";
  581. }
  582. if (strtolower($op) == 'all' || empty($op)) {
  583. } else {
  584. $sqlWhere .= " and lower(dest_op) " . utils::getInSql($op);
  585. }
  586. if (strtolower($follow) == 'all' || empty($follow)) {
  587. } else {
  588. if (utils::checkExist($follow, ";")) {
  589. $sql = "1!=1";
  590. $tt = explode(";", $follow);
  591. foreach ($tt as $t) {
  592. $t = trim($t);
  593. if (!empty($t))
  594. $sql .= " or following_sales ilike '" . $t . "'";
  595. }
  596. $sqlWhere .= " and ($sql)";
  597. } else
  598. $sqlWhere .= " and following_sales ilike '" . $follow . "'";
  599. }
  600. $sqlWhere = " (1=1 $sqlWhere)";
  601. if (!empty($o_or)) {
  602. $sqlWhere .= " or lower(origin)";
  603. $sqlWhere .= utils::getInSql($o_or);
  604. }
  605. if (!empty($d_or)) {
  606. $sqlWhere .= " or lower(agent)";
  607. $sqlWhere .= utils::getInSql($d_or);
  608. }
  609. if (!empty($sales_or)) {
  610. if (utils::checkExist($sales_or, ";")) {
  611. $sql = "1!=1";
  612. $tt = explode(";", $sales_or);
  613. foreach ($tt as $t) {
  614. $t = trim($t);
  615. if (!empty($t))
  616. $sql .= " or lower(sales_rep)='" . strtolower($t) . "'";
  617. }
  618. $sqlWhere .= " or ($sql)";
  619. } else
  620. $sqlWhere .= " or lower(sales_rep)='" . strtolower($sales_or) . "'";
  621. }
  622. if (!empty($op_or)) {
  623. $sqlWhere .= " or lower(dest_op) " . utils::getInSql($op_or);
  624. }
  625. if (!empty($follow_or)) {
  626. if (utils::checkExist($follow_or, ";")) {
  627. $sql = "1!=1";
  628. $tt = explode(";", $follow_or);
  629. foreach ($tt as $t) {
  630. $t = trim($t);
  631. if (!empty($t))
  632. $sql .= " or following_sales ilike '" . $t . "'";
  633. }
  634. $sqlWhere .= " or ($sql)";
  635. }else {
  636. $sqlWhere .= " or following_sales ilike '" . $follow_or . "'";
  637. }
  638. }
  639. $sqlWhere = " and ($sqlWhere)";
  640. }
  641. return $sqlWhere;
  642. }
  643. /**
  644. * _bookingHandNew 和 _oceanHandNew逻辑完全一样,只是ocean 多一个dest_op字段,在booking里没有的
  645. */
  646. private static function _bookingHandNew($user, $schames) {
  647. $o = $user['ocean_station'];
  648. $o_or = $user['ocean_station_or'];
  649. $d = $user['ocean_agent'];
  650. $d_or = $user['ocean_agent_or'];
  651. $sales = $user['ocean_sales'];
  652. $sales_or = $user['ocean_sales_or'];
  653. $op = $user['ocean_dest_op'];
  654. $op_or = $user['ocean_dest_op_or'];
  655. $follow = $user['ocean_following_sales'];
  656. $follow_or = $user['ocean_following_sales_or'];
  657. if (strtolower($o_or) == "all" || strtolower($d_or) == "all" || strtolower($sales_or) == "all") {
  658. return " and 1=1";
  659. }
  660. $sqlWhere = "";
  661. if (_isCustomerLoginHandNew($user)) {
  662. $sqlWhere .= " and " . _customerFilerSearchHandNew($user, $schames);
  663. } else {
  664. if (empty($o) && empty($d) && empty($sales) && empty($op) && empty($follow)) {
  665. return " and 1<>1";
  666. }
  667. if ((strtolower($o) == 'all' || empty($o)) && (strtolower($d) == "all" || empty($d))) {
  668. } else {
  669. $sql = "1=1";
  670. if (!empty($o) && strtolower($o) != 'all') {
  671. $sql .= " and lower(origin)";
  672. $sql .= utils::getInSql($o);
  673. }
  674. if (!empty($d) && strtolower($d) != 'all') {
  675. $sql .= " and lower(agent)";
  676. $sql .= utils::getInSql($d);
  677. }
  678. $sqlWhere .= " and (" . $sql . ")";
  679. }
  680. if (strtolower($sales) == 'all' || empty($sales)) {
  681. } else {
  682. if (utils::checkExist($sales, ";")) {
  683. $sql = "1!=1";
  684. $tt = explode(";", $sales);
  685. foreach ($tt as $t) {
  686. $t = trim($t);
  687. if (!empty($t))
  688. $sql .= " or lower(sales_rep)='" . strtolower($t) . "'";
  689. }
  690. $sqlWhere .= " and ($sql)";
  691. } else
  692. $sqlWhere .= " and lower(sales_rep)='" . strtolower($sales) . "'";
  693. }
  694. if (strtolower($follow) == 'all' || empty($follow)) {
  695. } else {
  696. if (utils::checkExist($follow, ";")) {
  697. $sql = "1!=1";
  698. $tt = explode(";", $follow);
  699. foreach ($tt as $t) {
  700. $t = trim($t);
  701. if (!empty($t))
  702. $sql .= " or following_sales ilike '" . $t . "%'";
  703. }
  704. $sqlWhere .= " and ($sql)";
  705. } else
  706. $sqlWhere .= " and following_sales ilike '" . $follow . "%'";
  707. }
  708. $sqlWhere = " (1=1 $sqlWhere)";
  709. if (!empty($o_or)) {
  710. $sqlWhere .= " or lower(origin)";
  711. $sqlWhere .= utils::getInSql($o_or);
  712. }
  713. if (!empty($d_or)) {
  714. $sqlWhere .= " or lower(agent)";
  715. $sqlWhere .= utils::getInSql($d_or);
  716. }
  717. if (!empty($sales_or)) {
  718. if (utils::checkExist($sales_or, ";")) {
  719. $sql = "1!=1";
  720. $tt = explode(";", $sales_or);
  721. foreach ($tt as $t) {
  722. $t = trim($t);
  723. if (!empty($t))
  724. $sql .= " or lower(sales_rep)='" . strtolower($t) . "'";
  725. }
  726. $sqlWhere .= " or ($sql)";
  727. } else
  728. $sqlWhere .= " or lower(sales_rep)='" . strtolower($sales_or) . "%'";
  729. }
  730. if (!empty($follow_or)) {
  731. if (utils::checkExist($follow_or, ";")) {
  732. $sql = "1!=1";
  733. $tt = explode(";", $follow_or);
  734. foreach ($tt as $t) {
  735. $t = trim($t);
  736. if (!empty($t))
  737. $sql .= " or following_sales ilike '" . $t . "%'";
  738. }
  739. $sqlWhere .= " or ($sql)";
  740. } else
  741. $sqlWhere .= " or following_sales ilike '" . $follow_or . "%'";
  742. }
  743. $sqlWhere = " and ($sqlWhere)";
  744. }
  745. return $sqlWhere;
  746. }
  747. /**
  748. * online air
  749. */
  750. private static function _air($schemas = "public") {
  751. $station = _getAirStation($schemas);
  752. $station_or = _getAirStationOr($schemas);
  753. $sales = _getAirSales($schemas);
  754. $sales_or = _getAirSalesOr($schemas);
  755. $sqlWhere = " 1=1 ";
  756. if (_isCustomerLogin()) {
  757. $sqlWhere .= " and " . _customerAirFilerSearch($schemas);
  758. } else {
  759. if (empty($station) && empty($sales)) {
  760. return "and 1<>1";
  761. }
  762. if (strtolower($station_or) == "all" || strtolower($sales_or) == "all")
  763. return " and ($sqlWhere)";
  764. if (strtolower($station) == 'all' || empty($station)) {
  765. } else {
  766. $sqlWhere .= " and (lower(origin)";
  767. $sqlWhere .= utils::getInSql($station);
  768. $sqlWhere .= " or lower(agent)";
  769. $sqlWhere .= utils::getInSql($station);
  770. $sqlWhere .= ")";
  771. }
  772. if (strtolower($sales) == 'all' || empty($sales)) {
  773. } else {
  774. $sqlWhere .= " and (lower(sales_rep) " . utils::getInSql($sales) . " or lower(following_sales) " . utils::getInSql($sales) . ")";
  775. }
  776. $sqlWhere = " ($sqlWhere)";
  777. if (!empty($station_or))
  778. $sqlWhere = "$sqlWhere or lower(origin)" . utils::getInSql($station_or) . " or lower(agent)" . utils::getInSql($station_or);
  779. if (!empty($sales_or))
  780. $sqlWhere = "$sqlWhere or lower(sales_rep)" . utils::getInSql($sales_or) . " or lower(following_sales)" . utils::getInSql($sales_or);
  781. }
  782. return " and ($sqlWhere)";
  783. }
  784. public static function isNewVersion() {
  785. if (utils::checkExist($_SERVER['PHP_SELF'], "main_new_version.php")) {
  786. return "_new";
  787. }
  788. return "";
  789. }
  790. public static function removeTopOceanOldVersionSpecialField($rss){
  791. $rss_bk = $rss;
  792. $new_arr = array();
  793. foreach ($rss_bk as $k => $v) {
  794. if (utils::startWith($v['database_column_name'], "__") || utils::startWith($v['database_column_name'], "___")){
  795. //unset($rss[$k]);
  796. }else{
  797. $new_arr[] = $v;
  798. }
  799. }
  800. return $new_arr;
  801. }
  802. public static function echo_json_encode($code,$data){
  803. $resData = array();
  804. $resData["code"] = $code;
  805. $resData["data"] =$data;
  806. //echo utils::jsonFiltration("null", "\"\"", json_encode($resData));
  807. echo json_encode($resData);
  808. }
  809. /*
  810. * MM/DD/YYYY To YYYY-MM-DD
  811. */
  812. public static function usDate2sqlDate($timestr) {
  813. if (empty($timestr))
  814. return '';
  815. $datearray = explode("/", $timestr);
  816. $m = $datearray [0];
  817. $d = $datearray [1];
  818. $y = $datearray [2];
  819. return $y . "-" . $m . "-" . $d;
  820. }
  821. public static function uuid() {
  822. return md5(uniqid("", TRUE) . mt_rand());
  823. }
  824. /*
  825. * YYYYMMDD To MM/DD/YYYY
  826. */
  827. public static function date2usdate($datestr) {
  828. if (empty($datestr))
  829. return '';
  830. $y = substr($datestr, 0, 4);
  831. $m = substr($datestr, 4, 2);
  832. $d = substr($datestr, 6, 2);
  833. return $m . "/" . $d . "/" . $y;
  834. }
  835. /*
  836. * date add some days
  837. */
  838. public static function addDays($date, $days) {
  839. $time = strtotime($date) + $days * 24 * 3600;
  840. return date('m/d/Y', $time);
  841. }
  842. /*
  843. * download file from file system
  844. */
  845. public static function download_file($filename, $display_name = null, $delete = FALSE, $files = NULL) {
  846. $filename = str_replace("/", DIRECTORY_SEPARATOR, $filename);
  847. $filename = str_replace("\\", DIRECTORY_SEPARATOR, $filename);
  848. if (!file_exists($filename))
  849. exit('File Not Exist');
  850. if (empty($display_name))
  851. $display_name = basename($filename);
  852. //$file = fopen($filename, "r");
  853. header_remove("Content-type");
  854. header("Content-type:" . self::getContentType($filename));
  855. header("Expires: 0");
  856. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  857. header("Pragma: can-cache");
  858. header("Accept-ranges:bytes");
  859. header("Accept-length:" . filesize($filename));
  860. header("Content-Disposition:attachment;filename=\"" . $display_name . "\"");
  861. //echo fread($file, filesize($filename));
  862. //fclose($file);
  863. //针对大文件,规定每次读取文件的字节数为4096字节,直接输出数据
  864. $read_buffer = 4096;
  865. $handle = fopen($filename, 'rb');
  866. //总的缓冲的字节数
  867. $sum_buffer = 0;
  868. $filesize = filesize($filename);
  869. //只要没到文件尾,就一直读取
  870. while (!feof($handle) && $sum_buffer < $filesize) {
  871. echo fread($handle, $read_buffer);
  872. $sum_buffer += $read_buffer;
  873. }
  874. //关闭句柄
  875. fclose($handle);
  876. if ($delete !== FALSE) {
  877. unlink($filename);
  878. }
  879. if (!empty($files)) {
  880. foreach ($files as $f) {
  881. unlink($f);
  882. }
  883. }
  884. }
  885. public static function getContentType($filename) {
  886. $extend = self::getExtendFilename($filename);
  887. $filetype = array(
  888. 'xls' => 'application/vnd.ms-excel',
  889. 'doc' => 'application/msword',
  890. 'gif' => 'image/gif',
  891. 'jpg' => 'image/jpeg',
  892. 'jpeg' => 'image/jpeg',
  893. 'jpe' => 'image/jpeg',
  894. 'bmp' => 'image/bmp',
  895. 'png' => 'image/png',
  896. 'tif' => 'image/tiff',
  897. 'pdf' => 'application/pdf',
  898. 'zip' => 'application/zip'
  899. );
  900. return $filetype[$extend];
  901. }
  902. /*
  903. * Get the file extension
  904. */
  905. public static function getExtendFilename($file_name) {
  906. $extend = pathinfo($file_name);
  907. $extend = strtolower($extend["extension"]);
  908. return $extend;
  909. }
  910. public static function getManagement(){
  911. //Management 自己配置需要创建表保存
  912. $user_management_data = common::excuteObjectSql("select management,dashboard_filter from ra_online_user where user_login = '"._getLoginName()."'");
  913. //为空,配置使用默认值
  914. $user_management = $user_management_data['management'];
  915. if(empty($user_management)){
  916. $Management = common::getdefaultManagement();
  917. }else{
  918. $Management = json_decode($user_management,true);
  919. foreach($Management as $key =>$val){
  920. $Management[$key]['id'] = intval($val['id']);
  921. $Management[$key]['switchValue'] = $val['switchValue'] == "true" ? true : false;
  922. }
  923. }
  924. $user_dashboard_filter = $user_management_data['dashboard_filter'];
  925. $dashboard_filter =array();
  926. if(!empty($user_dashboard_filter)){
  927. $dashboard_filter = json_decode($user_dashboard_filter,true);
  928. }else{
  929. $threeMonthsAgoTimestamp = strtotime('-3 months');
  930. $date_start = date('Y-m-d', $threeMonthsAgoTimestamp);
  931. $date_end = date('Y-m-d');
  932. $date_start_two = date('m/d/Y', $threeMonthsAgoTimestamp);
  933. $date_end_two = date('m/d/Y');
  934. //ETD
  935. $_12MonthsAgoTimestamp = strtotime('-11 months');
  936. $etd_date_start = date('Y-m', $_12MonthsAgoTimestamp);
  937. $etd_date_end = date('Y-m');
  938. $etd_date_start_two = date('m/Y', $_12MonthsAgoTimestamp);
  939. $etd_date_end_two = date('m/Y');
  940. //柜子
  941. $ctnr_date_start = date('Y-m', $_12MonthsAgoTimestamp);
  942. $ctnr_date_end = date('Y-m');
  943. $ctnr_date_start_two = date('m/Y', $_12MonthsAgoTimestamp);
  944. $ctnr_date_end_two = date('m/Y');
  945. //Top
  946. $top_date_start = date('Y-m-d', $_12MonthsAgoTimestamp);
  947. $top_date_end = date('Y-m-d');
  948. $top_date_start_two = date('m/d/Y', $_12MonthsAgoTimestamp);
  949. $top_date_end_two = date('m/d/Y');
  950. //KPIDefaulteData
  951. $dashboard_filter['KPIDefaulteData'] = array("transportation" =>array('All'),"date_type"=>"ETD","date_start"=>$date_start_two,"date_start_two"=>$date_start,
  952. "date_end"=>$date_end_two,"date_end_two"=>$date_end);
  953. //PendingDefaultData
  954. $dashboard_filter['PendingDefaultData'] = array("transportation" =>array('All'),"date_type"=>"ETD","date_start"=>"","date_start_two"=>"",
  955. "date_end"=>"","date_end_two"=>"");
  956. //RecentDefaultData
  957. $dashboard_filter['RecentDefaultData'] = array("transportation" =>array('All'),"date_type"=>"ETD","date_start"=>$date_start_two,"date_start_two"=>$date_start,
  958. "date_end"=>$date_end_two,"date_end_two"=>$date_end);
  959. //ETDDefaultData
  960. $dashboard_filter['ETDDefaultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$etd_date_start_two,"date_start_two"=>$etd_date_start,
  961. "date_end"=>$etd_date_end_two,"date_end_two"=>$etd_date_end);
  962. //ContainerefaultData
  963. $dashboard_filter['ContainerefaultData'] = array("transportation" =>array('Sea'),"date_type"=>"ETA","date_start"=>$ctnr_date_start_two,"date_start_two"=>$ctnr_date_start,
  964. "date_end"=>$ctnr_date_end_two,"date_end_two"=>$ctnr_date_end);
  965. //RevenueDefaultData
  966. if(_isRevenueDisplay()){
  967. $dashboard_filter['RevenueDefaultData'] = array("transportation" =>array('All'),"date_type"=>"Invoice Issue Date","date_start"=>$ctnr_date_start_two,"date_start_two"=>$ctnr_date_start,
  968. "date_end"=>$ctnr_date_end_two,"date_end_two"=>$ctnr_date_end);
  969. }
  970. //Top10faultData
  971. $dashboard_filter['Top10faultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$top_date_start_two,"date_start_two"=>$top_date_start,
  972. "date_end"=>$top_date_end_two,"date_end_two"=>$top_date_end);
  973. //OriginCo2Top10faultData
  974. $dashboard_filter['OriginCo2Top10faultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$top_date_start_two,"date_start_two"=>$top_date_start,
  975. "date_end"=>$top_date_end_two,"date_end_two"=>$top_date_end);
  976. //DestinationCo2Top10faultData
  977. $dashboard_filter['DestinationCo2Top10faultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$top_date_start_two,"date_start_two"=>$top_date_start,
  978. "date_end"=>$top_date_end_two,"date_end_two"=>$top_date_end);
  979. }
  980. return array("Management" => $Management,"dashboard_filter" =>$dashboard_filter);
  981. }
  982. public static function getItemStyle($type,$code){
  983. if($type == 'r1'){
  984. $data = array("0-20 Days" =>"#ffc594",
  985. "20-40 Days" =>"#ff9e4c",
  986. "40-60 Days" =>"#ff7500",
  987. "60-80 Days" =>"#ff3d00",
  988. "Over 80 Days" =>"#d50000");
  989. return $data[$code];
  990. }
  991. if($type == 'r4' || $type == 'r3' || $type == 'atd_r4' || $type == 'ata_r3'){
  992. $data = array("0 Day" =>"#ffc594",
  993. "Today" =>"#ffc594",
  994. "1-2 Days" =>"#ff9e4c",
  995. "3-6 Days" =>"#ff7500",
  996. "7 Days" =>"#ff3d00");
  997. return $data[$code];
  998. }
  999. if($type == 'r2' || utils::startWith($type,"co2e")){
  1000. $data = array("45" =>"#FFE3CC",
  1001. "40" =>"#FFAC66",
  1002. "20" =>"#FF7500",
  1003. "air" =>"#FFE3CC",
  1004. "sea" =>"#FFAC66",
  1005. "road" =>"#FF7500");
  1006. return $data[$code];
  1007. }
  1008. if($type == "top"){
  1009. $data = array("1" =>"#FF7500",
  1010. "2" =>"#ff9033",
  1011. "3" =>"#ff9e4d",
  1012. "4" =>"#ffac66",
  1013. "5" =>"#ffba80",
  1014. "6" =>"#ffc899",
  1015. "7" =>"#ffd6b3",
  1016. "8" =>"#ffe3cc",
  1017. "9" =>"#fff1e6",
  1018. "10" =>"#fff1e6");
  1019. return $data[$code];
  1020. }
  1021. }
  1022. //处理返回原表数据格式
  1023. public static function mian_repot_do($value,$type,$totalValue){
  1024. $data = array();
  1025. $value_arr = json_decode($value,true);
  1026. //r1 是 ETD to ETA (Days)圆形图表数据结构返回
  1027. if($type == 'r1'){
  1028. $ETDList = array();
  1029. foreach($value_arr as $arr){
  1030. $color = common::getItemStyle($type,$arr['name']);
  1031. $ETDList[] = array("value" =>intval($arr['value']),"name" =>$arr['name'],"itemStyle" =>array("color" =>$color));
  1032. }
  1033. // 排序依据的键数组(这里我们用一个数字数组来表示)
  1034. $order = ["0-20 Days", "20-40 Days", "40-60 Days","60-80 Days","Over 80 Days"];
  1035. $ETDList = utils::arrayOrderBykeys($order,$ETDList,"name");
  1036. //$ETDList = array_reverse($ETDList);
  1037. $ETD_Title = "Total: $totalValue";
  1038. $data = array("ETDList" =>$ETDList,"ETD_Radius"=>array('50%','80%'),"ETD_Title" =>$ETD_Title,"download_name" => "ETD to ETA (Days)");
  1039. }
  1040. if($type == 'r4' || $type == 'r3'){
  1041. //重新整理一下数据,给UI一致
  1042. $data_kd = array();
  1043. foreach($value_arr as $arr){
  1044. if(stripos("Today", $arr['name']) !== false){
  1045. $color = common::getItemStyle($type,"Today");
  1046. if(empty($data_kd["0"])){
  1047. $data_kd["0"] = array("value" =>intval($arr['value']),"name" =>"≤1 Day","itemStyle" =>array("color" =>$color));
  1048. }else{
  1049. $data_kd["0"]["value"] = $data_kd["0"]["value"] + intval($arr['value']);
  1050. }
  1051. }
  1052. if(stripos("+1 Days/+2 Days", $arr['name']) !== false){
  1053. $color = common::getItemStyle($type,"1-2 Days");
  1054. if(empty($data_kd["1"])){
  1055. $data_kd["1"] = array("value" =>intval($arr['value']),"name" =>"1-2 Days","itemStyle" =>array("color" =>$color));
  1056. }else{
  1057. $data_kd["1"]["value"] = $data_kd["1"]["value"] + intval($arr['value']);
  1058. }
  1059. }
  1060. if(stripos("+3 Days/+4 Days/+5 Days/+6 Days", $arr['name']) !== false){
  1061. $color = common::getItemStyle($type,"3-6 Days");
  1062. if(empty($data_kd["2"])){
  1063. $data_kd["2"] = array("value" =>intval($arr['value']),"name" =>"3-6 Days","itemStyle" =>array("color" =>$color));
  1064. }else{
  1065. $data_kd["2"]["value"] = $data_kd["2"]["value"] + intval($arr['value']);
  1066. }
  1067. }
  1068. if(stripos("+7 Days/Over 7 Days", $arr['name']) !== false){
  1069. $color = common::getItemStyle($type,"7 Days");
  1070. if(empty($data_kd["3"])){
  1071. $data_kd["3"] = array("value" =>intval($arr['value']),"name" =>"≥7 Days","itemStyle" =>array("color" =>$color));
  1072. }else{
  1073. $data_kd["3"]["value"] = $data_kd["3"]["value"] + intval($arr['value']);
  1074. }
  1075. }
  1076. }
  1077. // 排序依据的键数组(这里我们用一个数字数组来表示)
  1078. $order = ["≤1 Day", "1-2 Days", "3-6 Days","≥7 Days"];
  1079. $data_kd = utils::arrayOrderBykeys($order,$data_kd,"name");
  1080. if($type == 'r4'){
  1081. $data = array("ETDList" =>$data_kd,"ETD_Radius"=>array('30%','50%'),"title1" =>"Departure","title2" =>"","download_name" => "Pending Departure");
  1082. }
  1083. if($type == 'r3'){
  1084. $data = array("ETDList" =>$data_kd,"ETD_Radius"=>array('30%','50%'),"title1" =>"Arrival","title2" =>"","download_name" => "Pending Arrival");
  1085. }
  1086. }
  1087. return $data;
  1088. }
  1089. //单独处理co2e bar
  1090. public static function getCo2eBar(){
  1091. //分担查询
  1092. include ONLINE_ROOT . 'libs' . DS . 'map_config.ini.php';
  1093. //新UI air sea road 目前只有sea
  1094. $type = $_REQUEST["r_type"];
  1095. $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1096. $sqlWhere = " " . $sqlWhere;
  1097. $date_type = strtolower($_REQUEST["date_type"]);
  1098. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start']))
  1099. $sqlWhere .= " and $date_type >= '" . common::usDate2sqlDate($_REQUEST['date_start']) . " 00:00:00'";
  1100. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end']))
  1101. $sqlWhere .= " and $date_type <= '" . common::usDate2sqlDate($_REQUEST['date_end']) . " 23:59:59'";
  1102. $transportation = $_REQUEST["transportation"];
  1103. if(!is_array($transportation)){
  1104. $transportation = array($transportation);
  1105. }
  1106. $mode_param = "";
  1107. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  1108. $mode_param = "'sea','air','road'";
  1109. }else{
  1110. $transport_mode = utils::implode(';', $transportation);
  1111. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  1112. }
  1113. $sqlWhere .= " and transport_mode in ($mode_param)";
  1114. $ContainerCount_Title = array();
  1115. //先查询总的排放量sea air road,确定排名后,在分别查询对应的sea air road
  1116. //这里的问题跟 top 一样 。总的排放量查询有问题。目前是总的排放量 暂时等于 sea的排放量
  1117. if ($type == "co2e_orgin"){
  1118. $co2e_shippr_sql = "select SUM(COALESCE(carbon_emission,0)) as catnum ,
  1119. sum(case when (1<>1 or (transport_mode='air')) then COALESCE(carbon_emission,0) else 0 end) as air_rc,
  1120. sum(case when (1<>1 or (transport_mode='sea')) then COALESCE(carbon_emission,0) else 0 end) as sea_rc,
  1121. sum(case when (1<>1 or (transport_mode='road')) then COALESCE(carbon_emission,0) else 0 end) as road_rc,
  1122. shippr_uncode as station from public.kln_ocean where 1=1 and COALESCE(shippr_uncode,'')<>'' and carbon_emission is not null $sqlWhere group by shippr_uncode order by catnum desc limit 10";
  1123. //$co2e_aLL = common::excuteListSql($co2e_shippr_sql);
  1124. $co2e_aLL = $mapdb->GetAll($co2e_shippr_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $co2e_shippr_sql), 0));
  1125. }
  1126. if ($type == "co2e_destination"){
  1127. $co2e_consignee_sql = "select SUM(COALESCE(carbon_emission,0)) as catnum ,
  1128. sum(case when (1<>1 or (transport_mode='air')) then COALESCE(carbon_emission,0) else 0 end) as air_rc,
  1129. sum(case when (1<>1 or (transport_mode='sea')) then COALESCE(carbon_emission,0) else 0 end) as sea_rc,
  1130. sum(case when (1<>1 or (transport_mode='road')) then COALESCE(carbon_emission,0) else 0 end) as road_rc,
  1131. consignee_uncode as station from public.kln_ocean where 1=1 and COALESCE(consignee_uncode,'')<>'' and carbon_emission is not null $sqlWhere group by consignee_uncode order by catnum desc limit 10";
  1132. //$co2e_aLL = common::excuteListSql($co2e_consignee_sql);
  1133. $co2e_aLL = $mapdb->GetAll($co2e_consignee_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $co2e_consignee_sql), 0));
  1134. }
  1135. //最大Y值
  1136. $maxY = 0;
  1137. $stations = array();
  1138. foreach($co2e_aLL as $val){
  1139. $ContainerCount_Title[] = $val['station'];
  1140. $maxY = $maxY > $val['catnum'] ? $maxY : $val['catnum'];
  1141. if(!empty($val['station'])){
  1142. $stations[] = $val['station'];
  1143. }
  1144. }
  1145. // $station_str = utils::implode(',',$stations);
  1146. $ContainerCounSeries = array();
  1147. $shipment_mode_arr = array("air","sea","road");
  1148. foreach($shipment_mode_arr as $_shipment_mode){
  1149. //类型有 sea air road,目前之类只查询sea的,其他为空
  1150. $shipment_mode = $_shipment_mode;
  1151. // $co2e = array();
  1152. if ($type == "co2e_orgin"){
  1153. // $co2e_shippr_sql_union = utils::_getSql($station_str,$type,$shipment_mode,$sqlWhere);
  1154. // if(!empty($co2e_shippr_sql_union)){
  1155. // $co2e = common::excuteListSql($co2e_shippr_sql_union);
  1156. // }
  1157. $download_name = "CO2e Emission by Origin (Top 10)";
  1158. }
  1159. if ($type == "co2e_destination"){
  1160. // $co2e_consignee_union = utils::_getSql($station_str,$type,$shipment_mode,$sqlWhere);
  1161. // if(!empty($co2e_consignee_union)){
  1162. // $co2e = common::excuteListSql($co2e_consignee_union);
  1163. // }
  1164. $download_name = "CO2e Emission by Destination (Top 10)";
  1165. }
  1166. $total = 0;
  1167. $max = 0;
  1168. $data = array();
  1169. foreach($co2e_aLL as $val){
  1170. $catnum = $shipment_mode."_rc";
  1171. $data[] = empty($val[$catnum])? 0 : round($val[$catnum], 4);
  1172. $total = $total + $val[$catnum];
  1173. $max = $max < $val[$catnum] ? $val[$catnum] : $max;
  1174. }
  1175. $ContainerCounSeries[$shipment_mode] = array("data"=>$data,"total"=>$total,"max"=>$max);
  1176. }
  1177. //处理返回时数据格式 其实不太需要计算最大值,在最开始总量查询的时候以及查询出来
  1178. $ContainerCounSeries_return = array();
  1179. foreach($ContainerCounSeries as $k =>$v){
  1180. $color = common::getItemStyle($type,$k);
  1181. $ContainerCounSeries_return[] = array("name"=>$k,"type"=>"bar","emphasis" => array("focus" =>"none"),
  1182. "stack" =>"总计","data" =>$v['data'],"itemStyle" =>array("color" =>$color),'barWidth'=>'40');
  1183. }
  1184. //处理返回原表数据格式
  1185. //计算刻度值 最小值是0,最大值是3000,刻度是500 interval
  1186. $interval = utils::calculateTicks(0,$maxY,10);
  1187. if($interval == 0){
  1188. //处理返回默认值
  1189. $interval = 1;
  1190. }
  1191. $returnData = array("ContainerCount_Title"=>"","ContainerCountList" =>$ContainerCount_Title,"ContainerCounSeries" =>$ContainerCounSeries_return,
  1192. "min" => 0,"Max" =>$interval*10,"interval" =>$interval,"download_name" => $download_name);
  1193. return $returnData;
  1194. }
  1195. public static function getTopBar(){
  1196. $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1197. $sqlWhere = " " . $sqlWhere;
  1198. $date_type = strtolower($_REQUEST["date_type"]);
  1199. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start']))
  1200. $sqlWhere .= " and $date_type >= '" . common::usDate2sqlDate($_REQUEST['date_start']) . " 00:00:00'";
  1201. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end']))
  1202. $sqlWhere .= " and $date_type <= '" . common::usDate2sqlDate($_REQUEST['date_end']) . " 23:59:59'";
  1203. $transportation = $_REQUEST["transportation"];
  1204. if(!is_array($transportation)){
  1205. $transportation = array($transportation);
  1206. }
  1207. $mode_param = "";
  1208. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  1209. $mode_param = "'sea','air','road'";
  1210. }else{
  1211. $transport_mode = utils::implode(';', $transportation);
  1212. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  1213. }
  1214. $sqlWhere .= " and transport_mode in ($mode_param)";
  1215. $toporiginType = "shippr_uncode";
  1216. $shippr_uncode_10_sql ="with aa as (select count(shippr_uncode) as num,shippr_uncode,
  1217. (array_agg(shipper_city))[1] AS shipper_city from public.kln_ocean
  1218. where 1=1 and COALESCE(shippr_uncode,'')<>'' $sqlWhere group by shippr_uncode order by num desc limit 10)
  1219. select aa.*,dd.* from aa
  1220. left join LATERAL ( select lon as lng, lat as lat,
  1221. '' as label, '' as infor, 3 as sort,
  1222. null::timestamp without time zone as stime,''::text as ptype
  1223. from vessel.vt_unlocode where (lat<=90 and lat>=-90) and (lon<=180 and lon>=-180) and lon is not null and lat is not null and uncode=aa.shippr_uncode ) dd on true";
  1224. $shippr_uncode_10 = common::excuteListSql($shippr_uncode_10_sql);
  1225. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1226. if(utils::count($shippr_uncode_10) == 1 && empty($shippr_uncode_10[0]["shippr_uncode"])){
  1227. $toporiginType = "fport_of_loading_un";
  1228. $shippr_uncode_10_sql = "with aa as (select count(fport_of_loading_un) as num,fport_of_loading_un as shippr_uncode
  1229. from public.kln_ocean where 1=1 and COALESCE(fport_of_loading_un,'')<>'' $sqlWhere group by fport_of_loading_un order by num desc limit 10)
  1230. select aa.*,dd.* from aa
  1231. left join LATERAL ( select lon as lng, lat as lat,
  1232. '' as label, '' as infor, 3 as sort,
  1233. null::timestamp without time zone as stime,''::text as ptype
  1234. from vessel.vt_unlocode where (lat<=90 and lat>=-90) and (lon<=180 and lon>=-180) and lon is not null and lat is not null and uncode=aa.fport_of_loading_un ) dd on true";
  1235. $shippr_uncode_10 = common::excuteListSql($shippr_uncode_10_sql);
  1236. }
  1237. //$toporiginType = "fport_of_loading_un";
  1238. $topdestinationinType = "consignee_uncode";
  1239. $consignee_uncode_10_sql = "with aa as (select count(consignee_uncode) as num,consignee_uncode,
  1240. (array_agg(consignee_city))[1] AS consignee_city
  1241. from public.kln_ocean where 1=1 and COALESCE(consignee_uncode,'')<>'' $sqlWhere group by consignee_uncode order by num desc limit 10)
  1242. select aa.*,dd.* from aa
  1243. left join LATERAL ( select lon as lng, lat as lat,
  1244. '' as label, '' as infor, 3 as sort,
  1245. null::timestamp without time zone as stime,''::text as ptype
  1246. from vessel.vt_unlocode where (lat<=90 and lat>=-90) and (lon<=180 and lon>=-180) and lon is not null and lat is not null and uncode=aa.consignee_uncode ) dd on true";
  1247. $consignee_uncode_10 = common::excuteListSql($consignee_uncode_10_sql);
  1248. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1249. if(utils::count($consignee_uncode_10) == 1 && empty($consignee_uncode_10[0]["consignee_uncode"])){
  1250. $topdestinationinType = "mport_of_discharge_un";
  1251. $consignee_uncode_10_sql = "with aa as (select count(mport_of_discharge_un) as num,mport_of_discharge_un as consignee_uncode from public.kln_ocean where 1=1 and COALESCE(mport_of_discharge_un,'')<>'' $sqlWhere group by mport_of_discharge_un order by num desc limit 10)
  1252. select aa.*,dd.* from aa
  1253. left join LATERAL ( select lon as lng, lat as lat,
  1254. '' as label, '' as infor, 3 as sort,
  1255. null::timestamp without time zone as stime,''::text as ptype
  1256. from vessel.vt_unlocode where (lat<=90 and lat>=-90) and (lon<=180 and lon>=-180) and lon is not null and lat is not null and uncode=aa.mport_of_discharge_un ) dd on true";
  1257. $consignee_uncode_10 = common::excuteListSql($consignee_uncode_10_sql);
  1258. }
  1259. $toporigin = array();
  1260. $toporiginMap = array();
  1261. $i = 0;
  1262. $origiNunMax = 0;
  1263. foreach($shippr_uncode_10 as $orgin){
  1264. $i = $i + 1;
  1265. $map = array();
  1266. if(!empty($orgin['lat'])&&!empty($orgin['lng'])){
  1267. $map = array("lat" =>$orgin['lat'],"lng" =>$orgin['lng']);
  1268. }
  1269. //$json = '{"lng":121.8525,"lat":29.926545,"label":"'.$orgin['origin'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1270. //$map = json_decode($json,true);
  1271. if(!empty($map)){
  1272. $toporiginMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1273. "divIcon" => array("iconSize"=>0),
  1274. "name" =>$orgin['shippr_uncode'],
  1275. "color" =>common::getItemStyle("top",$i),
  1276. "value" =>$orgin['num'],
  1277. "textcolor" =>"#FFF");
  1278. }
  1279. //查询uncode,对应的city
  1280. $city = "";
  1281. if($toporiginType == "shippr_uncode"){
  1282. $city = $orgin['shipper_city'];
  1283. }
  1284. //$city 做假数据
  1285. $toporigin[] = array("name"=>$orgin['shippr_uncode'],"city_name"=>$city,"value"=>$orgin['num'],"color"=>common::getItemStyle("top",$i));
  1286. $origiNunMax = $origiNunMax < $orgin['num'] ? $orgin['num'] : $origiNunMax;
  1287. }
  1288. $topdestination = array();
  1289. $topdestinationinMap = array();
  1290. $i = 0;
  1291. $agentiNunMax = 0;
  1292. foreach($consignee_uncode_10 as $agent){
  1293. $i = $i + 1;
  1294. $map = array();
  1295. if(!empty($agent['lat'])&&!empty($agent['lng'])){
  1296. $map = array("lat" =>$agent['lat'],"lng" =>$agent['lng']);
  1297. }
  1298. // $json = '{"lng":"100.78594000","lat":"13.68521000","label":"'.$agent['agent'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1299. // $map = json_decode($json,true);
  1300. if(!empty($map)){
  1301. $topdestinationinMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1302. "divIcon" => array("iconSize"=>0),
  1303. "name" =>$agent['consignee_uncode'],
  1304. "color" =>common::getItemStyle("top",$i),
  1305. "value" =>$agent['num'],
  1306. "textcolor" =>"#FFF");
  1307. }
  1308. //查询uncode,对应的city
  1309. $city = "";
  1310. if($topdestinationinType == "consignee_uncode"){
  1311. $city = $agent['consignee_city'];
  1312. }
  1313. //$city 做假数据
  1314. $topdestination[] = array("name"=>$agent['consignee_uncode'],"city_name"=>$city,"value"=>$agent['num'],"color"=>common::getItemStyle("top",$i));
  1315. $agentiNunMax = $agentiNunMax < $agent['num'] ? $agent['num'] : $agentiNunMax;
  1316. }
  1317. //处理返回原表数据格式
  1318. $interval = utils::calculateTicks(0,$origiNunMax,10);
  1319. if($interval == 0){
  1320. //处理返回默认值
  1321. $interval = 1;
  1322. }
  1323. $dest_interval = utils::calculateTicks(0,$agentiNunMax,10);
  1324. if($dest_interval == 0){
  1325. //处理返回默认值
  1326. $dest_interval = 1;
  1327. }
  1328. $returnData = array("seller_data_list_origin"=>$toporigin,"toporiginMap"=>array_reverse($toporiginMap),"toporiginType"=>$toporiginType,
  1329. "seller_data_list_destination"=>$topdestination,"topdestinationinMap"=>array_reverse($topdestinationinMap),"topdestinationinType"=>$topdestinationinType,
  1330. "min" => 0,"Max" =>$interval*10,"interval" =>$interval,
  1331. "dest_min" => 0,"dest_Max" =>$dest_interval*10,"dest_interval" =>$dest_interval);
  1332. return $returnData;
  1333. }
  1334. public static function getTopBarNew(){
  1335. //分担查询
  1336. include ONLINE_ROOT . 'libs' . DS . 'map_config.ini.php';
  1337. $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1338. $sqlWhere = " " . $sqlWhere;
  1339. $date_type = strtolower($_REQUEST["date_type"]);
  1340. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start']))
  1341. $sqlWhere .= " and $date_type >= '" . common::usDate2sqlDate($_REQUEST['date_start']) . " 00:00:00'";
  1342. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end']))
  1343. $sqlWhere .= " and $date_type <= '" . common::usDate2sqlDate($_REQUEST['date_end']) . " 23:59:59'";
  1344. $transportation = $_REQUEST["transportation"];
  1345. if(!is_array($transportation)){
  1346. $transportation = array($transportation);
  1347. }
  1348. $mode_param = "";
  1349. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  1350. $mode_param = "'sea','air','road'";
  1351. }else{
  1352. $transport_mode = utils::implode(';', $transportation);
  1353. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  1354. }
  1355. $sqlWhere .= " and transport_mode in ($mode_param)";
  1356. $toporiginType = "shippr_uncode";
  1357. $shippr_uncode_10_sql ="with aa as (select count(shippr_uncode) as num,shippr_uncode,
  1358. (array_agg(shipper_city))[1] AS shipper_city from public.kln_ocean
  1359. where 1=1 and COALESCE(shippr_uncode,'')<>'' $sqlWhere group by shippr_uncode order by num desc limit 10)
  1360. select aa.* from aa ";
  1361. $shippr_uncode_10 = $mapdb->GetAll($shippr_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $shippr_uncode_10_sql), 0));
  1362. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1363. if(utils::count($shippr_uncode_10) == 1 && empty($shippr_uncode_10[0]["shippr_uncode"])){
  1364. $toporiginType = "fport_of_loading_un";
  1365. $shippr_uncode_10_sql = "with aa as (select count(fport_of_loading_un) as num,fport_of_loading_un as shippr_uncode
  1366. from public.kln_ocean where 1=1 and COALESCE(fport_of_loading_un,'')<>'' $sqlWhere group by fport_of_loading_un order by num desc limit 10)
  1367. select aa.* from aa ";
  1368. $shippr_uncode_10 = $mapdb->GetAll($shippr_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $shippr_uncode_10_sql), 0));
  1369. }
  1370. $topdestinationinType = "consignee_uncode";
  1371. $consignee_uncode_10_sql = "with aa as (select count(consignee_uncode) as num,consignee_uncode,
  1372. (array_agg(consignee_city))[1] AS consignee_city
  1373. from public.kln_ocean where 1=1 and COALESCE(consignee_uncode,'')<>'' $sqlWhere group by consignee_uncode order by num desc limit 10)
  1374. select aa.* from aa";
  1375. $consignee_uncode_10 = $mapdb->GetAll($consignee_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $consignee_uncode_10_sql), 0));
  1376. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1377. if(utils::count($consignee_uncode_10) == 1 && empty($consignee_uncode_10[0]["consignee_uncode"])){
  1378. $topdestinationinType = "mport_of_discharge_un";
  1379. $consignee_uncode_10_sql = "with aa as (select count(mport_of_discharge_un) as num,mport_of_discharge_un as consignee_uncode from public.kln_ocean where 1=1 and COALESCE(mport_of_discharge_un,'')<>'' $sqlWhere group by mport_of_discharge_un order by num desc limit 10)
  1380. select aa.* from aa";
  1381. $consignee_uncode_10 = $mapdb->GetAll($consignee_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $consignee_uncode_10_sql), 0));
  1382. }
  1383. $toporigin = array();
  1384. $toporiginMap = array();
  1385. $i = 0;
  1386. $origiNunMax = 0;
  1387. foreach($shippr_uncode_10 as $orgin){
  1388. $i = $i + 1;
  1389. $map =common::excuteObjectSql("select lon as lng, lat as lat,
  1390. '' as label, '' as infor, 3 as sort,
  1391. null::timestamp without time zone as stime,''::text as ptype
  1392. from vessel.vt_unlocode where (lat<=90 and lat>=-90) and (lon<=180 and lon>=-180) and lon is not null and lat is not null and uncode='".$orgin['shippr_uncode']."'");
  1393. //$json = '{"lng":121.8525,"lat":29.926545,"label":"'.$orgin['origin'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1394. //$map = json_decode($json,true);
  1395. if(!empty($map)){
  1396. $toporiginMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1397. "divIcon" => array("iconSize"=>0),
  1398. "name" =>$orgin['shippr_uncode'],
  1399. "color" =>common::getItemStyle("top",$i),
  1400. "value" =>$orgin['num'],
  1401. "textcolor" =>"#FFF");
  1402. }
  1403. //查询uncode,对应的city
  1404. $city = "";
  1405. if($toporiginType == "shippr_uncode"){
  1406. $city = $orgin['shipper_city'];
  1407. }
  1408. //$city 做假数据
  1409. $toporigin[] = array("name"=>$orgin['shippr_uncode'],"city_name"=>$city,"value"=>$orgin['num'],"color"=>common::getItemStyle("top",$i));
  1410. $origiNunMax = $origiNunMax < $orgin['num'] ? $orgin['num'] : $origiNunMax;
  1411. }
  1412. $topdestination = array();
  1413. $topdestinationinMap = array();
  1414. $i = 0;
  1415. $agentiNunMax = 0;
  1416. foreach($consignee_uncode_10 as $agent){
  1417. $i = $i + 1;
  1418. $map =common::excuteObjectSql("select lon as lng, lat as lat,
  1419. '' as label, '' as infor, 3 as sort,
  1420. null::timestamp without time zone as stime,''::text as ptype
  1421. from vessel.vt_unlocode where (lat<=90 and lat>=-90) and (lon<=180 and lon>=-180) and lon is not null and lat is not null and uncode='".$agent['consignee_uncode']."' ");
  1422. // $json = '{"lng":"100.78594000","lat":"13.68521000","label":"'.$agent['agent'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1423. // $map = json_decode($json,true);
  1424. if(!empty($map)){
  1425. $topdestinationinMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1426. "divIcon" => array("iconSize"=>0),
  1427. "name" =>$agent['consignee_uncode'],
  1428. "color" =>common::getItemStyle("top",$i),
  1429. "value" =>$agent['num'],
  1430. "textcolor" =>"#FFF");
  1431. }
  1432. //查询uncode,对应的city
  1433. $city = "";
  1434. if($topdestinationinType == "consignee_uncode"){
  1435. $city = $agent['consignee_city'];
  1436. }
  1437. //$city 做假数据
  1438. $topdestination[] = array("name"=>$agent['consignee_uncode'],"city_name"=>$city,"value"=>$agent['num'],"color"=>common::getItemStyle("top",$i));
  1439. $agentiNunMax = $agentiNunMax < $agent['num'] ? $agent['num'] : $agentiNunMax;
  1440. }
  1441. //处理返回原表数据格式
  1442. $interval = utils::calculateTicks(0,$origiNunMax,10);
  1443. if($interval == 0){
  1444. //处理返回默认值
  1445. $interval = 1;
  1446. }
  1447. $dest_interval = utils::calculateTicks(0,$agentiNunMax,10);
  1448. if($dest_interval == 0){
  1449. //处理返回默认值
  1450. $dest_interval = 1;
  1451. }
  1452. $returnData = array("seller_data_list_origin"=>$toporigin,"toporiginMap"=>array_reverse($toporiginMap),"toporiginType"=>$toporiginType,
  1453. "seller_data_list_destination"=>$topdestination,"topdestinationinMap"=>array_reverse($topdestinationinMap),"topdestinationinType"=>$topdestinationinType,
  1454. "min" => 0,"Max" =>$interval*10,"interval" =>$interval,
  1455. "dest_min" => 0,"dest_Max" =>$dest_interval*10,"dest_interval" =>$dest_interval);
  1456. return $returnData;
  1457. }
  1458. public static function getRevenue(){
  1459. //$data = '{"bar_title":"Total: 0","barList":["DEC,23","JAN,24","FEB,24","MAR,24","APR,24","MAY,24","JUN,24","JUL,24","AUG,24","SEP,24","OCT,24","NOV,24"],"barSeries":[{"name":"USD","type":"bar","data":[1,1,1,1,1,1,1,1,1,1,1,1],"emphasis":{"disabled":true,"focus":"none"},"itemStyle":{"color":"#FF7500","borderRadius":6},"label":{"show":false,"color":"#646A73","position":"top","fontFamily":"Lato-Light","hideWhenMouseLeave":false}},{"name":"THB","type":"bar","data":[2,2,2,2,2,2,2,2,2,2,2,2],"emphasis":{"disabled":true,"focus":"none"},"itemStyle":{"color":"#FFAC66","borderRadius":6},"label":{"show":false,"color":"#646A73","position":"top","fontFamily":"Lato-Light","hideWhenMouseLeave":false}},{"name":"SGD","type":"bar","data":[3,3,3,3,3,3,3,3,3,3,3,3],"emphasis":{"disabled":true,"focus":"none"},"itemStyle":{"color":"#FFE3CC","borderRadius":6},"label":{"show":false,"color":"#646A73","position":"top","fontFamily":"Lato-Light","hideWhenMouseLeave":false}}],"Max":5,"interval":1,"download_name":"Rvenue","isShowTooltips":true}';
  1460. //return json_decode($data,true);
  1461. $date_from = null;
  1462. $date_to = null;
  1463. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start'])){
  1464. $date_start = common::dateFormatToYM($_REQUEST['date_start']);
  1465. $date_from = $date_start."-01";
  1466. }
  1467. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end'])){
  1468. $date_end = common::dateFormatToYM($_REQUEST['date_end']);
  1469. $date_to = date('Y-m-t', strtotime($date_end."-01"));
  1470. }
  1471. $param = '{"user_login":"'._getLoginName().'","report_type":"ALL","date_from":"'.$date_from.'","date_to":"'.$date_to.'"}';
  1472. $sql = "SELECT * FROM get_customer_revenue_report('$param');FETCH ALL FROM r2;";
  1473. error_log("Revenue_sql:".$sql);
  1474. $r2_data = common::excuteListSql($sql);
  1475. //$r2_data = common::excuteListSql("select * from _test_data_table");
  1476. $barList = array();
  1477. $groupedItems = array();
  1478. foreach ($r2_data as $item) {
  1479. if(!utils::in_array($item['month'],$barList)){
  1480. $barList[] = $item['month'];
  1481. }
  1482. $groupedItems[$item['currency']][] = $item;
  1483. }
  1484. //补齐所有货币的月份
  1485. foreach($groupedItems as $ckey =>$cvalueArr){
  1486. $currency = array();
  1487. foreach($barList as $month){
  1488. $currency[] = common::findCurrencyByMonth($month,$ckey,$cvalueArr);
  1489. }
  1490. $groupedItems[$ckey] = $currency;
  1491. }
  1492. //处理barSeries
  1493. $barSeries = array();
  1494. //先准备4种颜色
  1495. $color = array("#FF7500","#FFAC66","#FFE3CC");
  1496. $index = 0;
  1497. $max = 0;
  1498. foreach($groupedItems as $currency => $series){
  1499. $series_max = 0;
  1500. $num = $index % 3;
  1501. $index = $index +1;
  1502. $tem_series = array();
  1503. $tem_series["name"] = $currency;
  1504. $tem_series["type"] = "bar";
  1505. $tem_series["emphasis"] = array("disabled"=>true,"focus"=>"none");
  1506. $tem_series["itemStyle"] = array("color"=>$color[$num],"borderRadius"=>6);
  1507. $tem_series["label"] = array("show"=>false,"color"=>"#646A73","position"=>"top","fontFamily"=>"Lato-Light","hideWhenMouseLeave"=>false);
  1508. //准备series data
  1509. $data = array();
  1510. $total = 0;
  1511. foreach($series as $_series){
  1512. $invoice_amount = empty($_series['invoice_amount'])? 0 : round($_series['invoice_amount'], 4);
  1513. $data[]=$invoice_amount;
  1514. $total = $total + $invoice_amount;
  1515. $max = $max<$_series['invoice_amount'] ? $_series['invoice_amount'] : $max;
  1516. $series_max = $series_max<$_series['invoice_amount'] ? $_series['invoice_amount'] : $series_max;
  1517. }
  1518. //计算Y坐标的间隔 每种货币的
  1519. $interval = utils::calculateTicks(0,$series_max,5);
  1520. if($interval == 0){
  1521. //处理返回默认值
  1522. $interval = 2;
  1523. }
  1524. $tem_series["Max"] = $interval*5;
  1525. $tem_series["interval"] = $interval;
  1526. $tem_series["data"] = $data;
  1527. $tem_series["total"] = floatval(number_format($total, 4, '.', ''));
  1528. $barSeries[] = $tem_series;
  1529. }
  1530. //计算Y坐标的间隔
  1531. $interval = utils::calculateTicks(0,$max,5);
  1532. if($interval == 0){
  1533. //处理返回默认值
  1534. $interval = 2;
  1535. }
  1536. $revenueBarData = array("bar_title" =>"Total:","barList" => $barList,
  1537. "barSeries" =>$barSeries,"download_name"=>"Rvenue","isShowTooltips"=>true,"Max" =>$interval*5,"interval" =>$interval);
  1538. return $revenueBarData;
  1539. }
  1540. public static function findCurrencyByMonth($month,$ckey,$cvalueArr){
  1541. $data = array("month" =>$month,"currency"=>$ckey,"invoice_amount"=>0,"sort_month"=>"");
  1542. foreach($cvalueArr as $realmonth){
  1543. if($realmonth['month'] == $month){
  1544. $data = $realmonth;
  1545. }
  1546. }
  1547. return $data;
  1548. }
  1549. public static function getdefaultManagement(){
  1550. $Management = array();
  1551. $Management[] = array("id"=>1 ,
  1552. "title"=>"KPI",
  1553. "switchValue"=>true,
  1554. "text"=>"Pie chart showing figures of shipments KPI of Departure and Arrival.");
  1555. $Management[] = array("id"=>2 ,
  1556. "title"=>"Pending",
  1557. "switchValue"=>true,
  1558. "text"=>"Pie chart showing figures of shipments which are soon to depart/arrive (Calculated from ETD/ETA).");
  1559. $Management[] = array("id"=>3 ,
  1560. "title"=>"ETD to ETA (Days)",
  1561. "switchValue"=>true,
  1562. "text"=>"Pie chart showing figures of shipments which are soon to depart/arrive (Calculated from ETD/ETA).");
  1563. $Management[] = array("id"=>4 ,
  1564. "title"=>"Container Count",
  1565. "switchValue"=>true,
  1566. "text"=>"Pie chart showing figures of shipments which are soon to depart/arrive (Calculated from ETD/ETA).");
  1567. if(_isRevenueDisplay()){
  1568. $Management[] = array("id"=>5 ,
  1569. "title"=>"Revenue Spent",
  1570. "switchValue"=>true,
  1571. "text"=>"Revenue data for the past 12 months.");
  1572. }
  1573. $Management[] = array("id"=>6 ,
  1574. "title"=>"Top 10 Origin/Destination",
  1575. "switchValue"=>true,
  1576. "text"=>"Figure of the top 10 origin/destination.",
  1577. "title1"=>"Top 10 Origin",
  1578. "title2"=>"Top 10 Destination");
  1579. $Management[] = array("id"=>7 ,
  1580. "title"=>"CO2e Emission by Origin (Top 10)",
  1581. "switchValue"=>true,
  1582. "text"=>"Figure of the CO2e Emission by origin.");
  1583. $Management[] = array("id"=>8 ,
  1584. "title"=>"CO2e Emission by Destination (Top 10)",
  1585. "switchValue"=>true,
  1586. "text"=>"Figure of the CO2e Emission by destination.");
  1587. $Management[] = array("id"=>9 ,
  1588. "title"=>"Recent Status",
  1589. "switchValue"=>true,
  1590. "text"=>"A shipment list with latest status update on top.");
  1591. return $Management;
  1592. }
  1593. /**
  1594. * Destroy Session
  1595. */
  1596. public static function sessionDestroy() {
  1597. session_destroy();
  1598. setcookie(session_name(), '', time() - 3600);
  1599. $_SESSION = array();
  1600. }
  1601. public static function dateFormatToYM($dateString){
  1602. $date = DateTime::createFromFormat('m/Y', $dateString);
  1603. $formattedDate = $date->format('Y-m'); // YYYY-MM
  1604. return $formattedDate;
  1605. }
  1606. public static function retStationInfo($address_1,$address_2,$address_3,$address_4,$city,$state,$country,$zipcode){
  1607. $stationInfo = "";
  1608. if(!empty($address_1)){
  1609. $stationInfo .= $address_1;
  1610. }
  1611. if(!empty($address_2)){
  1612. $stationInfo .= " ".$address_2;
  1613. }
  1614. if(!empty($address_3)){
  1615. $stationInfo .= " ".$address_3;
  1616. }
  1617. if(!empty($address_4)){
  1618. $stationInfo .= " ".$address_4;
  1619. }
  1620. $temp_str = "";
  1621. if(!empty($city)){
  1622. $temp_str .= $city." ";
  1623. }
  1624. if(!empty($state)){
  1625. $temp_str .= $state." ";
  1626. }
  1627. if(!empty($zipcode)){
  1628. $temp_str .= $zipcode." ";
  1629. }
  1630. if(!empty($country)){
  1631. $temp_str .= $country." ";
  1632. }
  1633. if(!empty($temp_str)){
  1634. return $stationInfo." ".trim($temp_str);
  1635. }
  1636. return $stationInfo;
  1637. }
  1638. public static function getInsertSqlNull($table_name, $values) {
  1639. $field = "";
  1640. $value = "";
  1641. foreach ($values as $k => $v) {
  1642. if ($k == 'tmp' || $k == 'action' || $k == 'operate' || $k == 'x' || $k == 'y') {
  1643. continue;
  1644. }
  1645. if (is_array($v)) {
  1646. $v = utils::implode(",", $v);
  1647. }
  1648. if (empty($field)) {
  1649. $field = $k;
  1650. if (utils::checkExist($v, 'now()')) {
  1651. $value = $v;
  1652. } elseif ($v == null) {
  1653. $value .= 'null';
  1654. } elseif ($v == 'TRUE' || $v == 'FALSE') {
  1655. $value .= $v;
  1656. } else {
  1657. $value = '\'' . common::check_input($v) . '\'';
  1658. }
  1659. } else {
  1660. $field .= ',' . $k;
  1661. if (utils::checkExist($v, 'now()'))
  1662. $value .= ', now()';
  1663. elseif ($v == null) {
  1664. $value .= ',null';
  1665. } else if ($v == 'TRUE' || $v == 'FALSE') {
  1666. $value .= ',' . $v;
  1667. } else {
  1668. $value .= ', \'' . common::check_input($v) . '\'';
  1669. }
  1670. }
  1671. }
  1672. return 'insert into ' . $table_name . '(' . $field . ') values (' . $value . ')';
  1673. }
  1674. //密码规则验证
  1675. public static function checkPasswordRule($login, $new_password){
  1676. $sql="select item_value from config where item='passwordCheckRules'";
  1677. $rs = common::excuteObjectSql($sql);
  1678. $str = "";
  1679. if (!empty($rs)) {
  1680. $passwordCheckRules = json_decode($rs["item_value"],true);
  1681. //校验使用次数
  1682. if (!empty($passwordCheckRules["pastPasswordCheckNum"])) {
  1683. $sql = "select password from public.ra_online_user_password_history where lower(user_login)='".common::check_input(strtolower($login))."' order by id desc limit ".$passwordCheckRules["pastPasswordCheckNum"];
  1684. $passwords = common::excuteListSql($sql);
  1685. foreach ($passwords as $pwd) {
  1686. if ($pwd['password'] == $new_password) {
  1687. $str = "This password has been recently used";
  1688. }
  1689. }
  1690. }
  1691. if(empty($str)){
  1692. $str = utils::checkPassword($new_password,$passwordCheckRules,$login);
  1693. }
  1694. }else{
  1695. $str = utils::checkPassword($new_password);
  1696. }
  1697. return $str;
  1698. }
  1699. public static function getMilestonesInfo($ocean,$transport_mode,$_schemas,$EDI315TimeAndLocation=array()){
  1700. //Milestones info列名固定
  1701. $Milestones_column = array();
  1702. $Milestones_column[] = array("title" =>"Milestones","field" =>"milestones","formatter" =>"normal","type" =>"normal");
  1703. $Milestones_column[] = array("title" =>"Date Time","field" =>"date_time","formatter" =>"dateTime","type" =>"normal");
  1704. $Milestones_column[] = array("title" =>"Locations","field" =>"locations","formatter" =>"normal","type" =>"normal");
  1705. $Milestones_column[] = array("title" =>"Remarks","field" =>"remarks","formatter" =>"normal","type" =>"normal");
  1706. //EDI315 有关联查询,以那个为准。但是如果是手工录入或者不是EDI 进去的Milestone的情况,这以这个为准
  1707. $Milestones_NO_Mapping = common::getMilestones_NO_Mapping_Data($ocean);
  1708. //Milestones 数据信息待定
  1709. $Milestones_data = array();
  1710. if($transport_mode == 'sea'){
  1711. $Milestones_data_arr = common::excuteListSql("select sn.description,act_date||' '||COALESCE(act_time,'') as date_time,
  1712. remark,timezone,a.code
  1713. from public.ocean_milestone a
  1714. inner join public.customer_service_milestone_sno sn on sn.code=a.code and sn.type = 'sea'
  1715. where a.serial_no='".$ocean["serial_no"]."' and act_date is not null order by sn.sno asc");
  1716. }else{
  1717. $Milestones_data_arr = common::excuteListSql("select sn.description,act_date||' '||COALESCE(act_time,'') as date_time,
  1718. remark,timezone,a.code
  1719. from $_schemas.air_milestone a
  1720. inner join public.customer_service_milestone_sno sn on sn.code=a.code and sn.type = 'air'
  1721. where a.serial_no='".$ocean["serial_no"]."' and act_date is not null order by sn.sno asc");
  1722. }
  1723. foreach($Milestones_data_arr as $mda){
  1724. $timezone = "";
  1725. $IFFICC_locations ="";
  1726. if(!empty($EDI315TimeAndLocation[$mda['code']])){
  1727. $edi315Info = $EDI315TimeAndLocation[$mda['code']];
  1728. if(!empty($edi315Info)){
  1729. $timezone = $edi315Info['timezone'];
  1730. }
  1731. //IFFICC 比较特殊用EDI的locations
  1732. if($mda['code'] == "IFFICC"){
  1733. $IFFICC_locations = $edi315Info['location'];
  1734. }
  1735. }else{
  1736. $edi315Info = $Milestones_NO_Mapping[$mda['code']];
  1737. if(!empty($edi315Info)){
  1738. $timezone = $edi315Info['timezone'];
  1739. }
  1740. }
  1741. //locations 以配置的信息为准
  1742. $locations = "";
  1743. $edi315Info = $Milestones_NO_Mapping[$mda['code']];
  1744. if(!empty($edi315Info)){
  1745. $locations = $edi315Info['location'];
  1746. if($mda['code'] == "IFFICC" && !empty($IFFICC_locations)){
  1747. $locations = $IFFICC_locations;
  1748. }
  1749. }
  1750. $Milestones_data[] = array("milestones"=>$mda['description'],"date_time"=>$mda['date_time'],"timezone" =>$timezone,
  1751. "locations" => $locations, "remarks" =>$mda['remark']);
  1752. }
  1753. $Milestones = array("Milestones_column"=>$Milestones_column,"Milestones_data" =>$Milestones_data);
  1754. return $Milestones;
  1755. }
  1756. /**
  1757. * 查询uncode 对应的时区
  1758. */
  1759. public static function getCityPortsInfo($uncodes){
  1760. $data =array();
  1761. $sql = "select time_zone as timezonecode,uncode as ctrycitycode from public.city_timezone where lower(uncode) ". common::getInNotInSql($uncodes);
  1762. $uncode_rs = common::excuteListSql($sql);
  1763. foreach($uncode_rs as $value){
  1764. $data[$value['ctrycitycode']] = $value['timezonecode'];
  1765. }
  1766. return $data;
  1767. }
  1768. /**
  1769. * EDI315 有关联查询,以那个为准。但是如果是手工录入或者没有对应的情况,这以这个为准
  1770. */
  1771. public static function getMilestones_NO_Mapping_Data($ocean){
  1772. $Milestones_NO_Mapping = array();
  1773. //取origin $ocean['aa_city'] 不是必需,对应文件里未提location来源
  1774. $Milestones_NO_Mapping['IFFBCF'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1775. $Milestones_NO_Mapping['IFFBCR'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1776. $Milestones_NO_Mapping['IFFCPU'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1777. $Milestones_NO_Mapping['IFFSIL'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1778. $Milestones_NO_Mapping['IFFEDO'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1779. $Milestones_NO_Mapping['IFFECC'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1780. //Place of Receipt
  1781. $Milestones_NO_Mapping['IFFREC'] = array("code"=>"por/pol","timezone"=>$ocean['por_timezone'],"location"=>$ocean['por_uncity']);
  1782. $Milestones_NO_Mapping['IFFECP'] = array("code"=>"por/pol","timezone"=>$ocean['por_timezone'],"location"=>$ocean['por_uncity']);
  1783. //Port of loading
  1784. $Milestones_NO_Mapping['IFFONB'] = array("code"=>"por/pol","timezone"=>$ocean['pol_timezone'],"location"=>$ocean['pol_uncity']);
  1785. $Milestones_NO_Mapping['IFFDEP'] = array("code"=>"por/pol","timezone"=>$ocean['pol_timezone'],"location"=>$ocean['pol_uncity']);
  1786. //取destination $ocean['dd_city']不是必需
  1787. $Milestones_NO_Mapping['IFFCSN'] = array("code"=>"destination","timezone"=>$ocean['dd_timezone'],"location"=>"");
  1788. $Milestones_NO_Mapping['IFFIDO'] = array("code"=>"destination","timezone"=>$ocean['dd_timezone'],"location"=>"");
  1789. //取Port of discharge
  1790. $Milestones_NO_Mapping['IFFARR'] = array("code"=>"mpod","timezone"=>$ocean['mpod_timezone'],"location"=>$ocean['mpod_uncity']);
  1791. $Milestones_NO_Mapping['IFFUND'] = array("code"=>"mpod/pod/fd","timezone"=>$ocean['mpod_timezone'],"location"=>$ocean['mpod_uncity']);
  1792. $Milestones_NO_Mapping['IFFICC'] = array("code"=>"mpod","timezone"=>$ocean['mpod_timezone'],"location"=>$ocean['mpod_uncity']);
  1793. //Place of Delivery
  1794. $Milestones_NO_Mapping['IFFAFD'] = array("code"=>"pod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1795. $Milestones_NO_Mapping['IFFCTA'] = array("code"=>"pod/mpod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1796. $Milestones_NO_Mapping['IFFADW'] = array("code"=>"pod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1797. $Milestones_NO_Mapping['IFFDDW'] = array("code"=>"pod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1798. $Milestones_NO_Mapping['IFFPPD'] = array("code"=>"mpod/pod/fd","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1799. $Milestones_NO_Mapping['IFFECR'] = array("code"=>"mpod/pod/fd","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1800. //final_destination $ocean['fd_city']不是必需
  1801. $Milestones_NO_Mapping['IFFDEL'] = array("code"=>"fd","timezone"=>$ocean['_fd_timezone'],"location"=>"");
  1802. $Milestones_NO_Mapping['IFFHBL'] = array("code"=>"fd","timezone"=>$ocean['_fd_timezone'],"location"=>"");
  1803. return $Milestones_NO_Mapping;
  1804. }
  1805. /**
  1806. * 这个详细查询已经带模式了
  1807. */
  1808. public static function getEDI315StatusForDetail($serial_no){
  1809. $data = array();
  1810. $ctnr_sql = "SELECT oc.ctnr, oc.serial_no,oc.size FROM oc_container oc LEFT JOIN ocean o ON oc.serial_no = o.serial_no
  1811. WHERE o.serial_no='$serial_no'";
  1812. $ctnr_data = common::excuteListSql($ctnr_sql);
  1813. $containerStatusData = array();
  1814. $VD = "";
  1815. $VA = "";
  1816. $VD_RELAY = "";
  1817. $VA_RELAY = "";
  1818. foreach ($ctnr_data as $cd){
  1819. //存在柜号为空的数据情况
  1820. if(empty($cd['ctnr'])){
  1821. continue;
  1822. }
  1823. //(select uncity from public.ports where uncode = s.event_code) as uncity, 按新版的逻辑这个先取消掉
  1824. $ctnr_status_sql = "select s.source_id, s.event_base as event,
  1825. to_char(to_timestamp(s.event_date, 'YYYYMMDD'), 'YYYY-MM-DD') as eventdate,
  1826. to_char(to_timestamp(s.event_time, 'HH24MI'), 'HH24:MI') as eventtime,
  1827. e.description,s.event_type as eventtype,
  1828. s.event_code as eventcode, s.event_city as eventcity,
  1829. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1830. s.event_city as uncity,
  1831. case when s.event_base ='I' or s.event_base ='TR' then 'IFFREC'::text
  1832. when s.event_base ='AE' then 'IFFONB'::text
  1833. when s.event_base ='VD' then 'IFFDEP'::text
  1834. when s.event_base ='EB' or s.event_base ='VA' then 'IFFARR'::text
  1835. when s.event_base ='UV' then 'IFFUND'::text
  1836. when s.event_base ='VA' then 'IFFAFD'::text
  1837. when s.event_base ='AV' then 'IFFCTA'::text
  1838. when s.event_base ='CT' then 'IFFICC'::text
  1839. when s.event_base ='OA' or s.event_base ='D' then 'IFFPPD'::text
  1840. when s.event_base ='RD' then 'IFFECR'::text
  1841. when s.event_base ='EE' then 'IFFECP'::text
  1842. else '' ::text
  1843. end as milestone_code
  1844. from public.ra_online_container_status_v s
  1845. left join public.ra_online_edi_event e on s.event_base = e.ra_name
  1846. where s.serial_no = '" . pg_escape_string($cd['serial_no']) . "'
  1847. and s.container_no = '" . pg_escape_string($cd['ctnr']) . "' and is_display = true
  1848. order by to_timestamp(s.event_date, 'YYYYMMDD') desc,
  1849. to_timestamp(s.event_time, 'HH24MI') desc,e.ra_order desc";
  1850. $ctnr_status = common::excuteListSql($ctnr_status_sql);
  1851. //Container_Status 新版只显示几个状态, CTNR# EE I AE VD VA
  1852. $container_status_column = array("EE","I","AE","VD","VA");
  1853. $containerStatusDataTemp = array();
  1854. $content = array();
  1855. //按顺序处理 新版只显示几个状态
  1856. //foreach($container_status_column as $status){
  1857. foreach($ctnr_status as $event){
  1858. //if(strtolower($event['event']) == strtolower($status)){
  1859. $eventdate = $event["eventdate"];
  1860. if (empty($event["source_id"]) || $event["source_id"]==0) {
  1861. $eventdate.= " " . $event["eventtime"];
  1862. }
  1863. $location_code = $event["eventcode"];
  1864. $content[] = array("code" =>$event['event'],"title" =>$event['description'],"date"=>$eventdate,"country"=>$location_code,"timezone"=>$event['timezone']);
  1865. if(strtolower($event['event']) == "vd" && !empty($eventdate)){
  1866. $VD = $eventdate;
  1867. }
  1868. if(strtolower($event['event']) == "va" && !empty($eventdate)){
  1869. $VA = $eventdate;
  1870. }
  1871. if(strtolower($event['event']) == strtolower("VD_RELAY") && !empty($eventdate)){
  1872. $VD_RELAY = $eventdate;
  1873. }
  1874. if(strtolower($event['event']) == strtolower("VA_RELAY") && !empty($eventdate)){
  1875. $VA_RELAY = $eventdate;
  1876. }
  1877. //}
  1878. }
  1879. //}
  1880. //记录所有的信息
  1881. $EDI315TimeAndLocation = array();
  1882. foreach($ctnr_status as $event){
  1883. if(!empty($EDI315TimeAndLocation['IFFARR']) && $EDI315TimeAndLocation['IFFARR']['code'] == "EB"){
  1884. //如果存在EB 的EB 的优先级最高
  1885. continue;
  1886. }
  1887. if(!empty($EDI315TimeAndLocation['IFFPPD']) && $EDI315TimeAndLocation['IFFARR']['code'] == "OA"){
  1888. //如果存在OA 的OA 的优先级最高
  1889. continue;
  1890. }
  1891. $EDI315TimeAndLocation[$event['milestone_code']] = array("code"=>$event['event'],"timezone"=>$event['timezone'],"location"=>$event['uncity']);
  1892. }
  1893. $containerStatusDataTemp['label'] = $cd['ctnr']." / ".$cd['size'];
  1894. $containerStatusDataTemp['content'] = $content;
  1895. $containerStatusData[] = $containerStatusDataTemp;
  1896. }
  1897. $data['containerStatusData'] = $containerStatusData;
  1898. $data['EDI315TimeAndLocation'] = $EDI315TimeAndLocation;
  1899. $data['VD'] = $VD;
  1900. $data['VA'] = $VA;
  1901. $data['VD_RELAY'] = $VD_RELAY;
  1902. $data['VA_RELAY'] = $VA_RELAY;
  1903. return $data;
  1904. }
  1905. public static function getEDI315Time($serial_no,$_schemas){
  1906. //Timezone From 来自于EDI315
  1907. $ctnr_sql = "SELECT oc.ctnr, oc.serial_no,oc.size FROM $_schemas.oc_container oc LEFT JOIN $_schemas.ocean o ON oc.serial_no = o.serial_no
  1908. WHERE o.serial_no='$serial_no'";
  1909. $ctnr_data = common::excuteListSql($ctnr_sql);
  1910. $EDI315TimeAndLocation = array();
  1911. foreach ($ctnr_data as $cd){
  1912. //存在柜号为空的数据情况
  1913. if(empty($cd['ctnr'])){
  1914. continue;
  1915. }
  1916. $ctnr_status_sql = "select
  1917. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1918. case when s.event_base ='I' or s.event_base ='TR' then 'IFFREC'::text
  1919. when s.event_base ='AE' then 'IFFONB'::text
  1920. when s.event_base ='VD' then 'IFFDEP'::text
  1921. when s.event_base ='EB' or s.event_base ='VA' then 'IFFARR'::text
  1922. when s.event_base ='UV' then 'IFFUND'::text
  1923. when s.event_base ='VA' then 'IFFAFD'::text
  1924. when s.event_base ='AV' then 'IFFCTA'::text
  1925. when s.event_base ='CT' then 'IFFICC'::text
  1926. when s.event_base ='OA' or s.event_base ='D' then 'IFFPPD'::text
  1927. when s.event_base ='RD' then 'IFFECR'::text
  1928. when s.event_base ='EE' then 'IFFECP'::text
  1929. else '' ::text
  1930. end as milestone_code
  1931. from public.ra_online_container_status_v s
  1932. left join public.ra_online_edi_event e on s.event_base = e.ra_name
  1933. where s.serial_no = '" . pg_escape_string($cd['serial_no']) . "'
  1934. and s.container_no = '" . pg_escape_string($cd['ctnr']) . "' and is_display = true
  1935. order by to_timestamp(s.event_date, 'YYYYMMDD') asc,
  1936. to_timestamp(s.event_time, 'HH24MI') asc,e.ra_order asc";
  1937. $ctnr_status = common::excuteListSql($ctnr_status_sql);
  1938. //记录所有的信息、替换最后一个柜子
  1939. $EDI315TimeAndLocation = array();
  1940. foreach($ctnr_status as $event){
  1941. if(!empty($EDI315TimeAndLocation['IFFARR']) && $EDI315TimeAndLocation['IFFARR']['code'] == "EB"){
  1942. //如果存在EB 的EB 的优先级最高
  1943. continue;
  1944. }
  1945. if(!empty($EDI315TimeAndLocation['IFFPPD']) && $EDI315TimeAndLocation['IFFARR']['code'] == "OA"){
  1946. //如果存在OA 的OA 的优先级最高
  1947. continue;
  1948. }
  1949. $EDI315TimeAndLocation[$event['milestone_code']] = array("code"=>$event['event'],"timezone"=>$event['timezone']);
  1950. }
  1951. }
  1952. return $EDI315TimeAndLocation;
  1953. }
  1954. public static function getMilestoneTimeAndlocations($milestone_code,$transport_mode,$serial_no,$order_from){
  1955. $EDI315TimeAndLocation = array();
  1956. if($transport_mode == "sea"){
  1957. $ctnr_sql = "SELECT oc.ctnr, oc.serial_no,oc.size FROM $order_from.oc_container oc LEFT JOIN ocean o ON oc.serial_no = o.serial_no
  1958. WHERE o.serial_no='$serial_no'";
  1959. $ctnr_data = common::excuteListSql($ctnr_sql);
  1960. foreach ($ctnr_data as $cd){
  1961. //存在柜号为空的数据情况
  1962. if(empty($cd['ctnr'])){
  1963. continue;
  1964. }
  1965. $ctnr_status_sql = "select s.source_id, s.event_base as event,
  1966. to_char(to_timestamp(s.event_date, 'YYYYMMDD'), 'YYYY-MM-DD') as eventdate,
  1967. to_char(to_timestamp(s.event_time, 'HH24MI'), 'HH24:MI') as eventtime,
  1968. e.description,s.event_type as eventtype,
  1969. s.event_code as eventcode, s.event_city as eventcity,
  1970. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1971. (select uncity from public.ports where uncode = s.event_code) as uncity,
  1972. case when s.event_base ='I' then 'IFFREC'::text
  1973. when s.event_base ='AE' then 'IFFONB'::text
  1974. when s.event_base ='VD' then 'IFFDEP'::text
  1975. when s.event_base ='EB' or s.event_base ='VA' then 'IFFARR'::text
  1976. when s.event_base ='UV' then 'IFFUND'::text
  1977. when s.event_base ='VA' then 'IFFAFD'::text
  1978. when s.event_base ='AV' then 'IFFCTA'::text
  1979. when s.event_base ='CT' then 'IFFICC'::text
  1980. when s.event_base ='OA' or s.event_base ='D' then 'IFFPPD'::text
  1981. when s.event_base ='EE' then 'IFFECP'::text
  1982. else '' ::text
  1983. end as milestone_code
  1984. from public.ra_online_container_status_v s
  1985. left join ra_online_edi_event e on s.event_base = e.ra_name
  1986. where s.serial_no = '" . pg_escape_string($cd['serial_no']) . "'
  1987. and s.container_no = '" . pg_escape_string($cd['ctnr']) . "' and is_display = true
  1988. order by to_timestamp(s.event_date, 'YYYYMMDD') asc,
  1989. to_timestamp(s.event_time, 'HH24MI') asc,e.ra_order asc";
  1990. $ctnr_status = common::excuteListSql($ctnr_status_sql);
  1991. //记录所有的信息
  1992. $EDI315TimeAndLocation = array();
  1993. foreach($ctnr_status as $event){
  1994. if(!empty($EDI315TimeAndLocation['IFFARR']) && $EDI315TimeAndLocation['IFFARR']['code'] == "EB"){
  1995. //如果存在EB 的EB 的优先级最高
  1996. continue;
  1997. }
  1998. if(!empty($EDI315TimeAndLocation['IFFPPD']) && $EDI315TimeAndLocation['IFFARR']['code'] == "OA"){
  1999. //如果存在OA 的OA 的优先级最高
  2000. continue;
  2001. }
  2002. $EDI315TimeAndLocation[$event['milestone_code']] = array("code"=>$event['event'],"timezone"=>$event['timezone'],"location"=>$event['uncity']);
  2003. }
  2004. }
  2005. }
  2006. //当前数据的所有time city 查询
  2007. $sql = common::trackingSql($serial_no,$order_from);
  2008. $data_arr = common::excuteListSql($sql);
  2009. $data = $data_arr[0];
  2010. //EDI315 有关联查询,以那个为准。但是如果是手工录入或者不是EDI 进去的Milestone的情况,这以这个为准
  2011. $Milestones_NO_Mapping = common::getMilestones_NO_Mapping_Data($data);
  2012. $timezone = "";
  2013. $IFFICC_locations ="";
  2014. if(!empty($EDI315TimeAndLocation[$milestone_code])){
  2015. $edi315Info = $EDI315TimeAndLocation[$milestone_code];
  2016. if(!empty($edi315Info)){
  2017. $timezone = $edi315Info['timezone'];
  2018. }
  2019. //IFFICC 比较特殊用EDI的locations
  2020. if($milestone_code == "IFFICC"){
  2021. $IFFICC_locations = $edi315Info['location'];
  2022. }
  2023. }else{
  2024. $edi315Info = $Milestones_NO_Mapping[$milestone_code];
  2025. if(!empty($edi315Info)){
  2026. $timezone = $edi315Info['timezone'];
  2027. }
  2028. }
  2029. //locations 以配置的信息为准
  2030. $locations = "";
  2031. $edi315Info = $Milestones_NO_Mapping[$milestone_code];
  2032. if(!empty($edi315Info)){
  2033. $locations = $edi315Info['location'];
  2034. if($milestone_code == "IFFICC" && !empty($IFFICC_locations)){
  2035. $locations = $IFFICC_locations;
  2036. }
  2037. }
  2038. return array("timezone" =>$timezone,"locations" =>$locations);
  2039. }
  2040. public static function trackingSql($serial_no,$order_from){
  2041. $_schemas = $order_from;
  2042. if($_schemas == 'public'){
  2043. $_schemas = "ocean";
  2044. }
  2045. $sql = "with o as(
  2046. SELECT oo.*,m_bol as _m_bol, h_bol as _h_bol,
  2047. (select time_zone from public.city_timezone where uncode = oo.fport_of_loading_un limit 1) as pol_timezone,
  2048. case when oo.transport_mode ='sea'
  2049. then (select uncity from $order_from.ports where uncode = oo.fport_of_loading_un limit 1)
  2050. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.fport_of_loading_un limit 1)
  2051. end as pol_uncity,
  2052. (select time_zone from public.city_timezone where uncode = oo.mport_of_discharge_un limit 1) as mpod_timezone,
  2053. case when oo.transport_mode ='sea'
  2054. then (select uncity from $order_from.ports where uncode = oo.mport_of_discharge_un limit 1)
  2055. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.mport_of_discharge_un limit 1)
  2056. end as mpod_uncity,
  2057. (select time_zone from public.city_timezone where uncode = oo.place_of_receipt_un limit 1) as por_timezone,
  2058. case when oo.transport_mode ='sea'
  2059. then (select uncity from $order_from.ports where uncode = oo.place_of_receipt_un limit 1)
  2060. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.place_of_receipt_un limit 1)
  2061. end as por_uncity,
  2062. (select time_zone from public.city_timezone where uncode = oo.place_of_delivery_un limit 1) as pod_timezone,
  2063. case when oo.transport_mode ='sea'
  2064. then (select uncity from $order_from.ports where uncode = oo.place_of_delivery_un limit 1)
  2065. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.place_of_delivery_un limit 1)
  2066. end as pod_uncity,
  2067. (select time_zone from public.city_timezone where uncode = oo.final_desination_uncode limit 1) as _fd_timezone,
  2068. case when oo.transport_mode ='sea'
  2069. then (select uncity from $order_from.ports where uncode = oo.final_desination_uncode limit 1)
  2070. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.final_desination_uncode limit 1)
  2071. end as _pd_uncity,
  2072. CASE
  2073. WHEN ((m_iffbcf is not null or m_iffbcf is null) and m_iffcpu is null and m_iffrec is null and m_iffdep is null and m_iffarr is null and m_iffdel is null) THEN 'Created'::text
  2074. WHEN ((m_iffcpu is not null or m_iffrec is not null) and m_iffdep is null and m_iffarr is null and m_iffdel is null) THEN 'Cargo Received'::text
  2075. WHEN (m_iffdep is not null and m_iffarr is null and m_iffdel is null) THEN 'Departure'::text
  2076. WHEN (m_iffarr is not null and m_iffdel is null) THEN 'Arrived'::text
  2077. WHEN (m_iffdel is not null) THEN 'Completed'::text
  2078. ELSE 'Created'::text
  2079. END AS new_status
  2080. from public.kln_ocean oo where oo.serial_no = '" . $serial_no . "' and oo.order_from = '$order_from'
  2081. )
  2082. SELECT o.* ,sh.*, cn.*,aa.*,dd.*,fd.*
  2083. from o
  2084. LEFT JOIN LATERAL ( SELECT company as cn_company,
  2085. address_1 as cn_address_1,
  2086. address_2 as cn_address_2,
  2087. address_3 as cn_address_3,
  2088. address_4 as cn_address_4,
  2089. city as cn_city, state as cn_state, zipcode as cn_zipcode, country as cn_country,
  2090. phone_1 as cn_phone
  2091. FROM $_schemas.contacts c WHERE o.consignee_id::text = c.contact_id::text) cn ON true
  2092. LEFT JOIN LATERAL ( SELECT company as sh_company,
  2093. address_1 as sh_address_1,
  2094. address_2 as sh_address_2,
  2095. address_3 as sh_address_3,
  2096. address_4 as sh_address_4,
  2097. city as sh_city, state as sh_state, zipcode as sh_zipcode, country as sh_country,
  2098. phone_1 as sh_phone
  2099. FROM $_schemas.contacts c WHERE o.shipper_id::text = c.contact_id::text) sh ON true
  2100. LEFT JOIN LATERAL ( SELECT company as aa_company,
  2101. address_1 as aa_address_1,
  2102. address_2 as aa_address_2,
  2103. address_3 as aa_address_3,
  2104. address_4 as aa_address_4,
  2105. city as aa_city, state as aa_state, zipcode as aa_zipcode, country as aa_country,
  2106. phone_1 as aa_phone,
  2107. (select time_zone from public.city_timezone where uncode = LEFT(c.country, 2) || COALESCE(c.city_code,'') limit 1) as aa_timezone
  2108. FROM $_schemas.contacts c WHERE o.origin::text = c.contact_id::text) aa ON true
  2109. LEFT JOIN LATERAL ( SELECT company as dd_company,
  2110. address_1 as dd_address_1,
  2111. address_2 as dd_address_2,
  2112. address_3 as dd_address_3,
  2113. address_4 as dd_address_4,
  2114. city as dd_city, state as dd_state, zipcode as dd_zipcode, country as dd_country,
  2115. phone_1 as dd_phone,
  2116. (select time_zone from public.city_timezone where uncode = LEFT(c.country, 2) || COALESCE(c.city_code,'') limit 1) as dd_timezone
  2117. FROM $_schemas.contacts c WHERE o.agent::text = c.contact_id::text) dd ON true
  2118. LEFT JOIN LATERAL ( SELECT
  2119. city as fd_city,
  2120. (select time_zone from public.city_timezone where uncode = LEFT(c.country, 2) || COALESCE(c.city_code,'') limit 1) as fd_timezone
  2121. FROM $_schemas.contacts c WHERE o.final_desination::text = c.contact_id::text) fd ON true";
  2122. return $sql;
  2123. }
  2124. public static function getDashboardTransportationSqlWhere(){
  2125. $transportation = $_REQUEST["transportation"];
  2126. if(!is_array($transportation)){
  2127. $transportation = array($transportation);
  2128. }
  2129. $mode_param = "";
  2130. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  2131. $mode_param = "'sea','air','road'";
  2132. }else{
  2133. $transport_mode = utils::implode(';', $transportation);
  2134. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  2135. }
  2136. return " and transport_mode in ($mode_param)";
  2137. }
  2138. /*
  2139. * Create Directory
  2140. */
  2141. public static function mkdirs($path, $mode = 0777) { //creates directory tree recursively
  2142. if (!file_exists($path)) {
  2143. if (!mkdir($path, $mode, TRUE))
  2144. return FALSE;
  2145. }
  2146. return TRUE;
  2147. }
  2148. /**
  2149. * checked is_subscribe
  2150. */
  2151. public static function checkedSubscribe($serial_no) { //creates directory tree recursively
  2152. $is_subscribe_exist = common::excuteOneSql("select user_login from public.kln_user_subscribed us
  2153. where lower(us.user_login) = '".strtolower(_getLoginName())."' and us.subscribed_serial_no = '".$serial_no."'");
  2154. if(empty($is_subscribe_exist)){
  2155. $is_subscribe = false;
  2156. }else{
  2157. $is_subscribe = true;
  2158. }
  2159. return $is_subscribe;
  2160. }
  2161. /**
  2162. * get webiste
  2163. */
  2164. public static function getWebiste($carrier) {
  2165. $website = "";
  2166. if (!empty($carrier)){
  2167. $website = common::excuteOneSql("select website from vessel_company where scac = '$carrier'");
  2168. }
  2169. if (strpos($website, ";") === FALSE){
  2170. }else{
  2171. $site = explode(";", $website);
  2172. $website = $site[0];
  2173. }
  2174. return $website;
  2175. }
  2176. public static function getWeek($week){
  2177. if ($week == "0"){
  2178. $week = "Sunday";
  2179. } elseif ($week == "1"){
  2180. $week = "Monday";
  2181. } elseif ($week == "2"){
  2182. $week = "Tuesday";
  2183. } elseif ($week == "3"){
  2184. $week = "Wednesday";
  2185. } elseif ($week == "4"){
  2186. $week = "Thursday";
  2187. } elseif ($week == "5"){
  2188. $week = "Friday";
  2189. } elseif ($week == "6"){
  2190. $week = "Sunday";
  2191. }
  2192. return $week;
  2193. }
  2194. /**
  2195. * 这里基准event 写死, 根据online查询页面的通用的来, 这里需提问确定
  2196. */
  2197. public static function getEDICtnrEvent(){
  2198. $event =array(array("event_name"=>"EE","description"=>"Empty Equipment Dispatched"),
  2199. array("event_name"=>"I","description"=>"Gate in full for a booking"),
  2200. array("event_name"=>"AE","description"=>"Container loaded on vessel"),
  2201. array("event_name"=>"VD","description"=>"Vessel Departure"),
  2202. array("event_name"=>"VA_RELAY","description"=>"Arrive Relay Port"),
  2203. array("event_name"=>"UV_RELAY","description"=>"Unloaded at Relay Port"),
  2204. array("event_name"=>"AE_RELAY","description"=>"Loaded at Relay Port"),
  2205. array("event_name"=>"VD_RELAY","description"=>"Depart Relay Port"),
  2206. array("event_name"=>"CU","description"=>"Carrier and Customs Release"),
  2207. array("event_name"=>"CT","description"=>"Customs release"),
  2208. array("event_name"=>"CR","description"=>"Carrier release"),
  2209. array("event_name"=>"VA","description"=>"Vessel Arrival"),
  2210. array("event_name"=>"UV","description"=>"Unloaded From Vessel"),
  2211. array("event_name"=>"AG","description"=>"Estimated Delivery"),
  2212. array("event_name"=>"OA","description"=>"Gate out full from final discharge port"),
  2213. array("event_name"=>"FT","description"=>"Free Time Expired"),
  2214. array("event_name"=>"AL","description"=>"Container loaded on Rail"),
  2215. array("event_name"=>"AR","description"=>"Container unloaded from Rail"),
  2216. array("event_name"=>"AV","description"=>"Shipment available for pickup or delivery"),
  2217. array("event_name"=>"D","description"=>"Gate out for delivery to customer"),
  2218. array("event_name"=>"RD","description"=>"Container returned empty"),
  2219. array("event_name"=>"C","description"=>"Vessel Estimated Time of Departure"),
  2220. array("event_name"=>"C_RELAY","description"=>"Estimated Time of Departure from Tranship Port"),
  2221. array("event_name"=>"AG_DES","description"=>"Estimated Delivery Destination"),
  2222. array("event_name"=>"IFFADW","description"=>"Shipment in CFS warehouse"),
  2223. array("event_name"=>"IFFDDW","description"=>"Shipment Out from CFS House"));
  2224. return $event;
  2225. }
  2226. /**
  2227. * 处理daily 和 week 不同周或者天的数据分组
  2228. */
  2229. public static function handleDailyWeekedData($notificationsArr){
  2230. $uniqe = array();
  2231. $ret = array();
  2232. foreach($notificationsArr as $info){
  2233. $uniqe_group_str = $info['insert_date_format'];
  2234. if(utils::in_array($uniqe_group_str,$uniqe)){
  2235. $tempArr = $ret[$uniqe_group_str];
  2236. $tempArr[] = $info;
  2237. $ret[$uniqe_group_str] = $tempArr;
  2238. } else {
  2239. $ret[$uniqe_group_str] = array($info);
  2240. $uniqe[] = $uniqe_group_str;
  2241. }
  2242. }
  2243. return $ret;
  2244. }
  2245. /**
  2246. * /unit=="Day(s)" ? "days":"hours";
  2247. */
  2248. public static function convertoVue($unit){
  2249. if(empty($unit))
  2250. return $unit;
  2251. if ($unit == "days"){
  2252. return "Day(s)";
  2253. }else{
  2254. return "Hour(s)";
  2255. }
  2256. }
  2257. /**
  2258. * vue to int
  2259. */
  2260. public static function convertoint($num){
  2261. if($num == "0"){
  2262. return intval($num);
  2263. }
  2264. return !empty($num) ? intval($num): $num;
  2265. }
  2266. //检查user name length
  2267. public static function checkUserNameLength($input) {
  2268. if(!empty($input) && strlen($input) > 50){
  2269. $data = array(
  2270. 'code' => 'no_exist',
  2271. 'login_version' => '',
  2272. 'msg' => 'The username or password you entered is incorrect'
  2273. );
  2274. common::echo_json_encode(500, $data);
  2275. exit();
  2276. }
  2277. }
  2278. //预加载写法
  2279. public static function excuteObjectPrepareSql($sql,$param) {
  2280. if (empty($sql))
  2281. exit(json_encode("Program encountered an error."));
  2282. global $db;
  2283. $stmt = $db->Prepare($sql);
  2284. $result = $db->Execute($stmt, $param);
  2285. if ($result && $result->RecordCount() > 0) {
  2286. $row = $result->fields;
  2287. return $row;
  2288. }
  2289. return null;
  2290. }
  2291. //拼接换行
  2292. public static function splicedLlineBreaks() {
  2293. return "
  2294. ";
  2295. }
  2296. /**
  2297. * chat获取自然序列号
  2298. */
  2299. public static function getChatAiSequence(){
  2300. $sequence = common::excuteOneSql("select count(*) from kln_robot_chat_log where request_time >= CURRENT_DATE");
  2301. $sequence = empty($sequence)? "1" : $sequence + 1;
  2302. $sequence = sprintf("%05d", $sequence);
  2303. return $sequence;
  2304. }
  2305. /**
  2306. * 处理chat 返回的json字符串
  2307. */
  2308. public static function getChatAimessage($message){
  2309. //格式:"```json ```"
  2310. return str_replace(["```json", "```"], "", $message);
  2311. }
  2312. public static function extractSelectFields($sql){
  2313. // 正则表达式匹配 SELECT 和 FROM 之间的内容
  2314. if (preg_match('/SELECT\s+(.*?)\s+FROM/si', $sql, $matches)) {
  2315. $selectPart = $matches[1];
  2316. // 去除注释和换行
  2317. $selectPart = preg_replace('/--.*$/m', '', $selectPart); // 去除单行注释
  2318. $selectPart = preg_replace('/\/\*.*?\*\//s', '', $selectPart); // 去除多行注释
  2319. $selectPart = str_replace(["\r", "\n"], ' ', $selectPart); // 换行替换成空格
  2320. // 分割字段
  2321. $fields = [];
  2322. foreach (explode(',', $selectPart) as $field) {
  2323. $field = trim($field);
  2324. if (empty($field)) continue;
  2325. // 匹配 AS 别名
  2326. if (preg_match('/(?:AS\s+)?(\w+)$/i', $field, $aliasMatch)) {
  2327. // 如果有别名,则使用别名
  2328. $fields[] = strtolower($aliasMatch[1]);
  2329. } else {
  2330. // 否则直接添加字段名
  2331. $fields[] = strtolower(trim($field));
  2332. }
  2333. }
  2334. return $fields;
  2335. }
  2336. return []; // 如果没有找到 SELECT 字段
  2337. }
  2338. public static function getUserCountry(){
  2339. return "deepseek";
  2340. // $contact_id = $_SESSION['ONLINE_USER']['contact_id'];
  2341. // if(empty($contact_id)){
  2342. // return "claude";
  2343. // }
  2344. // $model = "deepseek";
  2345. // $data = common::excuteListSql("select LEFT(country, 2) as country from ocean.contacts where contact_id = '$contact_id'");
  2346. // foreach($data as $country){
  2347. // if($country['country'] != "CN"){
  2348. // $model = "claude";
  2349. // }
  2350. // }
  2351. // return $model;
  2352. }
  2353. }
  2354. ?>