common.class.php 162 KB

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