common.class.php 160 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341
  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) // robot 开头的都匹配上了
  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'] = ($key +1);
  921. $Management[$key]['switchValue'] = $val['switchValue'] == "true" ? true : false;
  922. if ($val['title'] == "Revenue Spent"){
  923. $Management[$key]['isRevenueDisplay'] = _isRevenueDisplay();
  924. if(!_isRevenueDisplay()){
  925. $Management[$key]['switchValue'] = false;
  926. }
  927. }
  928. }
  929. }
  930. $user_dashboard_filter = $user_management_data['dashboard_filter'];
  931. $dashboard_filter =array();
  932. if(!empty($user_dashboard_filter)){
  933. $dashboard_filter = json_decode($user_dashboard_filter,true);
  934. }else{
  935. $threeMonthsAgoTimestamp = strtotime('-3 months');
  936. $date_start = date('Y-m-d', $threeMonthsAgoTimestamp);
  937. $date_end = date('Y-m-d');
  938. $date_start_two = date('m/d/Y', $threeMonthsAgoTimestamp);
  939. $date_end_two = date('m/d/Y');
  940. //ETD
  941. $_12MonthsAgoTimestamp = strtotime('-11 months');
  942. $etd_date_start = date('Y-m', $_12MonthsAgoTimestamp);
  943. $etd_date_end = date('Y-m');
  944. $etd_date_start_two = date('m/Y', $_12MonthsAgoTimestamp);
  945. $etd_date_end_two = date('m/Y');
  946. //柜子
  947. $ctnr_date_start = date('Y-m', $_12MonthsAgoTimestamp);
  948. $ctnr_date_end = date('Y-m');
  949. $ctnr_date_start_two = date('m/Y', $_12MonthsAgoTimestamp);
  950. $ctnr_date_end_two = date('m/Y');
  951. //Top
  952. $top_date_start = date('Y-m-d', $_12MonthsAgoTimestamp);
  953. $top_date_end = date('Y-m-d');
  954. $top_date_start_two = date('m/d/Y', $_12MonthsAgoTimestamp);
  955. $top_date_end_two = date('m/d/Y');
  956. //KPIDefaulteData
  957. $dashboard_filter['KPIDefaulteData'] = 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. //PendingDefaultData
  960. $dashboard_filter['PendingDefaultData'] = array("transportation" =>array('All'),"date_type"=>"ETD","date_start"=>"","date_start_two"=>"",
  961. "date_end"=>"","date_end_two"=>"");
  962. //RecentDefaultData
  963. $dashboard_filter['RecentDefaultData'] = array("transportation" =>array('All'),"date_type"=>"ETD","date_start"=>$date_start_two,"date_start_two"=>$date_start,
  964. "date_end"=>$date_end_two,"date_end_two"=>$date_end);
  965. //ETDDefaultData
  966. $dashboard_filter['ETDDefaultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$etd_date_start_two,"date_start_two"=>$etd_date_start,
  967. "date_end"=>$etd_date_end_two,"date_end_two"=>$etd_date_end);
  968. //ContainerefaultData
  969. $dashboard_filter['ContainerefaultData'] = array("transportation" =>array('Sea'),"date_type"=>"ETA","date_start"=>$ctnr_date_start_two,"date_start_two"=>$ctnr_date_start,
  970. "date_end"=>$ctnr_date_end_two,"date_end_two"=>$ctnr_date_end);
  971. //RevenueDefaultData
  972. if(_isRevenueDisplay()){
  973. $dashboard_filter['RevenueDefaultData'] = array("transportation" =>array('All'),"date_type"=>"Invoice Issue Date","date_start"=>$ctnr_date_start_two,"date_start_two"=>$ctnr_date_start,
  974. "date_end"=>$ctnr_date_end_two,"date_end_two"=>$ctnr_date_end);
  975. }
  976. //Top10faultData
  977. $dashboard_filter['Top10faultData'] = 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. //OriginCo2Top10faultData
  980. $dashboard_filter['OriginCo2Top10faultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$top_date_start_two,"date_start_two"=>$top_date_start,
  981. "date_end"=>$top_date_end_two,"date_end_two"=>$top_date_end);
  982. //DestinationCo2Top10faultData
  983. $dashboard_filter['DestinationCo2Top10faultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$top_date_start_two,"date_start_two"=>$top_date_start,
  984. "date_end"=>$top_date_end_two,"date_end_two"=>$top_date_end);
  985. }
  986. return array("Management" => $Management,"dashboard_filter" =>$dashboard_filter);
  987. }
  988. public static function getItemStyle($type,$code){
  989. if($type == 'r1'){
  990. $data = array("0-20 Days" =>"#ffc594",
  991. "20-40 Days" =>"#ff9e4c",
  992. "40-60 Days" =>"#ff7500",
  993. "60-80 Days" =>"#ff3d00",
  994. "Over 80 Days" =>"#d50000");
  995. return $data[$code];
  996. }
  997. if($type == 'r4' || $type == 'r3' || $type == 'atd_r4' || $type == 'ata_r3'){
  998. $data = array("0 Day" =>"#ffc594",
  999. "Today" =>"#ffc594",
  1000. "1-2 Days" =>"#ff9e4c",
  1001. "3-6 Days" =>"#ff7500",
  1002. "7 Days" =>"#ff3d00");
  1003. return $data[$code];
  1004. }
  1005. if($type == 'r2' || utils::startWith($type,"co2e")){
  1006. $data = array("45" =>"#FFE3CC",
  1007. "40" =>"#FFAC66",
  1008. "20" =>"#FF7500",
  1009. "air" =>"#FFE3CC",
  1010. "sea" =>"#FFAC66",
  1011. "road" =>"#FF7500");
  1012. return $data[$code];
  1013. }
  1014. if($type == "top"){
  1015. $data = array("1" =>"#FF7500",
  1016. "2" =>"#ff9033",
  1017. "3" =>"#ff9e4d",
  1018. "4" =>"#ffac66",
  1019. "5" =>"#ffba80",
  1020. "6" =>"#ffc899",
  1021. "7" =>"#ffd6b3",
  1022. "8" =>"#ffe3cc",
  1023. "9" =>"#fff1e6",
  1024. "10" =>"#fff1e6");
  1025. return $data[$code];
  1026. }
  1027. }
  1028. //处理返回原表数据格式
  1029. public static function mian_repot_do($value,$type,$totalValue){
  1030. $data = array();
  1031. $value_arr = json_decode($value,true);
  1032. //r1 是 ETD to ETA (Days)圆形图表数据结构返回
  1033. if($type == 'r1'){
  1034. $ETDList = array();
  1035. foreach($value_arr as $arr){
  1036. $color = common::getItemStyle($type,$arr['name']);
  1037. $ETDList[] = array("value" =>intval($arr['value']),"name" =>$arr['name'],"itemStyle" =>array("color" =>$color));
  1038. }
  1039. // 排序依据的键数组(这里我们用一个数字数组来表示)
  1040. $order = ["0-20 Days", "20-40 Days", "40-60 Days","60-80 Days","Over 80 Days"];
  1041. $ETDList = utils::arrayOrderBykeys($order,$ETDList,"name");
  1042. //$ETDList = array_reverse($ETDList);
  1043. $ETD_Title = "Total: $totalValue";
  1044. $data = array("ETDList" =>$ETDList,"ETD_Radius"=>array('50%','80%'),"ETD_Title" =>$ETD_Title,"download_name" => "ETD to ETA (Days)");
  1045. }
  1046. if($type == 'r4' || $type == 'r3'){
  1047. //重新整理一下数据,给UI一致
  1048. $data_kd = array();
  1049. foreach($value_arr as $arr){
  1050. if(stripos("Today", $arr['name']) !== false){
  1051. $color = common::getItemStyle($type,"Today");
  1052. if(empty($data_kd["0"])){
  1053. $data_kd["0"] = array("value" =>intval($arr['value']),"name" =>"≤1 Day","itemStyle" =>array("color" =>$color));
  1054. }else{
  1055. $data_kd["0"]["value"] = $data_kd["0"]["value"] + intval($arr['value']);
  1056. }
  1057. }
  1058. if(stripos("+1 Days/+2 Days", $arr['name']) !== false){
  1059. $color = common::getItemStyle($type,"1-2 Days");
  1060. if(empty($data_kd["1"])){
  1061. $data_kd["1"] = array("value" =>intval($arr['value']),"name" =>"1-2 Days","itemStyle" =>array("color" =>$color));
  1062. }else{
  1063. $data_kd["1"]["value"] = $data_kd["1"]["value"] + intval($arr['value']);
  1064. }
  1065. }
  1066. if(stripos("+3 Days/+4 Days/+5 Days/+6 Days", $arr['name']) !== false){
  1067. $color = common::getItemStyle($type,"3-6 Days");
  1068. if(empty($data_kd["2"])){
  1069. $data_kd["2"] = array("value" =>intval($arr['value']),"name" =>"3-6 Days","itemStyle" =>array("color" =>$color));
  1070. }else{
  1071. $data_kd["2"]["value"] = $data_kd["2"]["value"] + intval($arr['value']);
  1072. }
  1073. }
  1074. if(stripos("+7 Days/Over 7 Days", $arr['name']) !== false){
  1075. $color = common::getItemStyle($type,"7 Days");
  1076. if(empty($data_kd["3"])){
  1077. $data_kd["3"] = array("value" =>intval($arr['value']),"name" =>"≥7 Days","itemStyle" =>array("color" =>$color));
  1078. }else{
  1079. $data_kd["3"]["value"] = $data_kd["3"]["value"] + intval($arr['value']);
  1080. }
  1081. }
  1082. }
  1083. // 排序依据的键数组(这里我们用一个数字数组来表示)
  1084. $order = ["≤1 Day", "1-2 Days", "3-6 Days","≥7 Days"];
  1085. $data_kd = utils::arrayOrderBykeys($order,$data_kd,"name");
  1086. if($type == 'r4'){
  1087. $data = array("ETDList" =>$data_kd,"ETD_Radius"=>array('30%','50%'),"title1" =>"Departure","title2" =>"","download_name" => "Pending Departure");
  1088. }
  1089. if($type == 'r3'){
  1090. $data = array("ETDList" =>$data_kd,"ETD_Radius"=>array('30%','50%'),"title1" =>"Arrival","title2" =>"","download_name" => "Pending Arrival");
  1091. }
  1092. }
  1093. return $data;
  1094. }
  1095. //单独处理co2e bar
  1096. public static function getCo2eBar(){
  1097. //分担查询
  1098. include ONLINE_ROOT . 'libs' . DS . 'map_config.ini.php';
  1099. //新UI air sea road 目前只有sea
  1100. $type = $_REQUEST["r_type"];
  1101. $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1102. $sqlWhere = " " . $sqlWhere;
  1103. $date_type = strtolower($_REQUEST["date_type"]);
  1104. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start']))
  1105. $sqlWhere .= " and $date_type >= '" . common::usDate2sqlDate($_REQUEST['date_start']) . " 00:00:00'";
  1106. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end']))
  1107. $sqlWhere .= " and $date_type <= '" . common::usDate2sqlDate($_REQUEST['date_end']) . " 23:59:59'";
  1108. $transportation = $_REQUEST["transportation"];
  1109. if(!is_array($transportation)){
  1110. $transportation = array($transportation);
  1111. }
  1112. $mode_param = "";
  1113. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  1114. $mode_param = "'sea','air','road'";
  1115. }else{
  1116. $transport_mode = utils::implode(';', $transportation);
  1117. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  1118. }
  1119. $sqlWhere .= " and transport_mode in ($mode_param)";
  1120. $ContainerCount_Title = array();
  1121. //先查询总的排放量sea air road,确定排名后,在分别查询对应的sea air road
  1122. //这里的问题跟 top 一样 。总的排放量查询有问题。目前是总的排放量 暂时等于 sea的排放量
  1123. if ($type == "co2e_orgin"){
  1124. $co2e_shippr_sql = "select SUM(COALESCE(carbon_emission,0)) as catnum ,
  1125. sum(case when (1<>1 or (transport_mode='air')) then COALESCE(carbon_emission,0) else 0 end) as air_rc,
  1126. sum(case when (1<>1 or (transport_mode='sea')) then COALESCE(carbon_emission,0) else 0 end) as sea_rc,
  1127. sum(case when (1<>1 or (transport_mode='road')) then COALESCE(carbon_emission,0) else 0 end) as road_rc,
  1128. 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";
  1129. //$co2e_aLL = common::excuteListSql($co2e_shippr_sql);
  1130. $co2e_aLL = $mapdb->GetAll($co2e_shippr_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $co2e_shippr_sql), 0));
  1131. }
  1132. if ($type == "co2e_destination"){
  1133. $co2e_consignee_sql = "select SUM(COALESCE(carbon_emission,0)) as catnum ,
  1134. sum(case when (1<>1 or (transport_mode='air')) then COALESCE(carbon_emission,0) else 0 end) as air_rc,
  1135. sum(case when (1<>1 or (transport_mode='sea')) then COALESCE(carbon_emission,0) else 0 end) as sea_rc,
  1136. sum(case when (1<>1 or (transport_mode='road')) then COALESCE(carbon_emission,0) else 0 end) as road_rc,
  1137. 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";
  1138. //$co2e_aLL = common::excuteListSql($co2e_consignee_sql);
  1139. $co2e_aLL = $mapdb->GetAll($co2e_consignee_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $co2e_consignee_sql), 0));
  1140. }
  1141. //最大Y值
  1142. $maxY = 0;
  1143. $stations = array();
  1144. foreach($co2e_aLL as $val){
  1145. $ContainerCount_Title[] = $val['station'];
  1146. $maxY = $maxY > $val['catnum'] ? $maxY : $val['catnum'];
  1147. if(!empty($val['station'])){
  1148. $stations[] = $val['station'];
  1149. }
  1150. }
  1151. // $station_str = utils::implode(',',$stations);
  1152. $ContainerCounSeries = array();
  1153. $shipment_mode_arr = array("air","sea","road");
  1154. foreach($shipment_mode_arr as $_shipment_mode){
  1155. //类型有 sea air road,目前之类只查询sea的,其他为空
  1156. $shipment_mode = $_shipment_mode;
  1157. // $co2e = array();
  1158. if ($type == "co2e_orgin"){
  1159. // $co2e_shippr_sql_union = utils::_getSql($station_str,$type,$shipment_mode,$sqlWhere);
  1160. // if(!empty($co2e_shippr_sql_union)){
  1161. // $co2e = common::excuteListSql($co2e_shippr_sql_union);
  1162. // }
  1163. $download_name = "CO2e Emission by Origin (Top 10)";
  1164. }
  1165. if ($type == "co2e_destination"){
  1166. // $co2e_consignee_union = utils::_getSql($station_str,$type,$shipment_mode,$sqlWhere);
  1167. // if(!empty($co2e_consignee_union)){
  1168. // $co2e = common::excuteListSql($co2e_consignee_union);
  1169. // }
  1170. $download_name = "CO2e Emission by Destination (Top 10)";
  1171. }
  1172. $total = 0;
  1173. $max = 0;
  1174. $data = array();
  1175. foreach($co2e_aLL as $val){
  1176. $catnum = $shipment_mode."_rc";
  1177. $data[] = empty($val[$catnum])? 0 : round($val[$catnum], 4);
  1178. $total = $total + $val[$catnum];
  1179. $max = $max < $val[$catnum] ? $val[$catnum] : $max;
  1180. }
  1181. $ContainerCounSeries[$shipment_mode] = array("data"=>$data,"total"=>$total,"max"=>$max);
  1182. }
  1183. //处理返回时数据格式 其实不太需要计算最大值,在最开始总量查询的时候以及查询出来
  1184. $ContainerCounSeries_return = array();
  1185. foreach($ContainerCounSeries as $k =>$v){
  1186. $color = common::getItemStyle($type,$k);
  1187. $ContainerCounSeries_return[] = array("name"=>$k,"type"=>"bar","emphasis" => array("focus" =>"none"),
  1188. "stack" =>"总计","data" =>$v['data'],"itemStyle" =>array("color" =>$color),'barWidth'=>'40');
  1189. }
  1190. //处理返回原表数据格式
  1191. //计算刻度值 最小值是0,最大值是3000,刻度是500 interval
  1192. $interval = utils::calculateTicks(0,$maxY,10);
  1193. if($interval == 0){
  1194. //处理返回默认值
  1195. $interval = 1;
  1196. }
  1197. $returnData = array("ContainerCount_Title"=>"","ContainerCountList" =>$ContainerCount_Title,"ContainerCounSeries" =>$ContainerCounSeries_return,
  1198. "min" => 0,"Max" =>$interval*10,"interval" =>$interval,"download_name" => $download_name);
  1199. return $returnData;
  1200. }
  1201. public static function getTopBar(){
  1202. $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1203. $sqlWhere = " " . $sqlWhere;
  1204. $date_type = strtolower($_REQUEST["date_type"]);
  1205. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start']))
  1206. $sqlWhere .= " and $date_type >= '" . common::usDate2sqlDate($_REQUEST['date_start']) . " 00:00:00'";
  1207. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end']))
  1208. $sqlWhere .= " and $date_type <= '" . common::usDate2sqlDate($_REQUEST['date_end']) . " 23:59:59'";
  1209. $transportation = $_REQUEST["transportation"];
  1210. if(!is_array($transportation)){
  1211. $transportation = array($transportation);
  1212. }
  1213. $mode_param = "";
  1214. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  1215. $mode_param = "'sea','air','road'";
  1216. }else{
  1217. $transport_mode = utils::implode(';', $transportation);
  1218. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  1219. }
  1220. $sqlWhere .= " and transport_mode in ($mode_param)";
  1221. $toporiginType = "shippr_uncode";
  1222. $shippr_uncode_10_sql ="with aa as (select count(shippr_uncode) as num,shippr_uncode,
  1223. (array_agg(shipper_city))[1] AS shipper_city from public.kln_ocean
  1224. where 1=1 and COALESCE(shippr_uncode,'')<>'' $sqlWhere group by shippr_uncode order by num desc limit 10)
  1225. select aa.*,dd.* from aa
  1226. left join LATERAL ( select lon as lng, lat as lat,
  1227. '' as label, '' as infor, 3 as sort,
  1228. null::timestamp without time zone as stime,''::text as ptype
  1229. 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";
  1230. $shippr_uncode_10 = common::excuteListSql($shippr_uncode_10_sql);
  1231. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1232. if(utils::count($shippr_uncode_10) == 1 && empty($shippr_uncode_10[0]["shippr_uncode"])){
  1233. $toporiginType = "fport_of_loading_un";
  1234. $shippr_uncode_10_sql = "with aa as (select count(fport_of_loading_un) as num,fport_of_loading_un as shippr_uncode
  1235. 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)
  1236. select aa.*,dd.* from aa
  1237. left join LATERAL ( select lon as lng, lat as lat,
  1238. '' as label, '' as infor, 3 as sort,
  1239. null::timestamp without time zone as stime,''::text as ptype
  1240. 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";
  1241. $shippr_uncode_10 = common::excuteListSql($shippr_uncode_10_sql);
  1242. }
  1243. //$toporiginType = "fport_of_loading_un";
  1244. $topdestinationinType = "consignee_uncode";
  1245. $consignee_uncode_10_sql = "with aa as (select count(consignee_uncode) as num,consignee_uncode,
  1246. (array_agg(consignee_city))[1] AS consignee_city
  1247. from public.kln_ocean where 1=1 and COALESCE(consignee_uncode,'')<>'' $sqlWhere group by consignee_uncode order by num desc limit 10)
  1248. select aa.*,dd.* from aa
  1249. left join LATERAL ( select lon as lng, lat as lat,
  1250. '' as label, '' as infor, 3 as sort,
  1251. null::timestamp without time zone as stime,''::text as ptype
  1252. 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";
  1253. $consignee_uncode_10 = common::excuteListSql($consignee_uncode_10_sql);
  1254. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1255. if(utils::count($consignee_uncode_10) == 1 && empty($consignee_uncode_10[0]["consignee_uncode"])){
  1256. $topdestinationinType = "mport_of_discharge_un";
  1257. $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)
  1258. select aa.*,dd.* from aa
  1259. left join LATERAL ( select lon as lng, lat as lat,
  1260. '' as label, '' as infor, 3 as sort,
  1261. null::timestamp without time zone as stime,''::text as ptype
  1262. 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";
  1263. $consignee_uncode_10 = common::excuteListSql($consignee_uncode_10_sql);
  1264. }
  1265. $toporigin = array();
  1266. $toporiginMap = array();
  1267. $i = 0;
  1268. $origiNunMax = 0;
  1269. foreach($shippr_uncode_10 as $orgin){
  1270. $i = $i + 1;
  1271. $map = array();
  1272. if(!empty($orgin['lat'])&&!empty($orgin['lng'])){
  1273. $map = array("lat" =>$orgin['lat'],"lng" =>$orgin['lng']);
  1274. }
  1275. //$json = '{"lng":121.8525,"lat":29.926545,"label":"'.$orgin['origin'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1276. //$map = json_decode($json,true);
  1277. if(!empty($map)){
  1278. $toporiginMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1279. "divIcon" => array("iconSize"=>0),
  1280. "name" =>$orgin['shippr_uncode'],
  1281. "color" =>common::getItemStyle("top",$i),
  1282. "value" =>$orgin['num'],
  1283. "textcolor" =>"#FFF");
  1284. }
  1285. //查询uncode,对应的city
  1286. $city = "";
  1287. if($toporiginType == "shippr_uncode"){
  1288. $city = $orgin['shipper_city'];
  1289. }
  1290. //$city 做假数据
  1291. $toporigin[] = array("name"=>$orgin['shippr_uncode'],"city_name"=>$city,"value"=>$orgin['num'],"color"=>common::getItemStyle("top",$i));
  1292. $origiNunMax = $origiNunMax < $orgin['num'] ? $orgin['num'] : $origiNunMax;
  1293. }
  1294. $topdestination = array();
  1295. $topdestinationinMap = array();
  1296. $i = 0;
  1297. $agentiNunMax = 0;
  1298. foreach($consignee_uncode_10 as $agent){
  1299. $i = $i + 1;
  1300. $map = array();
  1301. if(!empty($agent['lat'])&&!empty($agent['lng'])){
  1302. $map = array("lat" =>$agent['lat'],"lng" =>$agent['lng']);
  1303. }
  1304. // $json = '{"lng":"100.78594000","lat":"13.68521000","label":"'.$agent['agent'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1305. // $map = json_decode($json,true);
  1306. if(!empty($map)){
  1307. $topdestinationinMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1308. "divIcon" => array("iconSize"=>0),
  1309. "name" =>$agent['consignee_uncode'],
  1310. "color" =>common::getItemStyle("top",$i),
  1311. "value" =>$agent['num'],
  1312. "textcolor" =>"#FFF");
  1313. }
  1314. //查询uncode,对应的city
  1315. $city = "";
  1316. if($topdestinationinType == "consignee_uncode"){
  1317. $city = $agent['consignee_city'];
  1318. }
  1319. //$city 做假数据
  1320. $topdestination[] = array("name"=>$agent['consignee_uncode'],"city_name"=>$city,"value"=>$agent['num'],"color"=>common::getItemStyle("top",$i));
  1321. $agentiNunMax = $agentiNunMax < $agent['num'] ? $agent['num'] : $agentiNunMax;
  1322. }
  1323. //处理返回原表数据格式
  1324. $interval = utils::calculateTicks(0,$origiNunMax,10);
  1325. if($interval == 0){
  1326. //处理返回默认值
  1327. $interval = 1;
  1328. }
  1329. $dest_interval = utils::calculateTicks(0,$agentiNunMax,10);
  1330. if($dest_interval == 0){
  1331. //处理返回默认值
  1332. $dest_interval = 1;
  1333. }
  1334. $returnData = array("seller_data_list_origin"=>$toporigin,"toporiginMap"=>array_reverse($toporiginMap),"toporiginType"=>$toporiginType,
  1335. "seller_data_list_destination"=>$topdestination,"topdestinationinMap"=>array_reverse($topdestinationinMap),"topdestinationinType"=>$topdestinationinType,
  1336. "min" => 0,"Max" =>$interval*10,"interval" =>$interval,
  1337. "dest_min" => 0,"dest_Max" =>$dest_interval*10,"dest_interval" =>$dest_interval);
  1338. return $returnData;
  1339. }
  1340. public static function getTopBarNew(){
  1341. //分担查询
  1342. include ONLINE_ROOT . 'libs' . DS . 'map_config.ini.php';
  1343. $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1344. $sqlWhere = " " . $sqlWhere;
  1345. $date_type = strtolower($_REQUEST["date_type"]);
  1346. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start']))
  1347. $sqlWhere .= " and $date_type >= '" . common::usDate2sqlDate($_REQUEST['date_start']) . " 00:00:00'";
  1348. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end']))
  1349. $sqlWhere .= " and $date_type <= '" . common::usDate2sqlDate($_REQUEST['date_end']) . " 23:59:59'";
  1350. $transportation = $_REQUEST["transportation"];
  1351. if(!is_array($transportation)){
  1352. $transportation = array($transportation);
  1353. }
  1354. $mode_param = "";
  1355. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  1356. $mode_param = "'sea','air','road'";
  1357. }else{
  1358. $transport_mode = utils::implode(';', $transportation);
  1359. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  1360. }
  1361. $sqlWhere .= " and transport_mode in ($mode_param)";
  1362. $toporiginType = "shippr_uncode";
  1363. $shippr_uncode_10_sql ="with aa as (select count(shippr_uncode) as num,shippr_uncode,
  1364. (array_agg(shipper_city))[1] AS shipper_city from public.kln_ocean
  1365. where 1=1 and COALESCE(shippr_uncode,'')<>'' $sqlWhere group by shippr_uncode order by num desc limit 10)
  1366. select aa.* from aa ";
  1367. $shippr_uncode_10 = $mapdb->GetAll($shippr_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $shippr_uncode_10_sql), 0));
  1368. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1369. if(utils::count($shippr_uncode_10) == 1 && empty($shippr_uncode_10[0]["shippr_uncode"])){
  1370. $toporiginType = "fport_of_loading_un";
  1371. $shippr_uncode_10_sql = "with aa as (select count(fport_of_loading_un) as num,fport_of_loading_un as shippr_uncode
  1372. 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)
  1373. select aa.* from aa ";
  1374. $shippr_uncode_10 = $mapdb->GetAll($shippr_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $shippr_uncode_10_sql), 0));
  1375. }
  1376. $topdestinationinType = "consignee_uncode";
  1377. $consignee_uncode_10_sql = "with aa as (select count(consignee_uncode) as num,consignee_uncode,
  1378. (array_agg(consignee_city))[1] AS consignee_city
  1379. from public.kln_ocean where 1=1 and COALESCE(consignee_uncode,'')<>'' $sqlWhere group by consignee_uncode 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. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1383. if(utils::count($consignee_uncode_10) == 1 && empty($consignee_uncode_10[0]["consignee_uncode"])){
  1384. $topdestinationinType = "mport_of_discharge_un";
  1385. $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)
  1386. select aa.* from aa";
  1387. $consignee_uncode_10 = $mapdb->GetAll($consignee_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $consignee_uncode_10_sql), 0));
  1388. }
  1389. $toporigin = array();
  1390. $toporiginMap = array();
  1391. $i = 0;
  1392. $origiNunMax = 0;
  1393. foreach($shippr_uncode_10 as $orgin){
  1394. $i = $i + 1;
  1395. $map =common::excuteObjectSql("select lon as lng, lat as lat,
  1396. '' as label, '' as infor, 3 as sort,
  1397. null::timestamp without time zone as stime,''::text as ptype
  1398. 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']."'");
  1399. //$json = '{"lng":121.8525,"lat":29.926545,"label":"'.$orgin['origin'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1400. //$map = json_decode($json,true);
  1401. if(!empty($map)){
  1402. $toporiginMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1403. "divIcon" => array("iconSize"=>0),
  1404. "name" =>$orgin['shippr_uncode'],
  1405. "color" =>common::getItemStyle("top",$i),
  1406. "value" =>$orgin['num'],
  1407. "textcolor" =>"#FFF");
  1408. }
  1409. //查询uncode,对应的city
  1410. $city = "";
  1411. if($toporiginType == "shippr_uncode"){
  1412. $city = $orgin['shipper_city'];
  1413. }
  1414. //$city 做假数据
  1415. $toporigin[] = array("name"=>$orgin['shippr_uncode'],"city_name"=>$city,"value"=>$orgin['num'],"color"=>common::getItemStyle("top",$i));
  1416. $origiNunMax = $origiNunMax < $orgin['num'] ? $orgin['num'] : $origiNunMax;
  1417. }
  1418. $topdestination = array();
  1419. $topdestinationinMap = array();
  1420. $i = 0;
  1421. $agentiNunMax = 0;
  1422. foreach($consignee_uncode_10 as $agent){
  1423. $i = $i + 1;
  1424. $map =common::excuteObjectSql("select lon as lng, lat as lat,
  1425. '' as label, '' as infor, 3 as sort,
  1426. null::timestamp without time zone as stime,''::text as ptype
  1427. 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']."' ");
  1428. // $json = '{"lng":"100.78594000","lat":"13.68521000","label":"'.$agent['agent'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1429. // $map = json_decode($json,true);
  1430. if(!empty($map)){
  1431. $topdestinationinMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1432. "divIcon" => array("iconSize"=>0),
  1433. "name" =>$agent['consignee_uncode'],
  1434. "color" =>common::getItemStyle("top",$i),
  1435. "value" =>$agent['num'],
  1436. "textcolor" =>"#FFF");
  1437. }
  1438. //查询uncode,对应的city
  1439. $city = "";
  1440. if($topdestinationinType == "consignee_uncode"){
  1441. $city = $agent['consignee_city'];
  1442. }
  1443. //$city 做假数据
  1444. $topdestination[] = array("name"=>$agent['consignee_uncode'],"city_name"=>$city,"value"=>$agent['num'],"color"=>common::getItemStyle("top",$i));
  1445. $agentiNunMax = $agentiNunMax < $agent['num'] ? $agent['num'] : $agentiNunMax;
  1446. }
  1447. //处理返回原表数据格式
  1448. $interval = utils::calculateTicks(0,$origiNunMax,10);
  1449. if($interval == 0){
  1450. //处理返回默认值
  1451. $interval = 1;
  1452. }
  1453. $dest_interval = utils::calculateTicks(0,$agentiNunMax,10);
  1454. if($dest_interval == 0){
  1455. //处理返回默认值
  1456. $dest_interval = 1;
  1457. }
  1458. $returnData = array("seller_data_list_origin"=>$toporigin,"toporiginMap"=>array_reverse($toporiginMap),"toporiginType"=>$toporiginType,
  1459. "seller_data_list_destination"=>$topdestination,"topdestinationinMap"=>array_reverse($topdestinationinMap),"topdestinationinType"=>$topdestinationinType,
  1460. "min" => 0,"Max" =>$interval*10,"interval" =>$interval,
  1461. "dest_min" => 0,"dest_Max" =>$dest_interval*10,"dest_interval" =>$dest_interval);
  1462. return $returnData;
  1463. }
  1464. public static function getRevenue(){
  1465. //$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}';
  1466. //return json_decode($data,true);
  1467. $date_from = null;
  1468. $date_to = null;
  1469. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start'])){
  1470. $date_start = common::dateFormatToYM($_REQUEST['date_start']);
  1471. $date_from = $date_start."-01";
  1472. }
  1473. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end'])){
  1474. $date_end = common::dateFormatToYM($_REQUEST['date_end']);
  1475. $date_to = date('Y-m-t', strtotime($date_end."-01"));
  1476. }
  1477. $param = '{"user_login":"'._getLoginName().'","report_type":"ALL","date_from":"'.$date_from.'","date_to":"'.$date_to.'"}';
  1478. $sql = "SELECT * FROM get_customer_revenue_report('$param');FETCH ALL FROM r2;";
  1479. error_log("Revenue_sql:".$sql);
  1480. $r2_data = common::excuteListSql($sql);
  1481. //$r2_data = common::excuteListSql("select * from _test_data_table");
  1482. $barList = array();
  1483. $groupedItems = array();
  1484. foreach ($r2_data as $item) {
  1485. if(!utils::in_array($item['month'],$barList)){
  1486. $barList[] = $item['month'];
  1487. }
  1488. $groupedItems[$item['currency']][] = $item;
  1489. }
  1490. //补齐所有货币的月份
  1491. foreach($groupedItems as $ckey =>$cvalueArr){
  1492. $currency = array();
  1493. foreach($barList as $month){
  1494. $currency[] = common::findCurrencyByMonth($month,$ckey,$cvalueArr);
  1495. }
  1496. $groupedItems[$ckey] = $currency;
  1497. }
  1498. //处理barSeries
  1499. $barSeries = array();
  1500. //先准备4种颜色
  1501. $color = array("#FF7500","#FFAC66","#FFE3CC");
  1502. $index = 0;
  1503. $max = 0;
  1504. foreach($groupedItems as $currency => $series){
  1505. $series_max = 0;
  1506. $num = $index % 3;
  1507. $index = $index +1;
  1508. $tem_series = array();
  1509. $tem_series["name"] = $currency;
  1510. $tem_series["type"] = "bar";
  1511. $tem_series["emphasis"] = array("disabled"=>true,"focus"=>"none");
  1512. $tem_series["itemStyle"] = array("color"=>$color[$num],"borderRadius"=>6);
  1513. $tem_series["label"] = array("show"=>false,"color"=>"#646A73","position"=>"top","fontFamily"=>"Lato-Light","hideWhenMouseLeave"=>false);
  1514. //准备series data
  1515. $data = array();
  1516. $total = 0;
  1517. foreach($series as $_series){
  1518. $invoice_amount = empty($_series['invoice_amount'])? 0 : round($_series['invoice_amount'], 4);
  1519. $data[]=$invoice_amount;
  1520. $total = $total + $invoice_amount;
  1521. $max = $max<$_series['invoice_amount'] ? $_series['invoice_amount'] : $max;
  1522. $series_max = $series_max<$_series['invoice_amount'] ? $_series['invoice_amount'] : $series_max;
  1523. }
  1524. //计算Y坐标的间隔 每种货币的
  1525. $interval = utils::calculateTicks(0,$series_max,5);
  1526. if($interval == 0){
  1527. //处理返回默认值
  1528. $interval = 2;
  1529. }
  1530. $tem_series["Max"] = $interval*5;
  1531. $tem_series["interval"] = $interval;
  1532. $tem_series["data"] = $data;
  1533. $tem_series["total"] = floatval(number_format($total, 4, '.', ''));
  1534. $barSeries[] = $tem_series;
  1535. }
  1536. //计算Y坐标的间隔
  1537. $interval = utils::calculateTicks(0,$max,5);
  1538. if($interval == 0){
  1539. //处理返回默认值
  1540. $interval = 2;
  1541. }
  1542. $revenueBarData = array("bar_title" =>"Total:","barList" => $barList,
  1543. "barSeries" =>$barSeries,"download_name"=>"Rvenue","isShowTooltips"=>true,"Max" =>$interval*5,"interval" =>$interval);
  1544. return $revenueBarData;
  1545. }
  1546. public static function findCurrencyByMonth($month,$ckey,$cvalueArr){
  1547. $data = array("month" =>$month,"currency"=>$ckey,"invoice_amount"=>0,"sort_month"=>"");
  1548. foreach($cvalueArr as $realmonth){
  1549. if($realmonth['month'] == $month){
  1550. $data = $realmonth;
  1551. }
  1552. }
  1553. return $data;
  1554. }
  1555. public static function getdefaultManagement(){
  1556. $Management = array();
  1557. $Management[] = array("id"=>1 ,
  1558. "title"=>"KPI",
  1559. "switchValue"=>true,
  1560. "text"=>"Pie chart showing figures of shipments KPI of Departure and Arrival.");
  1561. $Management[] = array("id"=>2 ,
  1562. "title"=>"Pending",
  1563. "switchValue"=>true,
  1564. "text"=>"Pie chart showing figures of shipments which are soon to depart/arrive (Calculated from ETD/ETA).");
  1565. $Management[] = array("id"=>3 ,
  1566. "title"=>"ETD to ETA (Days)",
  1567. "switchValue"=>true,
  1568. "text"=>"Pie chart showing figures of shipments which are soon to depart/arrive (Calculated from ETD/ETA).");
  1569. $Management[] = array("id"=>4 ,
  1570. "title"=>"Container Count",
  1571. "switchValue"=>true,
  1572. "text"=>"Pie chart showing figures of shipments which are soon to depart/arrive (Calculated from ETD/ETA).");
  1573. //if(_isRevenueDisplay()){
  1574. $Management[] = array("id"=>5 ,
  1575. "title"=>"Revenue Spent",
  1576. "switchValue"=>_isRevenueDisplay(),
  1577. "text"=>"Revenue data for the past 12 months.",
  1578. "isRevenueDisplay"=>_isRevenueDisplay());
  1579. //}
  1580. $Management[] = array("id"=>6 ,
  1581. "title"=>"Top 10 Origin/Destination",
  1582. "switchValue"=>true,
  1583. "text"=>"Figure of the top 10 origin/destination.",
  1584. "title1"=>"Top 10 Origin",
  1585. "title2"=>"Top 10 Destination");
  1586. $Management[] = array("id"=>7 ,
  1587. "title"=>"CO2e Emission by Origin (Top 10)",
  1588. "switchValue"=>true,
  1589. "text"=>"Figure of the CO2e Emission by origin.");
  1590. $Management[] = array("id"=>8 ,
  1591. "title"=>"CO2e Emission by Destination (Top 10)",
  1592. "switchValue"=>true,
  1593. "text"=>"Figure of the CO2e Emission by destination.");
  1594. $Management[] = array("id"=>9 ,
  1595. "title"=>"Recent Status",
  1596. "switchValue"=>true,
  1597. "text"=>"A shipment list with latest status update on top.");
  1598. return $Management;
  1599. }
  1600. /**
  1601. * Destroy Session
  1602. */
  1603. public static function sessionDestroy() {
  1604. session_destroy();
  1605. setcookie(session_name(), '', time() - 3600);
  1606. $_SESSION = array();
  1607. }
  1608. public static function dateFormatToYM($dateString){
  1609. $date = DateTime::createFromFormat('m/Y', $dateString);
  1610. $formattedDate = $date->format('Y-m'); // YYYY-MM
  1611. return $formattedDate;
  1612. }
  1613. public static function retStationInfo($address_1,$address_2,$address_3,$address_4,$city,$state,$country,$zipcode){
  1614. $stationInfo = "";
  1615. if(!empty($address_1)){
  1616. $stationInfo .= $address_1;
  1617. }
  1618. if(!empty($address_2)){
  1619. $stationInfo .= " ".$address_2;
  1620. }
  1621. if(!empty($address_3)){
  1622. $stationInfo .= " ".$address_3;
  1623. }
  1624. if(!empty($address_4)){
  1625. $stationInfo .= " ".$address_4;
  1626. }
  1627. $temp_str = "";
  1628. if(!empty($city)){
  1629. $temp_str .= $city." ";
  1630. }
  1631. if(!empty($state)){
  1632. $temp_str .= $state." ";
  1633. }
  1634. if(!empty($zipcode)){
  1635. $temp_str .= $zipcode." ";
  1636. }
  1637. if(!empty($country)){
  1638. $temp_str .= $country." ";
  1639. }
  1640. if(!empty($temp_str)){
  1641. return $stationInfo." ".trim($temp_str);
  1642. }
  1643. return $stationInfo;
  1644. }
  1645. public static function getInsertSqlNull($table_name, $values) {
  1646. $field = "";
  1647. $value = "";
  1648. foreach ($values as $k => $v) {
  1649. if ($k == 'tmp' || $k == 'action' || $k == 'operate' || $k == 'x' || $k == 'y') {
  1650. continue;
  1651. }
  1652. if (is_array($v)) {
  1653. $v = utils::implode(",", $v);
  1654. }
  1655. if (empty($field)) {
  1656. $field = $k;
  1657. if (utils::checkExist($v, 'now()')) {
  1658. $value = $v;
  1659. } elseif ($v == null) {
  1660. $value .= 'null';
  1661. } elseif ($v == 'TRUE' || $v == 'FALSE') {
  1662. $value .= $v;
  1663. } else {
  1664. $value = '\'' . common::check_input($v) . '\'';
  1665. }
  1666. } else {
  1667. $field .= ',' . $k;
  1668. if (utils::checkExist($v, 'now()'))
  1669. $value .= ', now()';
  1670. elseif ($v == null) {
  1671. $value .= ',null';
  1672. } else if ($v == 'TRUE' || $v == 'FALSE') {
  1673. $value .= ',' . $v;
  1674. } else {
  1675. $value .= ', \'' . common::check_input($v) . '\'';
  1676. }
  1677. }
  1678. }
  1679. return 'insert into ' . $table_name . '(' . $field . ') values (' . $value . ')';
  1680. }
  1681. //密码规则验证
  1682. public static function checkPasswordRule($login, $new_password){
  1683. $sql="select item_value from config where item='passwordCheckRules'";
  1684. $rs = common::excuteObjectSql($sql);
  1685. $str = "";
  1686. if (!empty($rs)) {
  1687. $passwordCheckRules = json_decode($rs["item_value"],true);
  1688. //校验使用次数
  1689. if (!empty($passwordCheckRules["pastPasswordCheckNum"])) {
  1690. $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"];
  1691. $passwords = common::excuteListSql($sql);
  1692. foreach ($passwords as $pwd) {
  1693. if ($pwd['password'] == $new_password) {
  1694. $str = "This password has been recently used";
  1695. }
  1696. }
  1697. }
  1698. if(empty($str)){
  1699. $str = utils::checkPassword($new_password,$passwordCheckRules,$login);
  1700. }
  1701. }else{
  1702. $str = utils::checkPassword($new_password);
  1703. }
  1704. return $str;
  1705. }
  1706. public static function getMilestonesInfo($ocean,$transport_mode,$_schemas,$EDI315TimeAndLocation=array()){
  1707. //Milestones info列名固定
  1708. $Milestones_column = array();
  1709. $Milestones_column[] = array("title" =>"Milestones","field" =>"milestones","formatter" =>"normal","type" =>"normal");
  1710. $Milestones_column[] = array("title" =>"Date Time","field" =>"date_time","formatter" =>"dateTime","type" =>"normal");
  1711. $Milestones_column[] = array("title" =>"Locations","field" =>"locations","formatter" =>"normal","type" =>"normal");
  1712. $Milestones_column[] = array("title" =>"Remarks","field" =>"remarks","formatter" =>"normal","type" =>"normal");
  1713. //EDI315 有关联查询,以那个为准。但是如果是手工录入或者不是EDI 进去的Milestone的情况,这以这个为准
  1714. $Milestones_NO_Mapping = common::getMilestones_NO_Mapping_Data($ocean);
  1715. //Milestones 数据信息待定
  1716. $Milestones_data = array();
  1717. if($transport_mode == 'sea'){
  1718. $Milestones_data_arr = common::excuteListSql("select sn.description,act_date||' '||COALESCE(act_time,'') as date_time,
  1719. remark,timezone,a.code
  1720. from public.ocean_milestone a
  1721. inner join public.customer_service_milestone_sno sn on sn.code=a.code and sn.type = 'sea'
  1722. where a.serial_no='".$ocean["serial_no"]."' and act_date is not null order by sn.sno asc");
  1723. }else{
  1724. $Milestones_data_arr = common::excuteListSql("select sn.description,act_date||' '||COALESCE(act_time,'') as date_time,
  1725. remark,timezone,a.code
  1726. from $_schemas.air_milestone a
  1727. inner join public.customer_service_milestone_sno sn on sn.code=a.code and sn.type = 'air'
  1728. where a.serial_no='".$ocean["serial_no"]."' and act_date is not null order by sn.sno asc");
  1729. }
  1730. foreach($Milestones_data_arr as $mda){
  1731. $timezone = "";
  1732. $IFFICC_locations ="";
  1733. if(!empty($EDI315TimeAndLocation[$mda['code']])){
  1734. $edi315Info = $EDI315TimeAndLocation[$mda['code']];
  1735. if(!empty($edi315Info)){
  1736. $timezone = $edi315Info['timezone'];
  1737. }
  1738. //IFFICC 比较特殊用EDI的locations
  1739. if($mda['code'] == "IFFICC"){
  1740. $IFFICC_locations = $edi315Info['location'];
  1741. }
  1742. }else{
  1743. $edi315Info = $Milestones_NO_Mapping[$mda['code']];
  1744. if(!empty($edi315Info)){
  1745. $timezone = $edi315Info['timezone'];
  1746. }
  1747. }
  1748. //locations 以配置的信息为准
  1749. $locations = "";
  1750. $edi315Info = $Milestones_NO_Mapping[$mda['code']];
  1751. if(!empty($edi315Info)){
  1752. $locations = $edi315Info['location'];
  1753. if($mda['code'] == "IFFICC" && !empty($IFFICC_locations)){
  1754. $locations = $IFFICC_locations;
  1755. }
  1756. }
  1757. $Milestones_data[] = array("milestones"=>$mda['description'],"date_time"=>$mda['date_time'],"timezone" =>$timezone,
  1758. "locations" => $locations, "remarks" =>$mda['remark']);
  1759. }
  1760. $Milestones = array("Milestones_column"=>$Milestones_column,"Milestones_data" =>$Milestones_data);
  1761. return $Milestones;
  1762. }
  1763. /**
  1764. * 查询uncode 对应的时区
  1765. */
  1766. public static function getCityPortsInfo($uncodes){
  1767. $data =array();
  1768. $sql = "select time_zone as timezonecode,uncode as ctrycitycode from public.city_timezone where lower(uncode) ". common::getInNotInSql($uncodes);
  1769. $uncode_rs = common::excuteListSql($sql);
  1770. foreach($uncode_rs as $value){
  1771. $data[$value['ctrycitycode']] = $value['timezonecode'];
  1772. }
  1773. return $data;
  1774. }
  1775. /**
  1776. * EDI315 有关联查询,以那个为准。但是如果是手工录入或者没有对应的情况,这以这个为准
  1777. */
  1778. public static function getMilestones_NO_Mapping_Data($ocean){
  1779. $Milestones_NO_Mapping = array();
  1780. //取origin $ocean['aa_city'] 不是必需,对应文件里未提location来源
  1781. $Milestones_NO_Mapping['IFFBCF'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1782. $Milestones_NO_Mapping['IFFBCR'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1783. $Milestones_NO_Mapping['IFFCPU'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1784. $Milestones_NO_Mapping['IFFSIL'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1785. $Milestones_NO_Mapping['IFFEDO'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1786. $Milestones_NO_Mapping['IFFECC'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1787. //Place of Receipt
  1788. $Milestones_NO_Mapping['IFFREC'] = array("code"=>"por/pol","timezone"=>$ocean['por_timezone'],"location"=>$ocean['por_uncity']);
  1789. $Milestones_NO_Mapping['IFFECP'] = array("code"=>"por/pol","timezone"=>$ocean['por_timezone'],"location"=>$ocean['por_uncity']);
  1790. //Port of loading
  1791. $Milestones_NO_Mapping['IFFONB'] = array("code"=>"por/pol","timezone"=>$ocean['pol_timezone'],"location"=>$ocean['pol_uncity']);
  1792. $Milestones_NO_Mapping['IFFDEP'] = array("code"=>"por/pol","timezone"=>$ocean['pol_timezone'],"location"=>$ocean['pol_uncity']);
  1793. //取destination $ocean['dd_city']不是必需
  1794. $Milestones_NO_Mapping['IFFCSN'] = array("code"=>"destination","timezone"=>$ocean['dd_timezone'],"location"=>"");
  1795. $Milestones_NO_Mapping['IFFIDO'] = array("code"=>"destination","timezone"=>$ocean['dd_timezone'],"location"=>"");
  1796. //取Port of discharge
  1797. $Milestones_NO_Mapping['IFFARR'] = array("code"=>"mpod","timezone"=>$ocean['mpod_timezone'],"location"=>$ocean['mpod_uncity']);
  1798. $Milestones_NO_Mapping['IFFUND'] = array("code"=>"mpod/pod/fd","timezone"=>$ocean['mpod_timezone'],"location"=>$ocean['mpod_uncity']);
  1799. $Milestones_NO_Mapping['IFFICC'] = array("code"=>"mpod","timezone"=>$ocean['mpod_timezone'],"location"=>$ocean['mpod_uncity']);
  1800. //Place of Delivery
  1801. $Milestones_NO_Mapping['IFFAFD'] = array("code"=>"pod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1802. $Milestones_NO_Mapping['IFFCTA'] = array("code"=>"pod/mpod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1803. $Milestones_NO_Mapping['IFFADW'] = array("code"=>"pod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1804. $Milestones_NO_Mapping['IFFDDW'] = array("code"=>"pod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1805. $Milestones_NO_Mapping['IFFPPD'] = array("code"=>"mpod/pod/fd","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1806. $Milestones_NO_Mapping['IFFECR'] = array("code"=>"mpod/pod/fd","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1807. //final_destination $ocean['fd_city']不是必需
  1808. $Milestones_NO_Mapping['IFFDEL'] = array("code"=>"fd","timezone"=>$ocean['_fd_timezone'],"location"=>"");
  1809. $Milestones_NO_Mapping['IFFHBL'] = array("code"=>"fd","timezone"=>$ocean['_fd_timezone'],"location"=>"");
  1810. return $Milestones_NO_Mapping;
  1811. }
  1812. /**
  1813. * 这个详细查询已经带模式了
  1814. */
  1815. public static function getEDI315StatusForDetail($serial_no){
  1816. $data = array();
  1817. $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
  1818. WHERE o.serial_no='$serial_no'";
  1819. $ctnr_data = common::excuteListSql($ctnr_sql);
  1820. $containerStatusData = array();
  1821. $VD = "";
  1822. $VA = "";
  1823. $VD_RELAY = "";
  1824. $VA_RELAY = "";
  1825. foreach ($ctnr_data as $cd){
  1826. //存在柜号为空的数据情况
  1827. if(empty($cd['ctnr'])){
  1828. continue;
  1829. }
  1830. //(select uncity from public.ports where uncode = s.event_code) as uncity, 按新版的逻辑这个先取消掉
  1831. $ctnr_status_sql = "select s.source_id, s.event_base as event,
  1832. to_char(to_timestamp(s.event_date, 'YYYYMMDD'), 'YYYY-MM-DD') as eventdate,
  1833. to_char(to_timestamp(s.event_time, 'HH24MI'), 'HH24:MI') as eventtime,
  1834. e.description,s.event_type as eventtype,
  1835. s.event_code as eventcode, s.event_city as eventcity,
  1836. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1837. s.event_city as uncity,
  1838. case when s.event_base ='I' or s.event_base ='TR' then 'IFFREC'::text
  1839. when s.event_base ='AE' then 'IFFONB'::text
  1840. when s.event_base ='VD' then 'IFFDEP'::text
  1841. when s.event_base ='EB' or s.event_base ='VA' then 'IFFARR'::text
  1842. when s.event_base ='UV' then 'IFFUND'::text
  1843. when s.event_base ='VA' then 'IFFAFD'::text
  1844. when s.event_base ='AV' then 'IFFCTA'::text
  1845. when s.event_base ='CT' then 'IFFICC'::text
  1846. when s.event_base ='OA' or s.event_base ='D' then 'IFFPPD'::text
  1847. when s.event_base ='RD' then 'IFFECR'::text
  1848. when s.event_base ='EE' then 'IFFECP'::text
  1849. else '' ::text
  1850. end as milestone_code
  1851. from public.ra_online_container_status_v s
  1852. left join public.ra_online_edi_event e on s.event_base = e.ra_name
  1853. where s.serial_no = '" . pg_escape_string($cd['serial_no']) . "'
  1854. and s.container_no = '" . pg_escape_string($cd['ctnr']) . "' and is_display = true
  1855. order by to_timestamp(s.event_date, 'YYYYMMDD') desc,
  1856. to_timestamp(s.event_time, 'HH24MI') desc,e.ra_order desc";
  1857. $ctnr_status = common::excuteListSql($ctnr_status_sql);
  1858. //Container_Status 新版只显示几个状态, CTNR# EE I AE VD VA
  1859. $container_status_column = array("EE","I","AE","VD","VA");
  1860. $containerStatusDataTemp = array();
  1861. $content = array();
  1862. //按顺序处理 新版只显示几个状态
  1863. //foreach($container_status_column as $status){
  1864. foreach($ctnr_status as $event){
  1865. //if(strtolower($event['event']) == strtolower($status)){
  1866. $eventdate = $event["eventdate"];
  1867. if (empty($event["source_id"]) || $event["source_id"]==0) {
  1868. $eventdate.= " " . $event["eventtime"];
  1869. }
  1870. $location_code = $event["eventcode"];
  1871. $content[] = array("code" =>$event['event'],"title" =>$event['description'],"date"=>$eventdate,"country"=>$location_code,"timezone"=>$event['timezone']);
  1872. if(strtolower($event['event']) == "vd" && !empty($eventdate)){
  1873. $VD = $eventdate;
  1874. }
  1875. if(strtolower($event['event']) == "va" && !empty($eventdate)){
  1876. $VA = $eventdate;
  1877. }
  1878. if(strtolower($event['event']) == strtolower("VD_RELAY") && !empty($eventdate)){
  1879. $VD_RELAY = $eventdate;
  1880. }
  1881. if(strtolower($event['event']) == strtolower("VA_RELAY") && !empty($eventdate)){
  1882. $VA_RELAY = $eventdate;
  1883. }
  1884. //}
  1885. }
  1886. //}
  1887. //记录所有的信息
  1888. $EDI315TimeAndLocation = array();
  1889. foreach($ctnr_status as $event){
  1890. if(!empty($EDI315TimeAndLocation['IFFARR']) && $EDI315TimeAndLocation['IFFARR']['code'] == "EB"){
  1891. //如果存在EB 的EB 的优先级最高
  1892. continue;
  1893. }
  1894. if(!empty($EDI315TimeAndLocation['IFFPPD']) && $EDI315TimeAndLocation['IFFARR']['code'] == "OA"){
  1895. //如果存在OA 的OA 的优先级最高
  1896. continue;
  1897. }
  1898. $EDI315TimeAndLocation[$event['milestone_code']] = array("code"=>$event['event'],"timezone"=>$event['timezone'],"location"=>$event['uncity']);
  1899. }
  1900. $containerStatusDataTemp['label'] = $cd['ctnr']." / ".$cd['size'];
  1901. $containerStatusDataTemp['content'] = $content;
  1902. $containerStatusData[] = $containerStatusDataTemp;
  1903. }
  1904. $data['containerStatusData'] = $containerStatusData;
  1905. $data['EDI315TimeAndLocation'] = $EDI315TimeAndLocation;
  1906. $data['VD'] = $VD;
  1907. $data['VA'] = $VA;
  1908. $data['VD_RELAY'] = $VD_RELAY;
  1909. $data['VA_RELAY'] = $VA_RELAY;
  1910. return $data;
  1911. }
  1912. public static function getEDI315Time($serial_no,$_schemas){
  1913. //Timezone From 来自于EDI315
  1914. $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
  1915. WHERE o.serial_no='$serial_no'";
  1916. $ctnr_data = common::excuteListSql($ctnr_sql);
  1917. $EDI315TimeAndLocation = array();
  1918. foreach ($ctnr_data as $cd){
  1919. //存在柜号为空的数据情况
  1920. if(empty($cd['ctnr'])){
  1921. continue;
  1922. }
  1923. $ctnr_status_sql = "select
  1924. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1925. case when s.event_base ='I' or s.event_base ='TR' then 'IFFREC'::text
  1926. when s.event_base ='AE' then 'IFFONB'::text
  1927. when s.event_base ='VD' then 'IFFDEP'::text
  1928. when s.event_base ='EB' or s.event_base ='VA' then 'IFFARR'::text
  1929. when s.event_base ='UV' then 'IFFUND'::text
  1930. when s.event_base ='VA' then 'IFFAFD'::text
  1931. when s.event_base ='AV' then 'IFFCTA'::text
  1932. when s.event_base ='CT' then 'IFFICC'::text
  1933. when s.event_base ='OA' or s.event_base ='D' then 'IFFPPD'::text
  1934. when s.event_base ='RD' then 'IFFECR'::text
  1935. when s.event_base ='EE' then 'IFFECP'::text
  1936. else '' ::text
  1937. end as milestone_code
  1938. from public.ra_online_container_status_v s
  1939. left join public.ra_online_edi_event e on s.event_base = e.ra_name
  1940. where s.serial_no = '" . pg_escape_string($cd['serial_no']) . "'
  1941. and s.container_no = '" . pg_escape_string($cd['ctnr']) . "' and is_display = true
  1942. order by to_timestamp(s.event_date, 'YYYYMMDD') asc,
  1943. to_timestamp(s.event_time, 'HH24MI') asc,e.ra_order asc";
  1944. $ctnr_status = common::excuteListSql($ctnr_status_sql);
  1945. //记录所有的信息、替换最后一个柜子
  1946. $EDI315TimeAndLocation = array();
  1947. foreach($ctnr_status as $event){
  1948. if(!empty($EDI315TimeAndLocation['IFFARR']) && $EDI315TimeAndLocation['IFFARR']['code'] == "EB"){
  1949. //如果存在EB 的EB 的优先级最高
  1950. continue;
  1951. }
  1952. if(!empty($EDI315TimeAndLocation['IFFPPD']) && $EDI315TimeAndLocation['IFFARR']['code'] == "OA"){
  1953. //如果存在OA 的OA 的优先级最高
  1954. continue;
  1955. }
  1956. $EDI315TimeAndLocation[$event['milestone_code']] = array("code"=>$event['event'],"timezone"=>$event['timezone']);
  1957. }
  1958. }
  1959. return $EDI315TimeAndLocation;
  1960. }
  1961. public static function getMilestoneTimeAndlocations($milestone_code,$transport_mode,$serial_no,$order_from){
  1962. $EDI315TimeAndLocation = array();
  1963. if($transport_mode == "sea"){
  1964. $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
  1965. WHERE o.serial_no='$serial_no'";
  1966. $ctnr_data = common::excuteListSql($ctnr_sql);
  1967. foreach ($ctnr_data as $cd){
  1968. //存在柜号为空的数据情况
  1969. if(empty($cd['ctnr'])){
  1970. continue;
  1971. }
  1972. $ctnr_status_sql = "select s.source_id, s.event_base as event,
  1973. to_char(to_timestamp(s.event_date, 'YYYYMMDD'), 'YYYY-MM-DD') as eventdate,
  1974. to_char(to_timestamp(s.event_time, 'HH24MI'), 'HH24:MI') as eventtime,
  1975. e.description,s.event_type as eventtype,
  1976. s.event_code as eventcode, s.event_city as eventcity,
  1977. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1978. (select uncity from public.ports where uncode = s.event_code) as uncity,
  1979. case when s.event_base ='I' then 'IFFREC'::text
  1980. when s.event_base ='AE' then 'IFFONB'::text
  1981. when s.event_base ='VD' then 'IFFDEP'::text
  1982. when s.event_base ='EB' or s.event_base ='VA' then 'IFFARR'::text
  1983. when s.event_base ='UV' then 'IFFUND'::text
  1984. when s.event_base ='VA' then 'IFFAFD'::text
  1985. when s.event_base ='AV' then 'IFFCTA'::text
  1986. when s.event_base ='CT' then 'IFFICC'::text
  1987. when s.event_base ='OA' or s.event_base ='D' then 'IFFPPD'::text
  1988. when s.event_base ='EE' then 'IFFECP'::text
  1989. else '' ::text
  1990. end as milestone_code
  1991. from public.ra_online_container_status_v s
  1992. left join ra_online_edi_event e on s.event_base = e.ra_name
  1993. where s.serial_no = '" . pg_escape_string($cd['serial_no']) . "'
  1994. and s.container_no = '" . pg_escape_string($cd['ctnr']) . "' and is_display = true
  1995. order by to_timestamp(s.event_date, 'YYYYMMDD') asc,
  1996. to_timestamp(s.event_time, 'HH24MI') asc,e.ra_order asc";
  1997. $ctnr_status = common::excuteListSql($ctnr_status_sql);
  1998. //记录所有的信息
  1999. $EDI315TimeAndLocation = array();
  2000. foreach($ctnr_status as $event){
  2001. if(!empty($EDI315TimeAndLocation['IFFARR']) && $EDI315TimeAndLocation['IFFARR']['code'] == "EB"){
  2002. //如果存在EB 的EB 的优先级最高
  2003. continue;
  2004. }
  2005. if(!empty($EDI315TimeAndLocation['IFFPPD']) && $EDI315TimeAndLocation['IFFARR']['code'] == "OA"){
  2006. //如果存在OA 的OA 的优先级最高
  2007. continue;
  2008. }
  2009. $EDI315TimeAndLocation[$event['milestone_code']] = array("code"=>$event['event'],"timezone"=>$event['timezone'],"location"=>$event['uncity']);
  2010. }
  2011. }
  2012. }
  2013. //当前数据的所有time city 查询
  2014. $sql = common::trackingSql($serial_no,$order_from);
  2015. $data_arr = common::excuteListSql($sql);
  2016. $data = $data_arr[0];
  2017. //EDI315 有关联查询,以那个为准。但是如果是手工录入或者不是EDI 进去的Milestone的情况,这以这个为准
  2018. $Milestones_NO_Mapping = common::getMilestones_NO_Mapping_Data($data);
  2019. $timezone = "";
  2020. $IFFICC_locations ="";
  2021. if(!empty($EDI315TimeAndLocation[$milestone_code])){
  2022. $edi315Info = $EDI315TimeAndLocation[$milestone_code];
  2023. if(!empty($edi315Info)){
  2024. $timezone = $edi315Info['timezone'];
  2025. }
  2026. //IFFICC 比较特殊用EDI的locations
  2027. if($milestone_code == "IFFICC"){
  2028. $IFFICC_locations = $edi315Info['location'];
  2029. }
  2030. }else{
  2031. $edi315Info = $Milestones_NO_Mapping[$milestone_code];
  2032. if(!empty($edi315Info)){
  2033. $timezone = $edi315Info['timezone'];
  2034. }
  2035. }
  2036. //locations 以配置的信息为准
  2037. $locations = "";
  2038. $edi315Info = $Milestones_NO_Mapping[$milestone_code];
  2039. if(!empty($edi315Info)){
  2040. $locations = $edi315Info['location'];
  2041. if($milestone_code == "IFFICC" && !empty($IFFICC_locations)){
  2042. $locations = $IFFICC_locations;
  2043. }
  2044. }
  2045. return array("timezone" =>$timezone,"locations" =>$locations);
  2046. }
  2047. public static function trackingSql($serial_no,$order_from){
  2048. $_schemas = $order_from;
  2049. if($_schemas == 'public'){
  2050. $_schemas = "ocean";
  2051. }
  2052. $sql = "with o as(
  2053. SELECT oo.*,m_bol as _m_bol, h_bol as _h_bol,
  2054. (select time_zone from public.city_timezone where uncode = oo.fport_of_loading_un limit 1) as pol_timezone,
  2055. case when oo.transport_mode ='sea'
  2056. then (select uncity from $order_from.ports where uncode = oo.fport_of_loading_un limit 1)
  2057. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.fport_of_loading_un limit 1)
  2058. end as pol_uncity,
  2059. (select time_zone from public.city_timezone where uncode = oo.mport_of_discharge_un limit 1) as mpod_timezone,
  2060. case when oo.transport_mode ='sea'
  2061. then (select uncity from $order_from.ports where uncode = oo.mport_of_discharge_un limit 1)
  2062. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.mport_of_discharge_un limit 1)
  2063. end as mpod_uncity,
  2064. (select time_zone from public.city_timezone where uncode = oo.place_of_receipt_un limit 1) as por_timezone,
  2065. case when oo.transport_mode ='sea'
  2066. then (select uncity from $order_from.ports where uncode = oo.place_of_receipt_un limit 1)
  2067. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.place_of_receipt_un limit 1)
  2068. end as por_uncity,
  2069. (select time_zone from public.city_timezone where uncode = oo.place_of_delivery_un limit 1) as pod_timezone,
  2070. case when oo.transport_mode ='sea'
  2071. then (select uncity from $order_from.ports where uncode = oo.place_of_delivery_un limit 1)
  2072. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.place_of_delivery_un limit 1)
  2073. end as pod_uncity,
  2074. (select time_zone from public.city_timezone where uncode = oo.final_desination_uncode limit 1) as _fd_timezone,
  2075. case when oo.transport_mode ='sea'
  2076. then (select uncity from $order_from.ports where uncode = oo.final_desination_uncode limit 1)
  2077. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.final_desination_uncode limit 1)
  2078. end as _pd_uncity,
  2079. CASE
  2080. 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
  2081. 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
  2082. WHEN (m_iffdep is not null and m_iffarr is null and m_iffdel is null) THEN 'Departure'::text
  2083. WHEN (m_iffarr is not null and m_iffdel is null) THEN 'Arrived'::text
  2084. WHEN (m_iffdel is not null) THEN 'Completed'::text
  2085. ELSE 'Created'::text
  2086. END AS new_status
  2087. from public.kln_ocean oo where oo.serial_no = '" . $serial_no . "' and oo.order_from = '$order_from'
  2088. )
  2089. SELECT o.* ,sh.*, cn.*,aa.*,dd.*,fd.*
  2090. from o
  2091. LEFT JOIN LATERAL ( SELECT company as cn_company,
  2092. address_1 as cn_address_1,
  2093. address_2 as cn_address_2,
  2094. address_3 as cn_address_3,
  2095. address_4 as cn_address_4,
  2096. city as cn_city, state as cn_state, zipcode as cn_zipcode, country as cn_country,
  2097. phone_1 as cn_phone
  2098. FROM $_schemas.contacts c WHERE o.consignee_id::text = c.contact_id::text) cn ON true
  2099. LEFT JOIN LATERAL ( SELECT company as sh_company,
  2100. address_1 as sh_address_1,
  2101. address_2 as sh_address_2,
  2102. address_3 as sh_address_3,
  2103. address_4 as sh_address_4,
  2104. city as sh_city, state as sh_state, zipcode as sh_zipcode, country as sh_country,
  2105. phone_1 as sh_phone
  2106. FROM $_schemas.contacts c WHERE o.shipper_id::text = c.contact_id::text) sh ON true
  2107. LEFT JOIN LATERAL ( SELECT company as aa_company,
  2108. address_1 as aa_address_1,
  2109. address_2 as aa_address_2,
  2110. address_3 as aa_address_3,
  2111. address_4 as aa_address_4,
  2112. city as aa_city, state as aa_state, zipcode as aa_zipcode, country as aa_country,
  2113. phone_1 as aa_phone,
  2114. (select time_zone from public.city_timezone where uncode = LEFT(c.country, 2) || COALESCE(c.city_code,'') limit 1) as aa_timezone
  2115. FROM $_schemas.contacts c WHERE o.origin::text = c.contact_id::text) aa ON true
  2116. LEFT JOIN LATERAL ( SELECT company as dd_company,
  2117. address_1 as dd_address_1,
  2118. address_2 as dd_address_2,
  2119. address_3 as dd_address_3,
  2120. address_4 as dd_address_4,
  2121. city as dd_city, state as dd_state, zipcode as dd_zipcode, country as dd_country,
  2122. phone_1 as dd_phone,
  2123. (select time_zone from public.city_timezone where uncode = LEFT(c.country, 2) || COALESCE(c.city_code,'') limit 1) as dd_timezone
  2124. FROM $_schemas.contacts c WHERE o.agent::text = c.contact_id::text) dd ON true
  2125. LEFT JOIN LATERAL ( SELECT
  2126. city as fd_city,
  2127. (select time_zone from public.city_timezone where uncode = LEFT(c.country, 2) || COALESCE(c.city_code,'') limit 1) as fd_timezone
  2128. FROM $_schemas.contacts c WHERE o.final_desination::text = c.contact_id::text) fd ON true";
  2129. return $sql;
  2130. }
  2131. public static function getDashboardTransportationSqlWhere(){
  2132. $transportation = $_REQUEST["transportation"];
  2133. if(!is_array($transportation)){
  2134. $transportation = array($transportation);
  2135. }
  2136. $mode_param = "";
  2137. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  2138. $mode_param = "'sea','air','road'";
  2139. }else{
  2140. $transport_mode = utils::implode(';', $transportation);
  2141. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  2142. }
  2143. return " and transport_mode in ($mode_param)";
  2144. }
  2145. /*
  2146. * Create Directory
  2147. */
  2148. public static function mkdirs($path, $mode = 0777) { //creates directory tree recursively
  2149. if (!file_exists($path)) {
  2150. if (!mkdir($path, $mode, TRUE))
  2151. return FALSE;
  2152. }
  2153. return TRUE;
  2154. }
  2155. /**
  2156. * checked is_subscribe
  2157. */
  2158. public static function checkedSubscribe($serial_no) { //creates directory tree recursively
  2159. $is_subscribe_exist = common::excuteOneSql("select user_login from public.kln_user_subscribed us
  2160. where lower(us.user_login) = '".strtolower(_getLoginName())."' and us.subscribed_serial_no = '".$serial_no."'");
  2161. if(empty($is_subscribe_exist)){
  2162. $is_subscribe = false;
  2163. }else{
  2164. $is_subscribe = true;
  2165. }
  2166. return $is_subscribe;
  2167. }
  2168. /**
  2169. * get webiste
  2170. */
  2171. public static function getWebiste($carrier) {
  2172. $website = "";
  2173. if (!empty($carrier)){
  2174. $website = common::excuteOneSql("select website from vessel_company where scac = '$carrier'");
  2175. }
  2176. if (strpos($website, ";") === FALSE){
  2177. }else{
  2178. $site = explode(";", $website);
  2179. $website = $site[0];
  2180. }
  2181. return $website;
  2182. }
  2183. public static function getWeek($week){
  2184. if ($week == "0"){
  2185. $week = "Sunday";
  2186. } elseif ($week == "1"){
  2187. $week = "Monday";
  2188. } elseif ($week == "2"){
  2189. $week = "Tuesday";
  2190. } elseif ($week == "3"){
  2191. $week = "Wednesday";
  2192. } elseif ($week == "4"){
  2193. $week = "Thursday";
  2194. } elseif ($week == "5"){
  2195. $week = "Friday";
  2196. } elseif ($week == "6"){
  2197. $week = "Sunday";
  2198. }
  2199. return $week;
  2200. }
  2201. /**
  2202. * 这里基准event 写死, 根据online查询页面的通用的来, 这里需提问确定
  2203. */
  2204. public static function getEDICtnrEvent(){
  2205. $event =array(array("event_name"=>"EE","description"=>"Empty Equipment Dispatched"),
  2206. array("event_name"=>"I","description"=>"Gate in full for a booking"),
  2207. array("event_name"=>"AE","description"=>"Container loaded on vessel"),
  2208. array("event_name"=>"VD","description"=>"Vessel Departure"),
  2209. array("event_name"=>"VA_RELAY","description"=>"Arrive Relay Port"),
  2210. array("event_name"=>"UV_RELAY","description"=>"Unloaded at Relay Port"),
  2211. array("event_name"=>"AE_RELAY","description"=>"Loaded at Relay Port"),
  2212. array("event_name"=>"VD_RELAY","description"=>"Depart Relay Port"),
  2213. array("event_name"=>"CU","description"=>"Carrier and Customs Release"),
  2214. array("event_name"=>"CT","description"=>"Customs release"),
  2215. array("event_name"=>"CR","description"=>"Carrier release"),
  2216. array("event_name"=>"VA","description"=>"Vessel Arrival"),
  2217. array("event_name"=>"UV","description"=>"Unloaded From Vessel"),
  2218. array("event_name"=>"AG","description"=>"Estimated Delivery"),
  2219. array("event_name"=>"OA","description"=>"Gate out full from final discharge port"),
  2220. array("event_name"=>"FT","description"=>"Free Time Expired"),
  2221. array("event_name"=>"AL","description"=>"Container loaded on Rail"),
  2222. array("event_name"=>"AR","description"=>"Container unloaded from Rail"),
  2223. array("event_name"=>"AV","description"=>"Shipment available for pickup or delivery"),
  2224. array("event_name"=>"D","description"=>"Gate out for delivery to customer"),
  2225. array("event_name"=>"RD","description"=>"Container returned empty"),
  2226. array("event_name"=>"C","description"=>"Vessel Estimated Time of Departure"),
  2227. array("event_name"=>"C_RELAY","description"=>"Estimated Time of Departure from Tranship Port"),
  2228. array("event_name"=>"AG_DES","description"=>"Estimated Delivery Destination"),
  2229. array("event_name"=>"IFFADW","description"=>"Shipment in CFS warehouse"),
  2230. array("event_name"=>"IFFDDW","description"=>"Shipment Out from CFS House"));
  2231. return $event;
  2232. }
  2233. /**
  2234. * 处理daily 和 week 不同周或者天的数据分组
  2235. */
  2236. public static function handleDailyWeekedData($notificationsArr){
  2237. $uniqe = array();
  2238. $ret = array();
  2239. foreach($notificationsArr as $info){
  2240. $uniqe_group_str = $info['insert_date_format'];
  2241. if(utils::in_array($uniqe_group_str,$uniqe)){
  2242. $tempArr = $ret[$uniqe_group_str];
  2243. $tempArr[] = $info;
  2244. $ret[$uniqe_group_str] = $tempArr;
  2245. } else {
  2246. $ret[$uniqe_group_str] = array($info);
  2247. $uniqe[] = $uniqe_group_str;
  2248. }
  2249. }
  2250. return $ret;
  2251. }
  2252. /**
  2253. * /unit=="Day(s)" ? "days":"hours";
  2254. */
  2255. public static function convertoVue($unit){
  2256. if(empty($unit))
  2257. return $unit;
  2258. if ($unit == "days"){
  2259. return "Day(s)";
  2260. }else{
  2261. return "Hour(s)";
  2262. }
  2263. }
  2264. /**
  2265. * vue to int
  2266. */
  2267. public static function convertoint($num){
  2268. if($num == "0"){
  2269. return intval($num);
  2270. }
  2271. return !empty($num) ? intval($num): $num;
  2272. }
  2273. //检查user name length
  2274. public static function checkUserNameLength($input) {
  2275. if(!empty($input) && strlen($input) > 50){
  2276. $data = array(
  2277. 'code' => 'no_exist',
  2278. 'login_version' => '',
  2279. 'msg' => 'The username or password you entered is incorrect'
  2280. );
  2281. common::echo_json_encode(500, $data);
  2282. exit();
  2283. }
  2284. }
  2285. public static function checkInputInval($input) {
  2286. $data = true;
  2287. // 定义危险 SQL 关键字列表
  2288. $dangerousKeywords = [
  2289. 'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'DROP', 'ALTER', 'CREATE',
  2290. 'UNION', 'EXEC', 'EXECUTE', 'TRUNCATE', 'GRANT', 'REVOKE',
  2291. 'WAITFOR', 'DELAY', 'PG_SLEEP', '--', ';'
  2292. ];
  2293. // 检查是否包含危险关键字(不区分大小写)
  2294. foreach ($dangerousKeywords as $keyword) {
  2295. if (stripos($input, $keyword) !== false) {
  2296. $data = false;
  2297. }
  2298. }
  2299. // 检查是否包含 SQL 注入常见模式
  2300. if (preg_match('/\b(OR|AND)\s+1\s*=\s*1\b/i', $input) ||
  2301. preg_match('/\bUNION\s+SELECT\b/i', $input)) {
  2302. $data = false;
  2303. }
  2304. if(!empty($input) && strlen($input) > 50){
  2305. $data = false;
  2306. }
  2307. return $data;
  2308. }
  2309. //预加载写法
  2310. public static function excuteObjectPrepareSql($sql,$param) {
  2311. if (empty($sql))
  2312. exit(json_encode("Program encountered an error."));
  2313. global $db;
  2314. $stmt = $db->Prepare($sql);
  2315. $result = $db->Execute($stmt, $param);
  2316. if ($result && $result->RecordCount() > 0) {
  2317. $row = $result->fields;
  2318. return $row;
  2319. }
  2320. return null;
  2321. }
  2322. //拼接换行
  2323. public static function splicedLlineBreaks() {
  2324. return "
  2325. ";
  2326. }
  2327. /**
  2328. * chat获取自然序列号
  2329. */
  2330. public static function getChatAiSequence(){
  2331. $sequence = common::excuteOneSql("select count(*) from kln_robot_chat_log where request_time >= CURRENT_DATE");
  2332. $sequence = empty($sequence)? "1" : $sequence + 1;
  2333. if($sequence >99999){
  2334. return $sequence;
  2335. }
  2336. $sequence = sprintf("%05d", $sequence);
  2337. return $sequence;
  2338. }
  2339. /**
  2340. * 处理chat 返回的json字符串
  2341. */
  2342. public static function getChatAimessage($message){
  2343. //格式:"```json ```"
  2344. return str_replace(["```json", "```"], "", $message);
  2345. }
  2346. public static function extractSelectFields($sql){
  2347. // 正则表达式匹配 SELECT 和 FROM 之间的内容
  2348. if (preg_match('/SELECT\s+(.*?)\s+FROM/si', $sql, $matches)) {
  2349. $selectPart = $matches[1];
  2350. // 去除注释和换行
  2351. $selectPart = preg_replace('/--.*$/m', '', $selectPart); // 去除单行注释
  2352. $selectPart = preg_replace('/\/\*.*?\*\//s', '', $selectPart); // 去除多行注释
  2353. $selectPart = str_replace(["\r", "\n"], ' ', $selectPart); // 换行替换成空格
  2354. // 分割字段
  2355. $fields = [];
  2356. foreach (explode(',', $selectPart) as $field) {
  2357. $field = trim($field);
  2358. if (empty($field)) continue;
  2359. // 匹配 AS 别名
  2360. if (preg_match('/(?:AS\s+)?(\w+)$/i', $field, $aliasMatch)) {
  2361. // 如果有别名,则使用别名
  2362. $fields[] = strtolower($aliasMatch[1]);
  2363. } else {
  2364. // 否则直接添加字段名
  2365. $fields[] = strtolower(trim($field));
  2366. }
  2367. }
  2368. return $fields;
  2369. }
  2370. return []; // 如果没有找到 SELECT 字段
  2371. }
  2372. public static function getUserCountry(){
  2373. $contact_id = $_SESSION['ONLINE_USER']['contact_id'];
  2374. if(empty($contact_id)){
  2375. return "claude";
  2376. }
  2377. $model = "deepseek";
  2378. $belong_schemas = $_SESSION['ONLINE_USER']['belong_schemas'];
  2379. if(empty($belong_schemas)){
  2380. $belong_schemas = "public";
  2381. }
  2382. if(stripos($belong_schemas, "public") !== false){
  2383. $data = common::excuteListSql("select LEFT(country, 2) as country from ocean.contacts where contact_id = '$contact_id'");
  2384. foreach($data as $country){
  2385. if($country['country'] != "CN"){
  2386. $model = "claude";
  2387. }
  2388. }
  2389. }
  2390. if(stripos($belong_schemas, "sfs") !== false){
  2391. $data = common::excuteListSql("select LEFT(country, 2) as country from sfs.contacts where contact_id = '$contact_id'");
  2392. foreach($data as $country){
  2393. if($country['country'] != "CN"){
  2394. $model = "claude";
  2395. }
  2396. }
  2397. }
  2398. return $model;
  2399. }
  2400. public static function FixedAnswerAndLogData($fixedChat,$question_content){
  2401. $reference = "";
  2402. //返回格式相同的放到一起处理
  2403. if($fixedChat["fixed_faq"] == "Shipments arriving in the next 7 days."
  2404. || $fixedChat["fixed_faq"] == "What is the current status of my active shipments?"){
  2405. $reference = $fixedChat["answer_style"];
  2406. $sql = $fixedChat["fixed_sql"];
  2407. if($_POST['is_demo'] == 't'){
  2408. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2409. }
  2410. $sqlArr = explode(";", $sql);
  2411. $sqlCount = $sqlArr[0];
  2412. //拼接用户权限
  2413. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2414. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2415. error_log("countSql:".$sqlCount);
  2416. $count = common::excuteOneSql($sqlCount);
  2417. //替换总数
  2418. $total = array("total" =>$count);
  2419. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2420. $sqlDetail = $sqlArr[1];
  2421. //拼接用户权限
  2422. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2423. error_log("detail:".$sqlDetail);
  2424. $data = common::excuteListSql($sqlDetail);
  2425. if($fixedChat["fixed_faq"] == "Shipments arriving in the next 7 days."){
  2426. foreach($data as $key =>$d){
  2427. $serial_no = common::deCode($d['serial_no'], 'E');
  2428. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2429. $data[$key]['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2430. }
  2431. }
  2432. if($fixedChat["fixed_faq"] == "What is the current status of my active shipments?"){
  2433. $refer_data =array();
  2434. foreach($data as $key =>$d){
  2435. $temp = array();
  2436. $temp['h_bol'] = $d['h_bol'];
  2437. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  2438. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  2439. $temp['description'] = $d['description'];
  2440. $temp['time'] = common::dealDateTime($d['act_date'],$d['act_time'],$d['timezone'],"m/d/Y");
  2441. $temp['locations'] = $d['locations'];
  2442. $temp['cargo_type'] = $d['cargo_type'];
  2443. $serial_no = common::deCode($d['serial_no'], 'E');
  2444. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2445. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2446. $refer_data[] = $temp;
  2447. }
  2448. $data = $refer_data;
  2449. }
  2450. $reference = utils::replacementsFixedMultilineForFixed($data,$reference,$fixedChat['table_format_tr']);
  2451. $total = array("Download_Complete" =>"");
  2452. if ($count > 10){
  2453. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2454. $download_complete = '- Due to page limitations, only the first 10 records are currently displayed. If you need the complete data, please click the <a href="'.$httpUrl.'" target="_blank">Download Complete</a> button.';
  2455. $total = array("Download_Complete" =>$download_complete);
  2456. }
  2457. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2458. }
  2459. if($fixedChat["fixed_faq"] == "Show shipments delayed in the last 30 days."){
  2460. $reference = $fixedChat["answer_style"];
  2461. $sql = $fixedChat["fixed_sql"];
  2462. if($_POST['is_demo'] == 't'){
  2463. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2464. }
  2465. $sqlArr = explode(";", $sql);
  2466. $sqlCount = $sqlArr[0];
  2467. //拼接用户权限
  2468. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2469. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2470. error_log("countSql:".$sqlCount);
  2471. $count = common::excuteOneSql($sqlCount);
  2472. //替换总数
  2473. $total = array("total" =>$count);
  2474. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2475. $sqlDetail = $sqlArr[1];
  2476. //拼接用户权限
  2477. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2478. error_log("detail:".$sqlDetail);
  2479. $data = common::excuteListSql($sqlDetail);
  2480. $refer_data =array();
  2481. foreach($data as $key =>$d){
  2482. $temp = array();
  2483. $temp['h_bol'] = $d['h_bol'];
  2484. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  2485. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  2486. $temp['log_type'] = $d['log_type'];
  2487. $temp['planned_time'] = common::dealDateTime($d['event_old_date'],$d['event_old_time'],'',"m/d/Y");
  2488. $temp['actual_time'] = common::dealDateTime($d['event_date'],$d['event_time'],'',"m/d/Y");
  2489. $temp['duration'] = $d['duration'] <= 0 ? '< 1 Days' : $d['duration'].' Days';
  2490. $serial_no = common::deCode($d['serial_no'], 'E');
  2491. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2492. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2493. $refer_data[] = $temp;
  2494. }
  2495. $reference = utils::replacementsFixedMultilineForFixed($refer_data,$reference,$fixedChat['table_format_tr']);
  2496. $total = array("Download_Complete" =>"");
  2497. if ($count > 10){
  2498. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2499. $download_complete = '- Due to page limitations, only the first 10 records are currently displayed. If you need the complete data, please click the <a href="'.$httpUrl.'" target="_blank">Download Complete</a> button.';
  2500. $total = array("Download_Complete" =>$download_complete);
  2501. }
  2502. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2503. }
  2504. if($fixedChat["fixed_faq"] == "List shipments with milestone updates in the last 7 days."){
  2505. $reference = $fixedChat["answer_style"];
  2506. $sql = $fixedChat["fixed_sql"];
  2507. if($_POST['is_demo'] == 't'){
  2508. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2509. }
  2510. $sqlArr = explode(";", $sql);
  2511. $sqlCount = $sqlArr[0];
  2512. //拼接用户权限
  2513. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2514. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2515. error_log("countSql:".$sqlCount);
  2516. $count = common::excuteOneSql($sqlCount);
  2517. //替换总数
  2518. $total = array("total" =>$count);
  2519. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2520. $sqlDetail = $sqlArr[1];
  2521. //拼接用户权限
  2522. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2523. error_log("detail:".$sqlDetail);
  2524. $data = common::excuteListSql($sqlDetail);
  2525. $refer_data =array();
  2526. foreach($data as $key =>$d){
  2527. $temp = array();
  2528. $temp['h_bol'] = $d['h_bol'];
  2529. $temp['description'] = $d['description'];
  2530. $temp['update_date'] = common::dealDateTime($d['update_date'],"",$d['timezone'],"m/d/Y H:i:s");
  2531. $temp['locations'] = $d['locations'];
  2532. $serial_no = common::deCode($d['serial_no'], 'E');
  2533. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2534. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2535. $refer_data[] = $temp;
  2536. }
  2537. $reference = utils::replacementsFixedMultilineForFixed($refer_data,$reference,$fixedChat['table_format_tr']);
  2538. //Timeline View
  2539. $sqlview = $sqlArr[2];
  2540. //拼接用户权限
  2541. $sqlview = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlview);
  2542. error_log($sqlview);
  2543. $dateGroups = common::excuteListSql($sqlview);
  2544. $timeline_view = "";
  2545. if(!empty($dateGroups)){
  2546. $timeline_view = "## Timeline View: \n";
  2547. }
  2548. foreach($dateGroups as $key => $tv_count){
  2549. $timeline_view.="- ".$tv_count['update_date_format'].": ".$tv_count['total_count']." shipments reached milestones \n";
  2550. }
  2551. $total = array("Timeline View" =>$timeline_view);
  2552. $reference = utils::replacementsFixed($total,$reference,array("Timeline View"));
  2553. $total = array("Download_Complete" =>"");
  2554. if ($count > 10){
  2555. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2556. $download_complete = '- Due to page limitations, only the first 10 records are currently displayed. If you need the complete data, please click the <a href="'.$httpUrl.'" target="_blank">Download Complete</a> button.';
  2557. $total = array("Download_Complete" =>$download_complete);
  2558. }
  2559. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2560. error_log($reference);
  2561. }
  2562. if($fixedChat["fixed_faq"] == "Show me the full history of my container."){
  2563. $reference = $fixedChat["answer_style"];
  2564. $sql = $fixedChat["fixed_sql"];
  2565. if($_POST['is_demo'] == 't'){
  2566. $question_content = 'DRYU9375994';
  2567. }
  2568. $sqlArr = explode(";", $sql);
  2569. $sqlOne = $sqlArr[0];
  2570. //拼接用户权限
  2571. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2572. $sqlOne = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlOne);
  2573. $sqlOne = str_replace('<{ctnr}>', strtolower($question_content), $sqlOne);
  2574. error_log($sqlOne);
  2575. $data = common::excuteListSql($sqlOne);
  2576. if(empty($data)){
  2577. return "No valid Container number detected. Please try clicking on other FAQ questions or input your own question. Thank you.";
  2578. }
  2579. //如果数据为空,用这个fileds配置的 把模板里值逐个替换为空
  2580. $fileds = array("ctnr","size","h_bol","carrier","vessel","voyage","grs_kgs","ams_commodity","seal_no",
  2581. "place_of_receipt_exp","place_of_delivery_exp","last_status_315_code","last_status_city","last_status_315_date");
  2582. //Container Information替换
  2583. $reference = utils::replacementsFixed($data[0],$reference,$fileds);
  2584. //Related Shipments替换,如果有的话
  2585. if (!empty($data[0]['cleaned_ctnrs'])){
  2586. $related_Shipments = "## Related Shipments \n";
  2587. $related_Shipments .= "- **Other Containers on same Bill of Lading**: ".$data[0]['cleaned_ctnrs'];
  2588. $rsdata = array("Related Shipments" =>$related_Shipments);
  2589. $reference = utils::replacementsFixed($rsdata,$reference,[]);
  2590. }else{
  2591. $rsdata = array("Related Shipments" =>"");
  2592. $reference = utils::replacementsFixed($rsdata,$reference,[]);
  2593. }
  2594. //Complete Container Status
  2595. //根据第一个sql 查出来的serial_no,和 container_no.
  2596. $complete_container_status = "";
  2597. if (!empty($data)) {
  2598. $sqltwo = $sqlArr[1];
  2599. $sqltwo = str_replace('<{serial_no}>', $data[0]['serial_no'], $sqltwo);
  2600. $sqltwo = str_replace('<{container_no}>', $data[0]['ctnr'], $sqltwo);
  2601. $csdata = common::excuteListSql($sqltwo);
  2602. foreach($csdata as $csd){
  2603. $complete_container_status .= "- **".$csd['eventdate']." ".$csd['eventtime']."** ".$csd['description']." | ".$csd['uncity']." \n";
  2604. }
  2605. }
  2606. $rsdata = array("complete_container_status" =>$complete_container_status);
  2607. $reference = utils::replacementsFixed($rsdata,$reference,[]);
  2608. }
  2609. if($fixedChat["fixed_faq"] == "Show me the full history of my shipment."){
  2610. $reference = $fixedChat["answer_style"];
  2611. $sql = $fixedChat["fixed_sql"];
  2612. if($_POST['is_demo'] == 't'){
  2613. $question_content = 'XSTSNA003195';
  2614. }
  2615. $sqlArr = explode(";", $sql);
  2616. $sqlOne = $sqlArr[0];
  2617. //拼接用户权限
  2618. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2619. $sqlOne = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlOne);
  2620. $sqlOne = str_replace('<h_bol>', strtolower($question_content), $sqlOne);
  2621. error_log($sqlOne);
  2622. $data = common::excuteListSql($sqlOne);
  2623. if(empty($data)){
  2624. return "No valid Shipment number detected. Please try clicking on other FAQ questions or input your own question. Thank you.";
  2625. }
  2626. //如果数据为空,用这个fileds配置的 把模板里值逐个替换为空
  2627. $fileds = array("h_bol","carrier_booking","po_no","service","incoterms","shipper_city","consignee_city","etd","eta",
  2628. "shipper","consignee","notify_party","origin_agent","destination_agent","carrier");
  2629. //Container Information替换
  2630. $reference = utils::replacementsFixed($data[0],$reference,$fileds);
  2631. $ref_data = array();
  2632. $serial_no = common::deCode($data[0]['serial_no'], 'E');
  2633. $httpUrl = SERVER_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$data[0]['order_from'];
  2634. $ref_data['Track Shipment'] = '<a href="'.$httpUrl.'" target="_blank">Track Shipment</a>';
  2635. $reference = utils::replacementsFixed($ref_data,$reference,$fileds);
  2636. //Complete Container Status
  2637. //根据第一个sql 查出来的serial_no,和 container_no.
  2638. $complete_container_status = "";
  2639. if (!empty($data)) {
  2640. $sqltwo = $sqlArr[1];
  2641. $sqltwo = str_replace('<{serial_no}>', $data[0]['serial_no'], $sqltwo);
  2642. $csdata = common::excuteListSql($sqltwo);
  2643. foreach($csdata as $csd){
  2644. $complete_container_status .= "- **".$csd['eventdate']." ".$csd['eventtime']."** ".$csd['description']." | ".$csd['uncity']." \n";
  2645. }
  2646. }
  2647. $rsdata = array("complete_container_status" =>$complete_container_status);
  2648. $reference = utils::replacementsFixed($rsdata,$reference,[]);
  2649. }
  2650. if($fixedChat["fixed_faq"] == "List shipments with container status updates in the last 7 days."){
  2651. $reference = $fixedChat["answer_style"];
  2652. $sql = $fixedChat["fixed_sql"];
  2653. if($_POST['is_demo'] == 't'){
  2654. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2655. }
  2656. $sqlArr = explode(";", $sql);
  2657. $sqlCount = $sqlArr[0];
  2658. //拼接用户权限
  2659. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2660. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2661. error_log("countSql:".$sqlCount);
  2662. $count = common::excuteOneSql($sqlCount);
  2663. //替换总数
  2664. $total = array("total" =>$count);
  2665. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2666. $sqlDetail = $sqlArr[1];
  2667. //拼接用户权限
  2668. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2669. error_log("detail:".$sqlDetail);
  2670. $data = common::excuteListSql($sqlDetail);
  2671. $refer_data =array();
  2672. foreach($data as $key =>$d){
  2673. $temp = array();
  2674. $temp['container_no'] = $d['container_no'];
  2675. $temp['description'] = $d['description'];
  2676. $temp['time'] = common::dealDateTime($d['eventdate'],$d['eventtime'],$d['timezone'],"m/d/Y");
  2677. $temp['uncity'] = $d['uncity'];
  2678. $serial_no = common::deCode($d['serial_no'], 'E');
  2679. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2680. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2681. $refer_data[] = $temp;
  2682. }
  2683. $reference = utils::replacementsFixedMultilineForFixed($refer_data,$reference,$fixedChat['table_format_tr']);
  2684. //Timeline View
  2685. $sqlview = $sqlArr[2];
  2686. //拼接用户权限
  2687. $sqlview = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlview);
  2688. error_log("viewSql:".$sqlview);
  2689. $dateGroups = common::excuteListSql($sqlview);
  2690. $timeline_view = "";
  2691. if(!empty($dateGroups)){
  2692. $timeline_view = "## Timeline View: \n";
  2693. }
  2694. foreach($dateGroups as $key => $tv_count){
  2695. $timeline_view.="- ".$tv_count['_insert_date'].": ".$tv_count['total_count']." containers have been updated \n";
  2696. }
  2697. $total = array("Timeline View" =>$timeline_view);
  2698. $reference = utils::replacementsFixed($total,$reference,array("Timeline View"));
  2699. $total = array("Download_Complete" =>"");
  2700. if ($count > 10){
  2701. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2702. $download_complete = '- Due to page limitations, only the first 10 records are currently displayed. If you need the complete data, please click the <a href="'.$httpUrl.'" target="_blank">Download Complete</a> button.';
  2703. $total = array("Download_Complete" =>$download_complete);
  2704. }
  2705. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2706. }
  2707. if($fixedChat["fixed_faq"] == "Today's shipments summary."){
  2708. $reference = $fixedChat["answer_style"];
  2709. $sql = $fixedChat["fixed_sql"];
  2710. if($_POST['is_demo'] == 't'){
  2711. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2712. }
  2713. $sqlArr = explode(";", $sql);
  2714. $sqlCount = $sqlArr[0];
  2715. //拼接用户权限
  2716. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2717. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2718. error_log("countSql:".$sqlCount);
  2719. $count = common::excuteOneSql($sqlCount);
  2720. //替换总数
  2721. $total = array("total" =>$count);
  2722. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2723. $sqlDetail = $sqlArr[1];
  2724. //拼接用户权限
  2725. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2726. error_log("detail:".$sqlDetail);
  2727. $data = common::excuteListSql($sqlDetail);
  2728. $refer_data =array();
  2729. foreach($data as $key =>$d){
  2730. $temp = array();
  2731. $temp['h_bol'] = $d['h_bol'];
  2732. $temp['transport_mode'] = $d['transport_mode'];
  2733. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  2734. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  2735. $temp['action_type'] = $d['action_type'];
  2736. $temp['time'] = common::dealDateTime($d['act_date'],$d['act_time'],$d['timezone'],"m/d/Y");
  2737. $temp['locations'] = $d['locations'];
  2738. $serial_no = common::deCode($d['serial_no'], 'E');
  2739. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2740. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2741. $refer_data[] = $temp;
  2742. }
  2743. $reference = utils::replacementsFixedMultilineForFixed($refer_data,$reference,$fixedChat['table_format_tr']);
  2744. //替换开头日期
  2745. $d1_day = empty($data) ? "" : $data[0]['_update_date'];
  2746. $dateData = array("date" => $d1_day);
  2747. $reference = utils::replacementsFixed($dateData,$reference,[]);
  2748. //dep arr del total
  2749. $sqlview = $sqlArr[2];
  2750. //拼接用户权限
  2751. $sqlview = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlview);
  2752. error_log("depArrDelSql:".$sqlview);
  2753. $dateGroups = common::excuteListSql($sqlview);
  2754. $total = array("dep" =>$dateGroups[0]['dep'],"arr" => $dateGroups[0]['arr'],"del" => $dateGroups[0]['del']);
  2755. $reference = utils::replacementsFixed($total,$reference,[]);
  2756. $total = array("Download_Complete" =>"");
  2757. if ($count > 10){
  2758. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2759. $download_complete = '- Due to page limitations, only the first 10 records are currently displayed. If you need the complete data, please click the <a href="'.$httpUrl.'" target="_blank">Download Complete</a> button.';
  2760. $total = array("Download_Complete" =>$download_complete);
  2761. }
  2762. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2763. }
  2764. if($fixedChat["fixed_faq"] == "Show me the current location of my shipment."){
  2765. $reference = $fixedChat["answer_style"];
  2766. $sql = $fixedChat["fixed_sql"];
  2767. if($_POST['is_demo'] == 't'){
  2768. $question_content = 'DRYU9375994';
  2769. }
  2770. $sqlArr = explode(";", $sql);
  2771. $sqlOne = $sqlArr[0];
  2772. //拼接用户权限
  2773. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2774. $sqlOne = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlOne);
  2775. $sqlOne = str_replace('<{ctnr}>', strtolower($question_content), $sqlOne);
  2776. error_log($sqlOne);
  2777. $data = common::excuteListSql($sqlOne);
  2778. if(empty($data)){
  2779. return "No valid Container/BOL number detected. Please try clicking on other FAQ questions or input your own question. Thank you.";
  2780. }
  2781. //如果数据为空,用这个fileds配置的 把模板里值逐个替换为空
  2782. $fileds = array("tracking_no","h_bol","question_content","transport_mode","place_of_receipt_exp","place_of_delivery_exp","carrier","vessel","voyage","Shipment Detail Page Link");
  2783. $ref_data = array();
  2784. if(!empty($data)){
  2785. $ref_data = $data[0];
  2786. $ref_data['question_content'] = $question_content;
  2787. $serial_no = common::deCode($data[0]['serial_no'], 'E');
  2788. $httpUrl = SERVER_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$data[0]['order_from'];
  2789. $ref_data['Shipment Detail Page Link'] = '<a href="'.$httpUrl.'" target="_blank">Shipment Detail Page Link</a>';
  2790. }
  2791. $reference = utils::replacementsFixed($ref_data,$reference,$fileds);
  2792. }
  2793. if($fixedChat["fixed_faq"] == "Sort my active shipments by earliest arrival date."){
  2794. $reference = $fixedChat["answer_style"];
  2795. $sql = $fixedChat["fixed_sql"];
  2796. if($_POST['is_demo'] == 't'){
  2797. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2798. }
  2799. $sqlArr = explode(";", $sql);
  2800. $sqlCount = $sqlArr[0];
  2801. //拼接用户权限
  2802. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2803. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2804. error_log("countSql:".$sqlCount);
  2805. $count = common::excuteOneSql($sqlCount);
  2806. $sqlDetail = $sqlArr[1];
  2807. //拼接用户权限
  2808. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2809. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2810. error_log("detail:".$sqlDetail);
  2811. $data = common::excuteListSql($sqlDetail);
  2812. $refer_data =array();
  2813. foreach($data as $key =>$d){
  2814. $temp = array();
  2815. $temp['eta'] = $d['eta'];
  2816. $temp['h_bol'] = $d['h_bol'];
  2817. $temp['transport_mode'] = $d['transport_mode'];
  2818. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  2819. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  2820. $temp['day_to_arr'] = $d['day_to_arr'];
  2821. $serial_no = common::deCode($d['serial_no'], 'E');
  2822. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2823. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2824. $refer_data[] = $temp;
  2825. }
  2826. $data = $refer_data;
  2827. $reference = utils::replacementsFixedMultilineForFixed($data,$fixedChat['answer_style'],$fixedChat['table_format_tr']);
  2828. $total = array("Download_Complete" =>"");
  2829. if ($count > 10){
  2830. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2831. $download_complete = '- Due to page limitations, only the first 10 records are currently displayed. If you need the complete data, please click the <a href="'.$httpUrl.'" target="_blank">Download Complete</a> button.';
  2832. $total = array("Download_Complete" =>$download_complete);
  2833. }
  2834. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2835. }
  2836. if($fixedChat["fixed_faq"] == "Set up automatic notifications for shipment updates."
  2837. || $fixedChat["fixed_faq"] == "How can I view the detailed shipping route of my package?" ){
  2838. $reference = $fixedChat["answer_style"];
  2839. }
  2840. error_log($reference);
  2841. return $reference;
  2842. }
  2843. public static function dealDateTime($date,$time,$zone,$format){
  2844. if(empty($date)){
  2845. return "";
  2846. }
  2847. //处理掉多余空格
  2848. if(!empty($time)){
  2849. $time_str = " ".$time;
  2850. } else {
  2851. $time_str = "";
  2852. }
  2853. if(!empty($date) && !empty($zone)){
  2854. $utc = common::getUTCOffsetFormatted($zone);
  2855. return date($format, strtotime($date)).$time_str." UTC".$utc;
  2856. }
  2857. return date($format, strtotime($date)).$time_str;
  2858. }
  2859. public static function getUTCOffsetFormatted($timezone) {
  2860. $timezone = new DateTimeZone($timezone);
  2861. $now = new DateTime('now', $timezone);
  2862. $offset = $timezone->getOffset($now);
  2863. $hours = floor($offset / 3600 * 10) / 10;
  2864. if( $hours > 0 ){
  2865. $hours = "+".$hours;
  2866. }
  2867. return $hours;
  2868. }
  2869. /**
  2870. * 获取固定问题的查询sql
  2871. */
  2872. public static function getFaqSql($faq){
  2873. $sqlObj = common::excuteObjectSql("select fixed_sql from public.kln_robot_chat_fixed where fixed_faq = '$faq'");
  2874. $fixed_sql = $sqlObj['fixed_sql'];
  2875. $sqlDetail = '';
  2876. $sqlArr = explode(";", $fixed_sql);
  2877. if(count($sqlArr) > 1){
  2878. $sqlDetail = $sqlArr[1];
  2879. $search = 'limit 10';
  2880. $sqlDetail = str_ireplace($search, '', $sqlDetail);
  2881. }
  2882. return $sqlDetail;
  2883. }
  2884. /**
  2885. * 获取固定问题列
  2886. */
  2887. public static function getFaqColumnSql($faq){
  2888. //返回格式相同的放到一起处理
  2889. if($faq == "Shipments arriving in the next 7 days."){
  2890. // | HBL/HAWB No. | Origin | Destination | Latest Milestone | ETA | Cargo Type | Actions |
  2891. // |--------------|------------------|------------------|------------------|-----------|---------------|------------------|
  2892. // | {{h_bol}} | {{place_of_receipt_exp}} | {{place_of_delivery_exp}} | {{description}} | {{eta}} | {{cargo_type}} | {{action}} |
  2893. $columns = array();
  2894. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2895. $columns[] = array("display_name" => "Origin","database_column_name"=>"place_of_receipt_exp");
  2896. $columns[] = array("display_name" => "Destination","database_column_name"=>"place_of_delivery_exp");
  2897. $columns[] = array("display_name" => "Latest Milestone","database_column_name"=>"description");
  2898. $columns[] = array("display_name" => "ETA","database_column_name"=>"eta");
  2899. $columns[] = array("display_name" => "Cargo Type","database_column_name"=>"cargo_type");
  2900. }
  2901. if($faq == "Show shipments delayed in the last 30 days."){
  2902. // | HBL/HAWB No. | Origin | Destination | Latest Milestone | ETA | Cargo Type | Actions |
  2903. // |--------------|------------------|------------------|------------------|-----------|---------------|------------------|
  2904. // | {{h_bol}} | {{place_of_receipt_exp}} | {{place_of_delivery_exp}} | {{description}} | {{eta}} | {{cargo_type}} | {{action}} |
  2905. $columns = array();
  2906. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2907. $columns[] = array("display_name" => "Origin","database_column_name"=>"place_of_receipt_exp");
  2908. $columns[] = array("display_name" => "Destination","database_column_name"=>"place_of_delivery_exp");
  2909. $columns[] = array("display_name" => "Delayed Type","database_column_name"=>"log_type");
  2910. $columns[] = array("display_name" => "Planned Date","database_column_name"=>"planned_time");
  2911. $columns[] = array("display_name" => "Actual/Revised Date","database_column_name"=>"actual_time");
  2912. $columns[] = array("display_name" => "Delay Duration","database_column_name"=>"duration");
  2913. }
  2914. if($faq == "List shipments with milestone updates in the last 7 days."){
  2915. // | HBL/HAWB No. | Latest Milestone | Time | Location | Actions |
  2916. // |--------------|----------------------------|------------------------------|---------------------------|------------------|
  2917. // | {{h_bol}} | {{description}} | {{update_date}} | {{locations}} | {{action}} |
  2918. $columns = array();
  2919. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2920. $columns[] = array("display_name" => "Latest Milestone","database_column_name"=>"description");
  2921. $columns[] = array("display_name" => "Time","database_column_name"=>"update_date");
  2922. $columns[] = array("display_name" => "Location","database_column_name"=>"locations");
  2923. }
  2924. if($faq == "What is the current status of my active shipments?"){
  2925. // | HBL/HAWB No. | Origin | Destination | Latest Milestone | Time | Location | Cargo Type | Actions |
  2926. // |--------------|------------------|------------------|----------------------------|------------------------------|---------------------------|---------------|------------------|
  2927. // | {{h_bol}} | {{place_of_receipt_exp}} | {{place_of_delivery_exp}} | {{description}} | {{time}} | {{locations}} | {{cargo_type}} | {{action}} |
  2928. $columns = array();
  2929. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2930. $columns[] = array("display_name" => "Origin","database_column_name"=>"place_of_receipt_exp");
  2931. $columns[] = array("display_name" => "Destination","database_column_name"=>"place_of_delivery_exp");
  2932. $columns[] = array("display_name" => "Latest Milestone","database_column_name"=>"description");
  2933. $columns[] = array("display_name" => "Time","database_column_name"=>"time");
  2934. $columns[] = array("display_name" => "Location","database_column_name"=>"locations");
  2935. $columns[] = array("display_name" => "Cargo Type","database_column_name"=>"cargo_type");
  2936. }
  2937. if($faq == "List shipments with container status updates in the last 7 days."){
  2938. // | Container No. | Container Status | Time | Location | Actions |
  2939. // |---------------|----------------------------|------------------------------|---------------------------|------------------|
  2940. // | {{container_no}} | {{description}} | {{time}} | {{uncity}} | {{action}} |
  2941. $columns = array();
  2942. $columns[] = array("display_name" => "Container No.","database_column_name"=>"container_no");
  2943. $columns[] = array("display_name" => "Container Status","database_column_name"=>"description");
  2944. $columns[] = array("display_name" => "Time","database_column_name"=>"time");
  2945. $columns[] = array("display_name" => "Location","database_column_name"=>"uncity");
  2946. }
  2947. if($faq == "Today's shipments summary."){
  2948. // | HBL/HAWB No. | Mode | Origin | Destination | Action Type | Action Time | Action Location | Actions |
  2949. // |--------------|------|------------------|------------------|-------------|-------------------------|-----------------|------------------|
  2950. // | {{h_bol}} | {{transport_mode}} | {{place_of_receipt_exp}} | {{place_of_delivery_exp}} | {{action_type}} | {{time}} | {{locations}} | {{action}} |
  2951. $columns = array();
  2952. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2953. $columns[] = array("display_name" => "Mode","database_column_name"=>"transport_mode");
  2954. $columns[] = array("display_name" => "Origin","database_column_name"=>"place_of_receipt_exp");
  2955. $columns[] = array("display_name" => "Destination","database_column_name"=>"place_of_delivery_exp");
  2956. $columns[] = array("display_name" => "Action Type","database_column_name"=>"action_type");
  2957. $columns[] = array("display_name" => "Action Time","database_column_name"=>"time");
  2958. $columns[] = array("display_name" => "Action Location","database_column_name"=>"locations");
  2959. }
  2960. if($faq == "Sort my active shipments by earliest arrival date."){
  2961. // | ETA | HBOL/HAWB No. | Mode | Origin | Destination | Days to Arrival | Actions |
  2962. // |--------|---------------|-------|------------------|------------------|-----------------|------------------|
  2963. // | {{eta}} | {{h_bol}} | {{transport_mode}} | {{place_of_receipt_exp}} | {{place_of_delivery_exp}} | {{day_to_arr}} | {{action}} |
  2964. $columns = array();
  2965. $columns[] = array("display_name" => "ETA","database_column_name"=>"eta");
  2966. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2967. $columns[] = array("display_name" => "Mode","database_column_name"=>"transport_mode");
  2968. $columns[] = array("display_name" => "Origin","database_column_name"=>"place_of_receipt_exp");
  2969. $columns[] = array("display_name" => "Destination","database_column_name"=>"place_of_delivery_exp");
  2970. $columns[] = array("display_name" => "Days to Arrival","database_column_name"=>"day_to_arr");
  2971. }
  2972. return $columns;
  2973. }
  2974. /**
  2975. * 处理数据问题
  2976. */
  2977. public static function dealDataWithFaq($faq,$data){
  2978. $refer_data = array();
  2979. //返回格式相同的放到一起处理
  2980. if($faq == "Shipments arriving in the next 7 days."){
  2981. $refer_data = $data;
  2982. }
  2983. if($faq == "Show shipments delayed in the last 30 days."){
  2984. foreach($data as $key =>$d){
  2985. $temp = array();
  2986. $temp['h_bol'] = $d['h_bol'];
  2987. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  2988. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  2989. $temp['log_type'] = $d['log_type'];
  2990. $temp['planned_time'] = common::dealDateTime($d['event_old_date'],$d['event_old_time'],'',"m/d/Y");
  2991. $temp['actual_time'] = common::dealDateTime($d['event_date'],$d['event_time'],'',"m/d/Y");
  2992. $temp['duration'] = $d['duration'] <= 0 ? '< 1 Days' : $d['duration'].' Days';
  2993. $refer_data[] = $temp;
  2994. }
  2995. }
  2996. if($faq == "List shipments with milestone updates in the last 7 days."){
  2997. foreach($data as $key =>$d){
  2998. $temp = array();
  2999. $temp['h_bol'] = $d['h_bol'];
  3000. $temp['description'] = $d['description'];
  3001. $temp['update_date'] = common::dealDateTime($d['update_date'],"",$d['timezone'],"m/d/Y H:i:s");
  3002. $temp['locations'] = $d['locations'];
  3003. $refer_data[] = $temp;
  3004. }
  3005. }
  3006. if($faq == "What is the current status of my active shipments?"){
  3007. foreach($data as $key => $d){
  3008. $temp = array();
  3009. $temp['h_bol'] = $d['h_bol'];
  3010. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  3011. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  3012. $temp['description'] = $d['description'];
  3013. $temp['time'] = common::dealDateTime($d['act_date'],$d['act_time'],$d['timezone'],"m/d/Y");
  3014. $temp['locations'] = $d['locations'];
  3015. $temp['cargo_type'] = $d['cargo_type'];
  3016. $refer_data[] = $temp;
  3017. }
  3018. }
  3019. if($faq == "List shipments with container status updates in the last 7 days."){
  3020. foreach($data as $key =>$d){
  3021. $temp = array();
  3022. $temp['container_no'] = $d['container_no'];
  3023. $temp['description'] = $d['description'];
  3024. $temp['time'] = common::dealDateTime($d['eventdate'],$d['eventtime'],$d['timezone'],"m/d/Y");
  3025. $temp['uncity'] = $d['uncity'];
  3026. $refer_data[] = $temp;
  3027. }
  3028. }
  3029. if($faq == "Today's shipments summary."){
  3030. foreach($data as $key =>$d){
  3031. $temp = array();
  3032. $temp['h_bol'] = $d['h_bol'];
  3033. $temp['transport_mode'] = $d['transport_mode'];
  3034. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  3035. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  3036. $temp['action_type'] = $d['action_type'];
  3037. $temp['time'] = common::dealDateTime($d['act_date'],$d['act_time'],$d['timezone'],"m/d/Y");
  3038. $temp['locations'] = $d['locations'];
  3039. $refer_data[] = $temp;
  3040. }
  3041. }
  3042. if($faq == "Sort my active shipments by earliest arrival date."){
  3043. foreach($data as $key =>$d){
  3044. $temp = array();
  3045. $temp['eta'] = $d['eta'];
  3046. $temp['h_bol'] = $d['h_bol'];
  3047. $temp['transport_mode'] = $d['transport_mode'];
  3048. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  3049. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  3050. $temp['day_to_arr'] = $d['day_to_arr'];
  3051. $refer_data[] = $temp;
  3052. }
  3053. }
  3054. return $refer_data;
  3055. }
  3056. }
  3057. ?>