common.class.php 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995
  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. && !(stripos($action, "destination_delivery") === 0) // destination_delivery 开头的都匹配上了
  140. ) {
  141. $data = array("msg"=>"Permission Denied");
  142. common::echo_json_encode(500, $data);
  143. exit();
  144. }
  145. }
  146. }
  147. }
  148. session_write_close();
  149. }
  150. }
  151. public static function getCompanySearch() {
  152. $sc_list = _get_schemas();
  153. if (utils::count($sc_list) == 1) {
  154. return "";
  155. }
  156. if (_isCustomerLogin()) {
  157. $msg = '<input type="hidden" name="_apex_or_sfs" value=""/>';
  158. } else {
  159. $msg = '<div class="modules">Apex/SFS/Kerry :&nbsp;<select name="_apex_or_sfs" class="sl"><option value="">All</option>';
  160. if ($_SESSION['ONLINE_USER']['main_schemas'] == "public") {
  161. $msg .= '<option value="public">Apex</option>';
  162. } else {
  163. $msg .= '<option value="public">Apex</option>';
  164. }
  165. if ($_SESSION['ONLINE_USER']['main_schemas'] == "sfs") {
  166. $msg .= '<option value="sfs">SFS</option>';
  167. } else {
  168. $msg .= '<option value="sfs">SFS</option>';
  169. }
  170. if ($_SESSION['ONLINE_USER']['main_schemas'] == "kyiff") {
  171. $msg .= '<option value="kyiff">Kerry</option>';
  172. } else {
  173. $msg .= '<option value="kyiff">Kerry</option>';
  174. }
  175. $msg .= '</select></div>';
  176. }
  177. return $msg;
  178. }
  179. public static function sessionVerify() {
  180. if (!isset($_SESSION['user_agent'])) {
  181. $_SESSION['user_agent'] = MD5($_SERVER['REMOTE_ADDR']
  182. . $_SERVER['HTTP_USER_AGENT']);
  183. } elseif ($_SESSION['user_agent'] != MD5($_SERVER['REMOTE_ADDR']
  184. . $_SERVER['HTTP_USER_AGENT'])) {
  185. session_regenerate_id();
  186. }
  187. }
  188. public static function searchExtendHand_KLN($type, $user, $company_name = "station_name") {
  189. $sqlWhere = " 1=1";
  190. if($type == "booking"){
  191. $ocean_booking_sqlWhere = self::searchExtendHandNew("booking",$user, $company_name);
  192. $air_booking_sqlWhere = self::searchExtendHandNew("air_booking",$user, $company_name);
  193. $sqlWhere = "((transport_mode ='sea' and ".$ocean_booking_sqlWhere.") or (transport_mode ='air' and ".$air_booking_sqlWhere."))";
  194. }
  195. if($type == "ocean"){
  196. $ocean_booking_sqlWhere = self::searchExtendHandNew("ocean",$user, $company_name);
  197. $air_booking_sqlWhere = self::searchExtendHandNew("air",$user, $company_name);
  198. $sqlWhere = "((transport_mode ='sea' and ".$ocean_booking_sqlWhere.") or (transport_mode ='air' and ".$air_booking_sqlWhere."))";
  199. }
  200. return $sqlWhere;
  201. }
  202. public static function searchExtendHandNew($type, $user, $company_name = "station_name") {
  203. if (_isAdminHandNew($user)) {
  204. if(strtolower($type) == "air_booking" )
  205. {
  206. return "1=1";
  207. }
  208. return " (COALESCE(schem_not_display,false) = false)";
  209. }
  210. if (_isDocAdmin($user["user_login"])) {
  211. if(strtolower($type) == "air_booking" )
  212. {
  213. return "1=1";
  214. }
  215. return ' (COALESCE(schem_not_display,false) = false)';
  216. }
  217. if (strtolower($type) != "ocean" && strtolower($type) != "booking" && strtolower($type) != "air_booking"&& strtolower($type) != "air") {
  218. return " 1<>1";
  219. }
  220. if (empty($user["schemas_list"])) {
  221. $user["schemas_list"] = $_SESSION["schemas_list"];
  222. }
  223. $schemas_list = $user["schemas_list"];
  224. if ($user["is_kerry_shipment"] == "t") {
  225. $sqlWhere = " is_kerry_shipment is not null and is_kerry_shipment=true";
  226. } else if ($user["is_kerry_shipment"] == "f") {
  227. $sqlWhere = " (COALESCE(is_kerry_shipment,false) = false)";
  228. } else {
  229. $sqlWhere = " 1=1 ";
  230. }
  231. if (!empty($_POST["_apex_or_sfs"])) {
  232. $sqlWhere .= " and order_from='" . $_POST["_apex_or_sfs"] . "'";
  233. }
  234. if (utils::count($schemas_list) == 1) {
  235. $schames = $schemas_list[0]["schemas_name"];
  236. if(strtolower($type) == "air_booking" ||strtolower($type) == "air")
  237. {
  238. }
  239. else
  240. $sqlWhere .= " and order_from='$schames'";
  241. if ($schames == "sfs" && empty($user["sfs_ONLINE_USER"])) {
  242. $user = $_SESSION["sfs_ONLINE_USER"];
  243. }
  244. if (strtolower($type) == "ocean") {
  245. $sqlWhere .= self::_oceanHandNew($user, $schames);
  246. if ($company_name == "doc") {
  247. if (empty($user["view_file_format"])) {
  248. if (strtolower($user["user_type"]) == "customer") {
  249. $sqlWhere .= " and serial_no in (SELECT serial_no from $schames.ra_online_file_format where active = true and client_display = true)";
  250. } else {
  251. $sqlWhere .= " and serial_no in (SELECT serial_no from $schames.ra_online_file_format where active = true)";
  252. }
  253. } else {
  254. $sqlWhere .= " and serial_no in (SELECT regexp_split_to_table('" . $user["view_file_format"] . "',';'))";
  255. }
  256. }
  257. }
  258. if (strtolower($type) == "booking") {
  259. $sqlWhere .= self::_bookingHandNew($user, $schames);
  260. }
  261. if (strtolower($type) == "air_booking") {
  262. $sqlWhere .= self::_air($schames);
  263. }
  264. if (strtolower($type) == "air") {
  265. $sqlWhere .= self::_air($schames);
  266. }
  267. } elseif (utils::count($schemas_list) == 2) {
  268. if(strtolower($type) == "air_booking" ){
  269. }else{
  270. $sqlWhere .= " and (COALESCE(schem_not_display,false) = false)";
  271. }
  272. if (strtolower($type) == "ocean") {
  273. $sqlWhere .= " and ((order_from='public' ";
  274. $sqlWhere .= self::_oceanHandNew($user, "public");
  275. if ($company_name == "doc") {
  276. if (empty($user["view_file_format"])) {
  277. if (strtolower($user["user_type"]) == "customer") {
  278. $sqlWhere .= " and serial_no in (SELECT serial_no from public.ra_online_file_format where active = true and client_display = true)";
  279. } else {
  280. $sqlWhere .= " and serial_no in (SELECT serial_no from public.ra_online_file_format where active = true)";
  281. }
  282. } else {
  283. $sqlWhere .= " and serial_no in (SELECT regexp_split_to_table('" . $user["view_file_format"] . "',';'))";
  284. }
  285. }
  286. $sqlWhere .= ") or (order_from='sfs' ";
  287. if (empty($user["sfs_ONLINE_USER"])) {
  288. $user = $_SESSION["sfs_ONLINE_USER"];
  289. }
  290. $sqlWhere .= self::_oceanHandNew($user, "sfs");
  291. if ($company_name == "doc") {
  292. if (empty($user["view_file_format"])) {
  293. if (strtolower($user["user_type"]) == "customer") {
  294. $sqlWhere .= " and serial_no in (SELECT serial_no from sfs.ra_online_file_format where active = true and client_display = true)";
  295. } else {
  296. $sqlWhere .= " and serial_no in (SELECT serial_no from sfs.ra_online_file_format where active = true)";
  297. }
  298. } else {
  299. $sqlWhere .= " and serial_no in (SELECT regexp_split_to_table('" . $user["view_file_format"] . "',';'))";
  300. }
  301. }
  302. $sqlWhere .= ") )";
  303. }
  304. if (strtolower($type) == "booking") {
  305. $sqlWhere .= " and ((order_from='public' ";
  306. $sqlWhere .= self::_bookingHandNew($user, "public");
  307. $sqlWhere .= ") or (order_from='sfs' ";
  308. if (empty($user["sfs_ONLINE_USER"])) {
  309. $user = $_SESSION["sfs_ONLINE_USER"];
  310. }
  311. $sqlWhere .= self::_bookingHandNew($user, "sfs");
  312. $sqlWhere .= "))";
  313. }
  314. if (strtolower($type) == "air_booking") {
  315. $sqlWhere .= " and ((order_from='public' ";
  316. $sqlWhere .= self::_air("public");
  317. $sqlWhere .= ") or (order_from='sfs' ";
  318. if (empty($user["sfs_ONLINE_USER"])) {
  319. $user = $_SESSION["sfs_ONLINE_USER"];
  320. }
  321. $sqlWhere .= self::_air("sfs");
  322. $sqlWhere .= "))";
  323. }
  324. if (strtolower($type) == "air") {
  325. $sqlWhere .= " and ((order_from='public' ";
  326. $sqlWhere .= self::_air($user, "public");
  327. $sqlWhere .= ") or (order_from='sfs' ";
  328. if (empty($user["sfs_ONLINE_USER"])) {
  329. $user = $_SESSION["sfs_ONLINE_USER"];
  330. }
  331. $sqlWhere .= self::_air($user, "sfs");
  332. $sqlWhere .= ") )";
  333. }
  334. } else {
  335. $sqlWhere = " 1<>1";
  336. }
  337. return $sqlWhere;
  338. }
  339. public static function getStatusStage($status) {
  340. if ($status == "EE" || $status == "I") {
  341. return 0;
  342. }
  343. if ($status == "AE" || $status == "VD" || $status == "VA_RELAY" || $status == "UV_RELAY" || $status == "AE_RELAY" || $status == "VD_RELAY") {
  344. return 1;
  345. }
  346. if ($status == "VA" || $status == "UV" || $status == "AL" || $status == "AR" || $status == "CU" || $status == "CT" || $status == "CR" || $status == "OA") {
  347. return 2;
  348. }
  349. if ($status == "AV" || $status == "D" || $status == "RD") {
  350. return 3;
  351. }
  352. return -1;
  353. }
  354. public static function getInNotInSql($contact_id, $type = 'in') {
  355. if (empty($contact_id))
  356. return " =''";
  357. $contact_id = trim($contact_id);
  358. $contact_id = trim($contact_id, ";");
  359. $contact_id = trim($contact_id);
  360. $contact_id = strtolower($contact_id);
  361. if ($type == 'in') {
  362. if (utils::checkExist($contact_id, ";")) {
  363. $ss = "";
  364. $aa = explode(";", $contact_id);
  365. foreach ($aa as $k => $v) {
  366. $v = trim($v);
  367. if (empty($ss))
  368. $ss = "'" . common::check_input($v) . "'";
  369. else
  370. $ss .= ",'" . common::check_input($v) . "'";
  371. }
  372. return " in (" . $ss . ")";
  373. } else {
  374. return " = '" . common::check_input($contact_id) . "'";
  375. }
  376. } else {
  377. if (utils::checkExist($contact_id, ";")) {
  378. $ss = "";
  379. $aa = explode(";", $contact_id);
  380. foreach ($aa as $k => $v) {
  381. $v = trim($v);
  382. if (empty($ss))
  383. $ss = "'" . common::check_input($v) . "'";
  384. else
  385. $ss .= ",'" . common::check_input($v) . "'";
  386. }
  387. return " in (" . $ss . ")";
  388. } else {
  389. return " != '" . common::check_input($contact_id) . "'";
  390. }
  391. }
  392. }
  393. public static function getInNotInSqlForSearch($contact_id, $type = 'in') {
  394. if (empty($contact_id))
  395. return " =''";
  396. $contact_id = trim($contact_id);
  397. $contact_id = trim($contact_id, ";");
  398. $contact_id = trim($contact_id);
  399. $contact_id = strtolower($contact_id);
  400. if ($type == 'in') {
  401. if (utils::checkExist($contact_id, ";")) {
  402. $ss = "";
  403. $aa = explode(";", $contact_id);
  404. foreach ($aa as $k => $v) {
  405. $v = trim($v);
  406. if (empty($ss))
  407. $ss = "'" . common::check_input($v) . "'";
  408. else
  409. $ss .= ",'" . common::check_input($v) . "'";
  410. }
  411. return $ss;
  412. } else {
  413. return "'" . common::check_input($contact_id) . "'";
  414. }
  415. }
  416. }
  417. /*
  418. * Encrypt a SQL query statement used to be passed as a parameter to get excel output
  419. encode :DeCode('str','E');
  420. decode :DeCode('enstr','D');
  421. */
  422. public static function deCode($string, $operation = "E") {
  423. $key = md5("uls_webwms");
  424. $key_length = strlen($key);
  425. if ($operation == "D")
  426. $string = rawurldecode($string);
  427. $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
  428. $string_length = strlen($string);
  429. $rndkey = $box = array();
  430. $result = '';
  431. for ($i = 0; $i <= 255; $i++) {
  432. $rndkey [$i] = ord($key [$i % $key_length]);
  433. $box [$i] = $i;
  434. }
  435. for ($j = $i = 0; $i < 256; $i++) {
  436. $j = ($j + $box [$i] + $rndkey [$i]) % 256;
  437. $tmp = $box [$i];
  438. $box [$i] = $box [$j];
  439. $box [$j] = $tmp;
  440. }
  441. for ($a = $j = $i = 0; $i < $string_length; $i++) {
  442. $a = ($a + 1) % 256;
  443. $j = ($j + $box [$a]) % 256;
  444. $tmp = $box [$a];
  445. $box [$a] = $box [$j];
  446. $box [$j] = $tmp;
  447. $result .= chr(ord($string [$i]) ^ ($box [($box [$a] + $box [$j]) % 256]));
  448. }
  449. if ($operation == 'D') {
  450. if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
  451. return substr($result, 8);
  452. } else {
  453. return '';
  454. }
  455. } else {
  456. return rawurlencode(str_replace('=', '', base64_encode($result)));
  457. }
  458. }
  459. public static function getStatusDesc($code) {
  460. if (strtoupper($code) == "EE") {
  461. return "Empty Equipment Dispatched";
  462. }
  463. if (strtoupper($code) == "I") {
  464. return "Gate in full for a booking";
  465. }
  466. if (strtoupper($code) == "AE") {
  467. return "Container loaded on vessel";
  468. }
  469. if (strtoupper($code) == "VD") {
  470. return "Vessel Departure";
  471. }
  472. if (strtoupper($code) == "VA_RELAY") {
  473. return "Arrive Relay Port";
  474. }
  475. if (strtoupper($code) == "VD_RELAY") {
  476. return "Depart Relay Port";
  477. }
  478. if (strtoupper($code) == "AE_RELAY") {
  479. return "Loaded at Relay Port";
  480. }
  481. if (strtoupper($code) == "UV_RELAY") {
  482. return "Unloaded at Relay Port";
  483. }
  484. if (strtoupper($code) == "VA") {
  485. return "Vessel Arrival";
  486. }
  487. if (strtoupper($code) == "UV") {
  488. return "Unloaded From Vessel";
  489. }
  490. if (strtoupper($code) == "AL") {
  491. return "Container loaded on Rail";
  492. }
  493. if (strtoupper($code) == "AR") {
  494. return "Container unloaded from Rail";
  495. }
  496. if (strtoupper($code) == "CU") {
  497. return "Carrier and Customs Release";
  498. }
  499. if (strtoupper($code) == "CT") {
  500. return "Customs release";
  501. }
  502. if (strtoupper($code) == "CR") {
  503. return "Carrier release";
  504. }
  505. if (strtoupper($code) == "OA") {
  506. return "Gate out full from final discharge port";
  507. }
  508. if (strtoupper($code) == "AV") {
  509. return "Shipment available for pickup or delivery";
  510. }
  511. if (strtoupper($code) == "RD") {
  512. return "Container returned empty";
  513. }
  514. if (strtoupper($code) == "D") {
  515. return "Gate out for delivery to customer";
  516. }
  517. }
  518. public static function _toString($msg) {
  519. if ($msg == "" || $msg == NULL) {
  520. return "";
  521. }
  522. return $msg . "";
  523. }
  524. /*
  525. * timeout output
  526. */
  527. public static function timeoutPrintInfor($httpAccept, $ajax, $login) {
  528. //记录系统因session过期 退出登录
  529. $data = array("msg"=>"session_time_out");
  530. self::echo_json_encode(403,$data);
  531. exit();
  532. }
  533. /**
  534. * _bookingHandNew 和 _oceanHandNew逻辑完全一样,只是ocean 多一个dest_op字段,在booking里没有的
  535. */
  536. private static function _oceanHandNew($user, $schemas = "public") {
  537. $o = $user['ocean_station'];
  538. $o_or = $user['ocean_station_or'];
  539. $d = $user['ocean_agent'];
  540. $d_or = $user['ocean_agent_or'];
  541. $sales = $user['ocean_sales'];
  542. $sales_or = $user['ocean_sales_or'];
  543. $op = $user['ocean_dest_op'];
  544. $op_or = $user['ocean_dest_op_or'];
  545. $follow = $user['ocean_following_sales'];
  546. $follow_or = $user['ocean_following_sales_or'];
  547. if (strtolower($o_or) == "all" || strtolower($d_or) == "all" || strtolower($sales_or) == "all" || strtolower($op_or) == "all") {
  548. return " and 1=1";
  549. }
  550. $sqlWhere = "";
  551. if (_isCustomerLoginHandNew($user)) {
  552. $sqlWhere .= " and " . _customerFilerSearchHandNew($user, $schemas);
  553. } else {
  554. if (empty($o) && empty($d) && empty($sales) && empty($op) && empty($follow)) {
  555. return " and 1<>1";
  556. }
  557. if ((strtolower($o) == 'all' || empty($o)) && (strtolower($d) == "all" || empty($d))) {
  558. } else {
  559. $sql = "1=1";
  560. if (!empty($o) && strtolower($o) != 'all') {
  561. $sql .= " and lower(origin)";
  562. $sql .= utils::getInSql($o);
  563. }
  564. if (!empty($d) && strtolower($d) != 'all') {
  565. $sql .= " and lower(agent)";
  566. $sql .= utils::getInSql($d);
  567. }
  568. $sqlWhere .= " and (" . $sql . ")";
  569. }
  570. if (strtolower($sales) == 'all' || empty($sales)) {
  571. } else {
  572. if (utils::checkExist($sales, ";")) {
  573. $sql = "1!=1";
  574. $tt = explode(";", $sales);
  575. foreach ($tt as $t) {
  576. $t = trim($t);
  577. if (!empty($t))
  578. $sql .= " or lower(sales_rep)='" . strtolower($t) . "'";
  579. }
  580. $sqlWhere .= " and ($sql)";
  581. } else
  582. $sqlWhere .= " and lower(sales_rep)='" . strtolower($sales) . "'";
  583. }
  584. if (strtolower($op) == 'all' || empty($op)) {
  585. } else {
  586. $sqlWhere .= " and lower(dest_op) " . utils::getInSql($op);
  587. }
  588. if (strtolower($follow) == 'all' || empty($follow)) {
  589. } else {
  590. if (utils::checkExist($follow, ";")) {
  591. $sql = "1!=1";
  592. $tt = explode(";", $follow);
  593. foreach ($tt as $t) {
  594. $t = trim($t);
  595. if (!empty($t))
  596. $sql .= " or following_sales ilike '" . $t . "'";
  597. }
  598. $sqlWhere .= " and ($sql)";
  599. } else
  600. $sqlWhere .= " and following_sales ilike '" . $follow . "'";
  601. }
  602. $sqlWhere = " (1=1 $sqlWhere)";
  603. if (!empty($o_or)) {
  604. $sqlWhere .= " or lower(origin)";
  605. $sqlWhere .= utils::getInSql($o_or);
  606. }
  607. if (!empty($d_or)) {
  608. $sqlWhere .= " or lower(agent)";
  609. $sqlWhere .= utils::getInSql($d_or);
  610. }
  611. if (!empty($sales_or)) {
  612. if (utils::checkExist($sales_or, ";")) {
  613. $sql = "1!=1";
  614. $tt = explode(";", $sales_or);
  615. foreach ($tt as $t) {
  616. $t = trim($t);
  617. if (!empty($t))
  618. $sql .= " or lower(sales_rep)='" . strtolower($t) . "'";
  619. }
  620. $sqlWhere .= " or ($sql)";
  621. } else
  622. $sqlWhere .= " or lower(sales_rep)='" . strtolower($sales_or) . "'";
  623. }
  624. if (!empty($op_or)) {
  625. $sqlWhere .= " or lower(dest_op) " . utils::getInSql($op_or);
  626. }
  627. if (!empty($follow_or)) {
  628. if (utils::checkExist($follow_or, ";")) {
  629. $sql = "1!=1";
  630. $tt = explode(";", $follow_or);
  631. foreach ($tt as $t) {
  632. $t = trim($t);
  633. if (!empty($t))
  634. $sql .= " or following_sales ilike '" . $t . "'";
  635. }
  636. $sqlWhere .= " or ($sql)";
  637. }else {
  638. $sqlWhere .= " or following_sales ilike '" . $follow_or . "'";
  639. }
  640. }
  641. $sqlWhere = " and ($sqlWhere)";
  642. }
  643. return $sqlWhere;
  644. }
  645. /**
  646. * _bookingHandNew 和 _oceanHandNew逻辑完全一样,只是ocean 多一个dest_op字段,在booking里没有的
  647. */
  648. private static function _bookingHandNew($user, $schames) {
  649. $o = $user['ocean_station'];
  650. $o_or = $user['ocean_station_or'];
  651. $d = $user['ocean_agent'];
  652. $d_or = $user['ocean_agent_or'];
  653. $sales = $user['ocean_sales'];
  654. $sales_or = $user['ocean_sales_or'];
  655. $op = $user['ocean_dest_op'];
  656. $op_or = $user['ocean_dest_op_or'];
  657. $follow = $user['ocean_following_sales'];
  658. $follow_or = $user['ocean_following_sales_or'];
  659. if (strtolower($o_or) == "all" || strtolower($d_or) == "all" || strtolower($sales_or) == "all") {
  660. return " and 1=1";
  661. }
  662. $sqlWhere = "";
  663. if (_isCustomerLoginHandNew($user)) {
  664. $sqlWhere .= " and " . _customerFilerSearchHandNew($user, $schames);
  665. } else {
  666. if (empty($o) && empty($d) && empty($sales) && empty($op) && empty($follow)) {
  667. return " and 1<>1";
  668. }
  669. if ((strtolower($o) == 'all' || empty($o)) && (strtolower($d) == "all" || empty($d))) {
  670. } else {
  671. $sql = "1=1";
  672. if (!empty($o) && strtolower($o) != 'all') {
  673. $sql .= " and lower(origin)";
  674. $sql .= utils::getInSql($o);
  675. }
  676. if (!empty($d) && strtolower($d) != 'all') {
  677. $sql .= " and lower(agent)";
  678. $sql .= utils::getInSql($d);
  679. }
  680. $sqlWhere .= " and (" . $sql . ")";
  681. }
  682. if (strtolower($sales) == 'all' || empty($sales)) {
  683. } else {
  684. if (utils::checkExist($sales, ";")) {
  685. $sql = "1!=1";
  686. $tt = explode(";", $sales);
  687. foreach ($tt as $t) {
  688. $t = trim($t);
  689. if (!empty($t))
  690. $sql .= " or lower(sales_rep)='" . strtolower($t) . "'";
  691. }
  692. $sqlWhere .= " and ($sql)";
  693. } else
  694. $sqlWhere .= " and lower(sales_rep)='" . strtolower($sales) . "'";
  695. }
  696. if (strtolower($follow) == 'all' || empty($follow)) {
  697. } else {
  698. if (utils::checkExist($follow, ";")) {
  699. $sql = "1!=1";
  700. $tt = explode(";", $follow);
  701. foreach ($tt as $t) {
  702. $t = trim($t);
  703. if (!empty($t))
  704. $sql .= " or following_sales ilike '" . $t . "%'";
  705. }
  706. $sqlWhere .= " and ($sql)";
  707. } else
  708. $sqlWhere .= " and following_sales ilike '" . $follow . "%'";
  709. }
  710. $sqlWhere = " (1=1 $sqlWhere)";
  711. if (!empty($o_or)) {
  712. $sqlWhere .= " or lower(origin)";
  713. $sqlWhere .= utils::getInSql($o_or);
  714. }
  715. if (!empty($d_or)) {
  716. $sqlWhere .= " or lower(agent)";
  717. $sqlWhere .= utils::getInSql($d_or);
  718. }
  719. if (!empty($sales_or)) {
  720. if (utils::checkExist($sales_or, ";")) {
  721. $sql = "1!=1";
  722. $tt = explode(";", $sales_or);
  723. foreach ($tt as $t) {
  724. $t = trim($t);
  725. if (!empty($t))
  726. $sql .= " or lower(sales_rep)='" . strtolower($t) . "'";
  727. }
  728. $sqlWhere .= " or ($sql)";
  729. } else
  730. $sqlWhere .= " or lower(sales_rep)='" . strtolower($sales_or) . "%'";
  731. }
  732. if (!empty($follow_or)) {
  733. if (utils::checkExist($follow_or, ";")) {
  734. $sql = "1!=1";
  735. $tt = explode(";", $follow_or);
  736. foreach ($tt as $t) {
  737. $t = trim($t);
  738. if (!empty($t))
  739. $sql .= " or following_sales ilike '" . $t . "%'";
  740. }
  741. $sqlWhere .= " or ($sql)";
  742. } else
  743. $sqlWhere .= " or following_sales ilike '" . $follow_or . "%'";
  744. }
  745. $sqlWhere = " and ($sqlWhere)";
  746. }
  747. return $sqlWhere;
  748. }
  749. /**
  750. * online air
  751. */
  752. private static function _air($schemas = "public") {
  753. $station = _getAirStation($schemas);
  754. $station_or = _getAirStationOr($schemas);
  755. $sales = _getAirSales($schemas);
  756. $sales_or = _getAirSalesOr($schemas);
  757. $sqlWhere = " 1=1 ";
  758. if (_isCustomerLogin()) {
  759. $sqlWhere .= " and " . _customerAirFilerSearch($schemas);
  760. } else {
  761. if (empty($station) && empty($sales)) {
  762. return "and 1<>1";
  763. }
  764. if (strtolower($station_or) == "all" || strtolower($sales_or) == "all")
  765. return " and ($sqlWhere)";
  766. if (strtolower($station) == 'all' || empty($station)) {
  767. } else {
  768. $sqlWhere .= " and (lower(origin)";
  769. $sqlWhere .= utils::getInSql($station);
  770. $sqlWhere .= " or lower(agent)";
  771. $sqlWhere .= utils::getInSql($station);
  772. $sqlWhere .= ")";
  773. }
  774. if (strtolower($sales) == 'all' || empty($sales)) {
  775. } else {
  776. $sqlWhere .= " and (lower(sales_rep) " . utils::getInSql($sales) . " or lower(following_sales) " . utils::getInSql($sales) . ")";
  777. }
  778. $sqlWhere = " ($sqlWhere)";
  779. if (!empty($station_or))
  780. $sqlWhere = "$sqlWhere or lower(origin)" . utils::getInSql($station_or) . " or lower(agent)" . utils::getInSql($station_or);
  781. if (!empty($sales_or))
  782. $sqlWhere = "$sqlWhere or lower(sales_rep)" . utils::getInSql($sales_or) . " or lower(following_sales)" . utils::getInSql($sales_or);
  783. }
  784. return " and ($sqlWhere)";
  785. }
  786. public static function isNewVersion() {
  787. if (utils::checkExist($_SERVER['PHP_SELF'], "main_new_version.php")) {
  788. return "_new";
  789. }
  790. return "";
  791. }
  792. public static function removeTopOceanOldVersionSpecialField($rss){
  793. $rss_bk = $rss;
  794. $new_arr = array();
  795. foreach ($rss_bk as $k => $v) {
  796. if (utils::startWith($v['database_column_name'], "__") || utils::startWith($v['database_column_name'], "___")){
  797. //unset($rss[$k]);
  798. }else{
  799. $new_arr[] = $v;
  800. }
  801. }
  802. return $new_arr;
  803. }
  804. public static function echo_json_encode($code,$data){
  805. $resData = array();
  806. $resData["code"] = $code;
  807. $resData["data"] =$data;
  808. //echo utils::jsonFiltration("null", "\"\"", json_encode($resData));
  809. echo json_encode($resData);
  810. }
  811. /*
  812. * MM/DD/YYYY To YYYY-MM-DD
  813. */
  814. public static function usDate2sqlDate($timestr) {
  815. if (empty($timestr))
  816. return '';
  817. $datearray = explode("/", $timestr);
  818. $m = $datearray [0];
  819. $d = $datearray [1];
  820. $y = $datearray [2];
  821. return $y . "-" . $m . "-" . $d;
  822. }
  823. public static function uuid() {
  824. return md5(uniqid("", TRUE) . mt_rand());
  825. }
  826. /*
  827. * YYYYMMDD To MM/DD/YYYY
  828. */
  829. public static function date2usdate($datestr) {
  830. if (empty($datestr))
  831. return '';
  832. $y = substr($datestr, 0, 4);
  833. $m = substr($datestr, 4, 2);
  834. $d = substr($datestr, 6, 2);
  835. return $m . "/" . $d . "/" . $y;
  836. }
  837. /*
  838. * date add some days
  839. */
  840. public static function addDays($date, $days) {
  841. $time = strtotime($date) + $days * 24 * 3600;
  842. return date('m/d/Y', $time);
  843. }
  844. /*
  845. * download file from file system
  846. */
  847. public static function download_file($filename, $display_name = null, $delete = FALSE, $files = NULL) {
  848. $filename = str_replace("/", DIRECTORY_SEPARATOR, $filename);
  849. $filename = str_replace("\\", DIRECTORY_SEPARATOR, $filename);
  850. if (!file_exists($filename))
  851. exit('File Not Exist');
  852. if (empty($display_name))
  853. $display_name = basename($filename);
  854. //$file = fopen($filename, "r");
  855. header_remove("Content-type");
  856. header("Content-type:" . self::getContentType($filename));
  857. header("Expires: 0");
  858. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  859. header("Pragma: can-cache");
  860. header("Accept-ranges:bytes");
  861. header("Accept-length:" . filesize($filename));
  862. header("Content-Disposition:attachment;filename=\"" . $display_name . "\"");
  863. //echo fread($file, filesize($filename));
  864. //fclose($file);
  865. //针对大文件,规定每次读取文件的字节数为4096字节,直接输出数据
  866. $read_buffer = 4096;
  867. $handle = fopen($filename, 'rb');
  868. //总的缓冲的字节数
  869. $sum_buffer = 0;
  870. $filesize = filesize($filename);
  871. //只要没到文件尾,就一直读取
  872. while (!feof($handle) && $sum_buffer < $filesize) {
  873. echo fread($handle, $read_buffer);
  874. $sum_buffer += $read_buffer;
  875. }
  876. //关闭句柄
  877. fclose($handle);
  878. if ($delete !== FALSE) {
  879. unlink($filename);
  880. }
  881. if (!empty($files)) {
  882. foreach ($files as $f) {
  883. unlink($f);
  884. }
  885. }
  886. }
  887. public static function getContentType($filename) {
  888. $extend = self::getExtendFilename($filename);
  889. $filetype = array(
  890. 'xls' => 'application/vnd.ms-excel',
  891. 'doc' => 'application/msword',
  892. 'gif' => 'image/gif',
  893. 'jpg' => 'image/jpeg',
  894. 'jpeg' => 'image/jpeg',
  895. 'jpe' => 'image/jpeg',
  896. 'bmp' => 'image/bmp',
  897. 'png' => 'image/png',
  898. 'tif' => 'image/tiff',
  899. 'pdf' => 'application/pdf',
  900. 'zip' => 'application/zip'
  901. );
  902. return $filetype[$extend];
  903. }
  904. /*
  905. * Get the file extension
  906. */
  907. public static function getExtendFilename($file_name) {
  908. $extend = pathinfo($file_name);
  909. $extend = strtolower($extend["extension"]);
  910. return $extend;
  911. }
  912. public static function getManagement(){
  913. //Management 自己配置需要创建表保存
  914. $user_management_data = common::excuteObjectSql("select management,dashboard_filter from ra_online_user where user_login = '"._getLoginName()."'");
  915. //为空,配置使用默认值
  916. $user_management = $user_management_data['management'];
  917. if(empty($user_management)){
  918. $Management = common::getdefaultManagement();
  919. }else{
  920. $Management = json_decode($user_management,true);
  921. foreach($Management as $key =>$val){
  922. $Management[$key]['id'] = ($key +1);
  923. $Management[$key]['switchValue'] = $val['switchValue'] == "true" ? true : false;
  924. if ($val['title'] == "Revenue Spent"){
  925. $Management[$key]['isRevenueDisplay'] = _isRevenueDisplay();
  926. if(!_isRevenueDisplay()){
  927. $Management[$key]['switchValue'] = false;
  928. }
  929. }
  930. }
  931. }
  932. $user_dashboard_filter = $user_management_data['dashboard_filter'];
  933. $dashboard_filter =array();
  934. if(!empty($user_dashboard_filter)){
  935. $dashboard_filter = json_decode($user_dashboard_filter,true);
  936. }else{
  937. $threeMonthsAgoTimestamp = strtotime('-3 months');
  938. $date_start = date('Y-m-d', $threeMonthsAgoTimestamp);
  939. $date_end = date('Y-m-d');
  940. $date_start_two = date('m/d/Y', $threeMonthsAgoTimestamp);
  941. $date_end_two = date('m/d/Y');
  942. //ETD
  943. $_12MonthsAgoTimestamp = strtotime('-11 months');
  944. $etd_date_start = date('Y-m', $_12MonthsAgoTimestamp);
  945. $etd_date_end = date('Y-m');
  946. $etd_date_start_two = date('m/Y', $_12MonthsAgoTimestamp);
  947. $etd_date_end_two = date('m/Y');
  948. //柜子
  949. $ctnr_date_start = date('Y-m', $_12MonthsAgoTimestamp);
  950. $ctnr_date_end = date('Y-m');
  951. $ctnr_date_start_two = date('m/Y', $_12MonthsAgoTimestamp);
  952. $ctnr_date_end_two = date('m/Y');
  953. //Top
  954. $top_date_start = date('Y-m-d', $_12MonthsAgoTimestamp);
  955. $top_date_end = date('Y-m-d');
  956. $top_date_start_two = date('m/d/Y', $_12MonthsAgoTimestamp);
  957. $top_date_end_two = date('m/d/Y');
  958. //KPIDefaulteData
  959. $dashboard_filter['KPIDefaulteData'] = array("transportation" =>array('All'),"date_type"=>"ETD","date_start"=>$date_start_two,"date_start_two"=>$date_start,
  960. "date_end"=>$date_end_two,"date_end_two"=>$date_end);
  961. //PendingDefaultData
  962. $dashboard_filter['PendingDefaultData'] = array("transportation" =>array('All'),"date_type"=>"ETD","date_start"=>"","date_start_two"=>"",
  963. "date_end"=>"","date_end_two"=>"");
  964. //RecentDefaultData
  965. $dashboard_filter['RecentDefaultData'] = array("transportation" =>array('All'),"date_type"=>"ETD","date_start"=>$date_start_two,"date_start_two"=>$date_start,
  966. "date_end"=>$date_end_two,"date_end_two"=>$date_end);
  967. //ETDDefaultData
  968. $dashboard_filter['ETDDefaultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$etd_date_start_two,"date_start_two"=>$etd_date_start,
  969. "date_end"=>$etd_date_end_two,"date_end_two"=>$etd_date_end);
  970. //ContainerefaultData
  971. $dashboard_filter['ContainerefaultData'] = array("transportation" =>array('Sea'),"date_type"=>"ETA","date_start"=>$ctnr_date_start_two,"date_start_two"=>$ctnr_date_start,
  972. "date_end"=>$ctnr_date_end_two,"date_end_two"=>$ctnr_date_end);
  973. //RevenueDefaultData
  974. if(_isRevenueDisplay()){
  975. $dashboard_filter['RevenueDefaultData'] = array("transportation" =>array('All'),"date_type"=>"Invoice Issue Date","date_start"=>$ctnr_date_start_two,"date_start_two"=>$ctnr_date_start,
  976. "date_end"=>$ctnr_date_end_two,"date_end_two"=>$ctnr_date_end);
  977. }
  978. //Top10faultData
  979. $dashboard_filter['Top10faultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$top_date_start_two,"date_start_two"=>$top_date_start,
  980. "date_end"=>$top_date_end_two,"date_end_two"=>$top_date_end);
  981. //OriginCo2Top10faultData
  982. $dashboard_filter['OriginCo2Top10faultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$top_date_start_two,"date_start_two"=>$top_date_start,
  983. "date_end"=>$top_date_end_two,"date_end_two"=>$top_date_end);
  984. //DestinationCo2Top10faultData
  985. $dashboard_filter['DestinationCo2Top10faultData'] = array("transportation" =>array('All'),"date_type"=>"ETA","date_start"=>$top_date_start_two,"date_start_two"=>$top_date_start,
  986. "date_end"=>$top_date_end_two,"date_end_two"=>$top_date_end);
  987. }
  988. return array("Management" => $Management,"dashboard_filter" =>$dashboard_filter);
  989. }
  990. public static function getItemStyle($type,$code){
  991. if($type == 'r1'){
  992. $data = array("0-20 Days" =>"#ffc594",
  993. "20-40 Days" =>"#ff9e4c",
  994. "40-60 Days" =>"#ff7500",
  995. "60-80 Days" =>"#ff3d00",
  996. "Over 80 Days" =>"#d50000");
  997. return $data[$code];
  998. }
  999. if($type == 'r4' || $type == 'r3' || $type == 'atd_r4' || $type == 'ata_r3'){
  1000. $data = array("0 Day" =>"#ffc594",
  1001. "Today" =>"#ffc594",
  1002. "1-2 Days" =>"#ff9e4c",
  1003. "3-6 Days" =>"#ff7500",
  1004. "7 Days" =>"#ff3d00");
  1005. return $data[$code];
  1006. }
  1007. if($type == 'r2' || utils::startWith($type,"co2e")){
  1008. $data = array("45" =>"#FFE3CC",
  1009. "40" =>"#FFAC66",
  1010. "20" =>"#FF7500",
  1011. "air" =>"#FFE3CC",
  1012. "sea" =>"#FFAC66",
  1013. "road" =>"#FF7500");
  1014. return $data[$code];
  1015. }
  1016. if($type == "top"){
  1017. $data = array("1" =>"#FF7500",
  1018. "2" =>"#ff9033",
  1019. "3" =>"#ff9e4d",
  1020. "4" =>"#ffac66",
  1021. "5" =>"#ffba80",
  1022. "6" =>"#ffc899",
  1023. "7" =>"#ffd6b3",
  1024. "8" =>"#ffe3cc",
  1025. "9" =>"#fff1e6",
  1026. "10" =>"#fff1e6");
  1027. return $data[$code];
  1028. }
  1029. }
  1030. //处理返回原表数据格式
  1031. public static function mian_repot_do($value,$type,$totalValue){
  1032. $data = array();
  1033. $value_arr = json_decode($value,true);
  1034. //r1 是 ETD to ETA (Days)圆形图表数据结构返回
  1035. if($type == 'r1'){
  1036. $ETDList = array();
  1037. foreach($value_arr as $arr){
  1038. $color = common::getItemStyle($type,$arr['name']);
  1039. $ETDList[] = array("value" =>intval($arr['value']),"name" =>$arr['name'],"itemStyle" =>array("color" =>$color));
  1040. }
  1041. // 排序依据的键数组(这里我们用一个数字数组来表示)
  1042. $order = ["0-20 Days", "20-40 Days", "40-60 Days","60-80 Days","Over 80 Days"];
  1043. $ETDList = utils::arrayOrderBykeys($order,$ETDList,"name");
  1044. //$ETDList = array_reverse($ETDList);
  1045. $ETD_Title = "Total: $totalValue";
  1046. $data = array("ETDList" =>$ETDList,"ETD_Radius"=>array('50%','80%'),"ETD_Title" =>$ETD_Title,"download_name" => "ETD to ETA (Days)");
  1047. }
  1048. if($type == 'r4' || $type == 'r3'){
  1049. //重新整理一下数据,给UI一致
  1050. $data_kd = array();
  1051. foreach($value_arr as $arr){
  1052. if(stripos("Today", $arr['name']) !== false){
  1053. $color = common::getItemStyle($type,"Today");
  1054. if(empty($data_kd["0"])){
  1055. $data_kd["0"] = array("value" =>intval($arr['value']),"name" =>"≤1 Day","itemStyle" =>array("color" =>$color));
  1056. }else{
  1057. $data_kd["0"]["value"] = $data_kd["0"]["value"] + intval($arr['value']);
  1058. }
  1059. }
  1060. if(stripos("+1 Days/+2 Days", $arr['name']) !== false){
  1061. $color = common::getItemStyle($type,"1-2 Days");
  1062. if(empty($data_kd["1"])){
  1063. $data_kd["1"] = array("value" =>intval($arr['value']),"name" =>"1-2 Days","itemStyle" =>array("color" =>$color));
  1064. }else{
  1065. $data_kd["1"]["value"] = $data_kd["1"]["value"] + intval($arr['value']);
  1066. }
  1067. }
  1068. if(stripos("+3 Days/+4 Days/+5 Days/+6 Days", $arr['name']) !== false){
  1069. $color = common::getItemStyle($type,"3-6 Days");
  1070. if(empty($data_kd["2"])){
  1071. $data_kd["2"] = array("value" =>intval($arr['value']),"name" =>"3-6 Days","itemStyle" =>array("color" =>$color));
  1072. }else{
  1073. $data_kd["2"]["value"] = $data_kd["2"]["value"] + intval($arr['value']);
  1074. }
  1075. }
  1076. if(stripos("+7 Days/Over 7 Days", $arr['name']) !== false){
  1077. $color = common::getItemStyle($type,"7 Days");
  1078. if(empty($data_kd["3"])){
  1079. $data_kd["3"] = array("value" =>intval($arr['value']),"name" =>"≥7 Days","itemStyle" =>array("color" =>$color));
  1080. }else{
  1081. $data_kd["3"]["value"] = $data_kd["3"]["value"] + intval($arr['value']);
  1082. }
  1083. }
  1084. }
  1085. // 排序依据的键数组(这里我们用一个数字数组来表示)
  1086. $order = ["≤1 Day", "1-2 Days", "3-6 Days","≥7 Days"];
  1087. $data_kd = utils::arrayOrderBykeys($order,$data_kd,"name");
  1088. if($type == 'r4'){
  1089. $data = array("ETDList" =>$data_kd,"ETD_Radius"=>array('30%','50%'),"title1" =>"Departure","title2" =>"","download_name" => "Pending Departure");
  1090. }
  1091. if($type == 'r3'){
  1092. $data = array("ETDList" =>$data_kd,"ETD_Radius"=>array('30%','50%'),"title1" =>"Arrival","title2" =>"","download_name" => "Pending Arrival");
  1093. }
  1094. }
  1095. return $data;
  1096. }
  1097. //单独处理co2e bar
  1098. public static function getCo2eBar(){
  1099. //分担查询
  1100. include ONLINE_ROOT . 'libs' . DS . 'map_config.ini.php';
  1101. //新UI air sea road 目前只有sea
  1102. $type = $_REQUEST["r_type"];
  1103. $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1104. $sqlWhere = " " . $sqlWhere;
  1105. $date_type = strtolower($_REQUEST["date_type"]);
  1106. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start']))
  1107. $sqlWhere .= " and $date_type >= '" . common::usDate2sqlDate($_REQUEST['date_start']) . " 00:00:00'";
  1108. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end']))
  1109. $sqlWhere .= " and $date_type <= '" . common::usDate2sqlDate($_REQUEST['date_end']) . " 23:59:59'";
  1110. $transportation = $_REQUEST["transportation"];
  1111. if(!is_array($transportation)){
  1112. $transportation = array($transportation);
  1113. }
  1114. $mode_param = "";
  1115. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  1116. $mode_param = "'sea','air','road'";
  1117. }else{
  1118. $transport_mode = utils::implode(';', $transportation);
  1119. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  1120. }
  1121. $sqlWhere .= " and transport_mode in ($mode_param)";
  1122. $ContainerCount_Title = array();
  1123. //先查询总的排放量sea air road,确定排名后,在分别查询对应的sea air road
  1124. //这里的问题跟 top 一样 。总的排放量查询有问题。目前是总的排放量 暂时等于 sea的排放量
  1125. if ($type == "co2e_orgin"){
  1126. $co2e_shippr_sql = "select SUM(COALESCE(carbon_emission,0)) as catnum ,
  1127. sum(case when (1<>1 or (transport_mode='air')) then COALESCE(carbon_emission,0) else 0 end) as air_rc,
  1128. sum(case when (1<>1 or (transport_mode='sea')) then COALESCE(carbon_emission,0) else 0 end) as sea_rc,
  1129. sum(case when (1<>1 or (transport_mode='road')) then COALESCE(carbon_emission,0) else 0 end) as road_rc,
  1130. 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";
  1131. //$co2e_aLL = common::excuteListSql($co2e_shippr_sql);
  1132. $co2e_aLL = $mapdb->GetAll($co2e_shippr_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $co2e_shippr_sql), 0));
  1133. }
  1134. if ($type == "co2e_destination"){
  1135. $co2e_consignee_sql = "select SUM(COALESCE(carbon_emission,0)) as catnum ,
  1136. sum(case when (1<>1 or (transport_mode='air')) then COALESCE(carbon_emission,0) else 0 end) as air_rc,
  1137. sum(case when (1<>1 or (transport_mode='sea')) then COALESCE(carbon_emission,0) else 0 end) as sea_rc,
  1138. sum(case when (1<>1 or (transport_mode='road')) then COALESCE(carbon_emission,0) else 0 end) as road_rc,
  1139. 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";
  1140. //$co2e_aLL = common::excuteListSql($co2e_consignee_sql);
  1141. $co2e_aLL = $mapdb->GetAll($co2e_consignee_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $co2e_consignee_sql), 0));
  1142. }
  1143. //最大Y值
  1144. $maxY = 0;
  1145. $stations = array();
  1146. foreach($co2e_aLL as $val){
  1147. $ContainerCount_Title[] = $val['station'];
  1148. $maxY = $maxY > $val['catnum'] ? $maxY : $val['catnum'];
  1149. if(!empty($val['station'])){
  1150. $stations[] = $val['station'];
  1151. }
  1152. }
  1153. // $station_str = utils::implode(',',$stations);
  1154. $ContainerCounSeries = array();
  1155. $shipment_mode_arr = array("air","sea","road");
  1156. foreach($shipment_mode_arr as $_shipment_mode){
  1157. //类型有 sea air road,目前之类只查询sea的,其他为空
  1158. $shipment_mode = $_shipment_mode;
  1159. // $co2e = array();
  1160. if ($type == "co2e_orgin"){
  1161. // $co2e_shippr_sql_union = utils::_getSql($station_str,$type,$shipment_mode,$sqlWhere);
  1162. // if(!empty($co2e_shippr_sql_union)){
  1163. // $co2e = common::excuteListSql($co2e_shippr_sql_union);
  1164. // }
  1165. $download_name = "CO2e Emission by Origin (Top 10)";
  1166. }
  1167. if ($type == "co2e_destination"){
  1168. // $co2e_consignee_union = utils::_getSql($station_str,$type,$shipment_mode,$sqlWhere);
  1169. // if(!empty($co2e_consignee_union)){
  1170. // $co2e = common::excuteListSql($co2e_consignee_union);
  1171. // }
  1172. $download_name = "CO2e Emission by Destination (Top 10)";
  1173. }
  1174. $total = 0;
  1175. $max = 0;
  1176. $data = array();
  1177. foreach($co2e_aLL as $val){
  1178. $catnum = $shipment_mode."_rc";
  1179. $data[] = empty($val[$catnum])? 0 : round($val[$catnum], 4);
  1180. $total = $total + $val[$catnum];
  1181. $max = $max < $val[$catnum] ? $val[$catnum] : $max;
  1182. }
  1183. $ContainerCounSeries[$shipment_mode] = array("data"=>$data,"total"=>$total,"max"=>$max);
  1184. }
  1185. //处理返回时数据格式 其实不太需要计算最大值,在最开始总量查询的时候以及查询出来
  1186. $ContainerCounSeries_return = array();
  1187. foreach($ContainerCounSeries as $k =>$v){
  1188. $color = common::getItemStyle($type,$k);
  1189. $ContainerCounSeries_return[] = array("name"=>$k,"type"=>"bar","emphasis" => array("focus" =>"none"),
  1190. "stack" =>"总计","data" =>$v['data'],"itemStyle" =>array("color" =>$color),'barWidth'=>'40');
  1191. }
  1192. //处理返回原表数据格式
  1193. //计算刻度值 最小值是0,最大值是3000,刻度是500 interval
  1194. $interval = utils::calculateTicks(0,$maxY,10);
  1195. if($interval == 0){
  1196. //处理返回默认值
  1197. $interval = 1;
  1198. }
  1199. $returnData = array("ContainerCount_Title"=>"","ContainerCountList" =>$ContainerCount_Title,"ContainerCounSeries" =>$ContainerCounSeries_return,
  1200. "min" => 0,"Max" =>$interval*10,"interval" =>$interval,"download_name" => $download_name);
  1201. return $returnData;
  1202. }
  1203. public static function getTopBar(){
  1204. $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1205. $sqlWhere = " " . $sqlWhere;
  1206. $date_type = strtolower($_REQUEST["date_type"]);
  1207. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start']))
  1208. $sqlWhere .= " and $date_type >= '" . common::usDate2sqlDate($_REQUEST['date_start']) . " 00:00:00'";
  1209. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end']))
  1210. $sqlWhere .= " and $date_type <= '" . common::usDate2sqlDate($_REQUEST['date_end']) . " 23:59:59'";
  1211. $transportation = $_REQUEST["transportation"];
  1212. if(!is_array($transportation)){
  1213. $transportation = array($transportation);
  1214. }
  1215. $mode_param = "";
  1216. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  1217. $mode_param = "'sea','air','road'";
  1218. }else{
  1219. $transport_mode = utils::implode(';', $transportation);
  1220. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  1221. }
  1222. $sqlWhere .= " and transport_mode in ($mode_param)";
  1223. $toporiginType = "shippr_uncode";
  1224. $shippr_uncode_10_sql ="with aa as (select count(shippr_uncode) as num,shippr_uncode,
  1225. (array_agg(shipper_city))[1] AS shipper_city from public.kln_ocean
  1226. where 1=1 and COALESCE(shippr_uncode,'')<>'' $sqlWhere group by shippr_uncode order by num desc limit 10)
  1227. select aa.*,dd.* from aa
  1228. left join LATERAL ( select lon as lng, lat as lat,
  1229. '' as label, '' as infor, 3 as sort,
  1230. null::timestamp without time zone as stime,''::text as ptype
  1231. 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";
  1232. $shippr_uncode_10 = common::excuteListSql($shippr_uncode_10_sql);
  1233. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1234. if(utils::count($shippr_uncode_10) == 1 && empty($shippr_uncode_10[0]["shippr_uncode"])){
  1235. $toporiginType = "fport_of_loading_un";
  1236. $shippr_uncode_10_sql = "with aa as (select count(fport_of_loading_un) as num,fport_of_loading_un as shippr_uncode
  1237. 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)
  1238. select aa.*,dd.* from aa
  1239. left join LATERAL ( select lon as lng, lat as lat,
  1240. '' as label, '' as infor, 3 as sort,
  1241. null::timestamp without time zone as stime,''::text as ptype
  1242. 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";
  1243. $shippr_uncode_10 = common::excuteListSql($shippr_uncode_10_sql);
  1244. }
  1245. //$toporiginType = "fport_of_loading_un";
  1246. $topdestinationinType = "consignee_uncode";
  1247. $consignee_uncode_10_sql = "with aa as (select count(consignee_uncode) as num,consignee_uncode,
  1248. (array_agg(consignee_city))[1] AS consignee_city
  1249. from public.kln_ocean where 1=1 and COALESCE(consignee_uncode,'')<>'' $sqlWhere group by consignee_uncode order by num desc limit 10)
  1250. select aa.*,dd.* from aa
  1251. left join LATERAL ( select lon as lng, lat as lat,
  1252. '' as label, '' as infor, 3 as sort,
  1253. null::timestamp without time zone as stime,''::text as ptype
  1254. 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";
  1255. $consignee_uncode_10 = common::excuteListSql($consignee_uncode_10_sql);
  1256. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1257. if(utils::count($consignee_uncode_10) == 1 && empty($consignee_uncode_10[0]["consignee_uncode"])){
  1258. $topdestinationinType = "mport_of_discharge_un";
  1259. $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)
  1260. select aa.*,dd.* from aa
  1261. left join LATERAL ( select lon as lng, lat as lat,
  1262. '' as label, '' as infor, 3 as sort,
  1263. null::timestamp without time zone as stime,''::text as ptype
  1264. 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";
  1265. $consignee_uncode_10 = common::excuteListSql($consignee_uncode_10_sql);
  1266. }
  1267. $toporigin = array();
  1268. $toporiginMap = array();
  1269. $i = 0;
  1270. $origiNunMax = 0;
  1271. foreach($shippr_uncode_10 as $orgin){
  1272. $i = $i + 1;
  1273. $map = array();
  1274. if(!empty($orgin['lat'])&&!empty($orgin['lng'])){
  1275. $map = array("lat" =>$orgin['lat'],"lng" =>$orgin['lng']);
  1276. }
  1277. //$json = '{"lng":121.8525,"lat":29.926545,"label":"'.$orgin['origin'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1278. //$map = json_decode($json,true);
  1279. if(!empty($map)){
  1280. $toporiginMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1281. "divIcon" => array("iconSize"=>0),
  1282. "name" =>$orgin['shippr_uncode'],
  1283. "color" =>common::getItemStyle("top",$i),
  1284. "value" =>$orgin['num'],
  1285. "textcolor" =>"#FFF");
  1286. }
  1287. //查询uncode,对应的city
  1288. $city = "";
  1289. if($toporiginType == "shippr_uncode"){
  1290. $city = $orgin['shipper_city'];
  1291. }
  1292. //$city 做假数据
  1293. $toporigin[] = array("name"=>$orgin['shippr_uncode'],"city_name"=>$city,"value"=>$orgin['num'],"color"=>common::getItemStyle("top",$i));
  1294. $origiNunMax = $origiNunMax < $orgin['num'] ? $orgin['num'] : $origiNunMax;
  1295. }
  1296. $topdestination = array();
  1297. $topdestinationinMap = array();
  1298. $i = 0;
  1299. $agentiNunMax = 0;
  1300. foreach($consignee_uncode_10 as $agent){
  1301. $i = $i + 1;
  1302. $map = array();
  1303. if(!empty($agent['lat'])&&!empty($agent['lng'])){
  1304. $map = array("lat" =>$agent['lat'],"lng" =>$agent['lng']);
  1305. }
  1306. // $json = '{"lng":"100.78594000","lat":"13.68521000","label":"'.$agent['agent'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1307. // $map = json_decode($json,true);
  1308. if(!empty($map)){
  1309. $topdestinationinMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1310. "divIcon" => array("iconSize"=>0),
  1311. "name" =>$agent['consignee_uncode'],
  1312. "color" =>common::getItemStyle("top",$i),
  1313. "value" =>$agent['num'],
  1314. "textcolor" =>"#FFF");
  1315. }
  1316. //查询uncode,对应的city
  1317. $city = "";
  1318. if($topdestinationinType == "consignee_uncode"){
  1319. $city = $agent['consignee_city'];
  1320. }
  1321. //$city 做假数据
  1322. $topdestination[] = array("name"=>$agent['consignee_uncode'],"city_name"=>$city,"value"=>$agent['num'],"color"=>common::getItemStyle("top",$i));
  1323. $agentiNunMax = $agentiNunMax < $agent['num'] ? $agent['num'] : $agentiNunMax;
  1324. }
  1325. //处理返回原表数据格式
  1326. $interval = utils::calculateTicks(0,$origiNunMax,10);
  1327. if($interval == 0){
  1328. //处理返回默认值
  1329. $interval = 1;
  1330. }
  1331. $dest_interval = utils::calculateTicks(0,$agentiNunMax,10);
  1332. if($dest_interval == 0){
  1333. //处理返回默认值
  1334. $dest_interval = 1;
  1335. }
  1336. $returnData = array("seller_data_list_origin"=>$toporigin,"toporiginMap"=>array_reverse($toporiginMap),"toporiginType"=>$toporiginType,
  1337. "seller_data_list_destination"=>$topdestination,"topdestinationinMap"=>array_reverse($topdestinationinMap),"topdestinationinType"=>$topdestinationinType,
  1338. "min" => 0,"Max" =>$interval*10,"interval" =>$interval,
  1339. "dest_min" => 0,"dest_Max" =>$dest_interval*10,"dest_interval" =>$dest_interval);
  1340. return $returnData;
  1341. }
  1342. public static function getTopBarNew(){
  1343. //分担查询
  1344. include ONLINE_ROOT . 'libs' . DS . 'map_config.ini.php';
  1345. $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1346. $sqlWhere = " " . $sqlWhere;
  1347. $date_type = strtolower($_REQUEST["date_type"]);
  1348. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start']))
  1349. $sqlWhere .= " and $date_type >= '" . common::usDate2sqlDate($_REQUEST['date_start']) . " 00:00:00'";
  1350. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end']))
  1351. $sqlWhere .= " and $date_type <= '" . common::usDate2sqlDate($_REQUEST['date_end']) . " 23:59:59'";
  1352. $transportation = $_REQUEST["transportation"];
  1353. if(!is_array($transportation)){
  1354. $transportation = array($transportation);
  1355. }
  1356. $mode_param = "";
  1357. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  1358. $mode_param = "'sea','air','road'";
  1359. }else{
  1360. $transport_mode = utils::implode(';', $transportation);
  1361. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  1362. }
  1363. $sqlWhere .= " and transport_mode in ($mode_param)";
  1364. $toporiginType = "shippr_uncode";
  1365. $shippr_uncode_10_sql ="with aa as (select count(shippr_uncode) as num,shippr_uncode,
  1366. (array_agg(shipper_city))[1] AS shipper_city from public.kln_ocean
  1367. where 1=1 and COALESCE(shippr_uncode,'')<>'' $sqlWhere group by shippr_uncode order by num desc limit 10)
  1368. select aa.* from aa ";
  1369. $shippr_uncode_10 = $mapdb->GetAll($shippr_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $shippr_uncode_10_sql), 0));
  1370. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1371. if(utils::count($shippr_uncode_10) == 1 && empty($shippr_uncode_10[0]["shippr_uncode"])){
  1372. $toporiginType = "fport_of_loading_un";
  1373. $shippr_uncode_10_sql = "with aa as (select count(fport_of_loading_un) as num,fport_of_loading_un as shippr_uncode
  1374. 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)
  1375. select aa.* from aa ";
  1376. $shippr_uncode_10 = $mapdb->GetAll($shippr_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $shippr_uncode_10_sql), 0));
  1377. }
  1378. $topdestinationinType = "consignee_uncode";
  1379. $consignee_uncode_10_sql = "with aa as (select count(consignee_uncode) as num,consignee_uncode,
  1380. (array_agg(consignee_city))[1] AS consignee_city
  1381. from public.kln_ocean where 1=1 and COALESCE(consignee_uncode,'')<>'' $sqlWhere group by consignee_uncode order by num desc limit 10)
  1382. select aa.* from aa";
  1383. $consignee_uncode_10 = $mapdb->GetAll($consignee_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $consignee_uncode_10_sql), 0));
  1384. //如果值没有:客户地址-->站点地址-->Port地址(POL/POD)
  1385. if(utils::count($consignee_uncode_10) == 1 && empty($consignee_uncode_10[0]["consignee_uncode"])){
  1386. $topdestinationinType = "mport_of_discharge_un";
  1387. $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)
  1388. select aa.* from aa";
  1389. $consignee_uncode_10 = $mapdb->GetAll($consignee_uncode_10_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $consignee_uncode_10_sql), 0));
  1390. }
  1391. $toporigin = array();
  1392. $toporiginMap = array();
  1393. $i = 0;
  1394. $origiNunMax = 0;
  1395. foreach($shippr_uncode_10 as $orgin){
  1396. $i = $i + 1;
  1397. $map =common::excuteObjectSql("select lon as lng, lat as lat,
  1398. '' as label, '' as infor, 3 as sort,
  1399. null::timestamp without time zone as stime,''::text as ptype
  1400. 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']."'");
  1401. //$json = '{"lng":121.8525,"lat":29.926545,"label":"'.$orgin['origin'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1402. //$map = json_decode($json,true);
  1403. if(!empty($map)){
  1404. $toporiginMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1405. "divIcon" => array("iconSize"=>0),
  1406. "name" =>$orgin['shippr_uncode'],
  1407. "color" =>common::getItemStyle("top",$i),
  1408. "value" =>$orgin['num'],
  1409. "textcolor" =>"#FFF");
  1410. }
  1411. //查询uncode,对应的city
  1412. $city = "";
  1413. if($toporiginType == "shippr_uncode"){
  1414. $city = $orgin['shipper_city'];
  1415. }
  1416. //$city 做假数据
  1417. $toporigin[] = array("name"=>$orgin['shippr_uncode'],"city_name"=>$city,"value"=>$orgin['num'],"color"=>common::getItemStyle("top",$i));
  1418. $origiNunMax = $origiNunMax < $orgin['num'] ? $orgin['num'] : $origiNunMax;
  1419. }
  1420. $topdestination = array();
  1421. $topdestinationinMap = array();
  1422. $i = 0;
  1423. $agentiNunMax = 0;
  1424. foreach($consignee_uncode_10 as $agent){
  1425. $i = $i + 1;
  1426. $map =common::excuteObjectSql("select lon as lng, lat as lat,
  1427. '' as label, '' as infor, 3 as sort,
  1428. null::timestamp without time zone as stime,''::text as ptype
  1429. 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']."' ");
  1430. // $json = '{"lng":"100.78594000","lat":"13.68521000","label":"'.$agent['agent'].'","infor":"LAT KRABANG, THAILAND","sort":"0","stime":null,"ptype":"por"}';
  1431. // $map = json_decode($json,true);
  1432. if(!empty($map)){
  1433. $topdestinationinMap[] = array("qandl"=>array(floatval($map['lat']),floatval($map['lng'])),
  1434. "divIcon" => array("iconSize"=>0),
  1435. "name" =>$agent['consignee_uncode'],
  1436. "color" =>common::getItemStyle("top",$i),
  1437. "value" =>$agent['num'],
  1438. "textcolor" =>"#FFF");
  1439. }
  1440. //查询uncode,对应的city
  1441. $city = "";
  1442. if($topdestinationinType == "consignee_uncode"){
  1443. $city = $agent['consignee_city'];
  1444. }
  1445. //$city 做假数据
  1446. $topdestination[] = array("name"=>$agent['consignee_uncode'],"city_name"=>$city,"value"=>$agent['num'],"color"=>common::getItemStyle("top",$i));
  1447. $agentiNunMax = $agentiNunMax < $agent['num'] ? $agent['num'] : $agentiNunMax;
  1448. }
  1449. //处理返回原表数据格式
  1450. $interval = utils::calculateTicks(0,$origiNunMax,10);
  1451. if($interval == 0){
  1452. //处理返回默认值
  1453. $interval = 1;
  1454. }
  1455. $dest_interval = utils::calculateTicks(0,$agentiNunMax,10);
  1456. if($dest_interval == 0){
  1457. //处理返回默认值
  1458. $dest_interval = 1;
  1459. }
  1460. $returnData = array("seller_data_list_origin"=>$toporigin,"toporiginMap"=>array_reverse($toporiginMap),"toporiginType"=>$toporiginType,
  1461. "seller_data_list_destination"=>$topdestination,"topdestinationinMap"=>array_reverse($topdestinationinMap),"topdestinationinType"=>$topdestinationinType,
  1462. "min" => 0,"Max" =>$interval*10,"interval" =>$interval,
  1463. "dest_min" => 0,"dest_Max" =>$dest_interval*10,"dest_interval" =>$dest_interval);
  1464. return $returnData;
  1465. }
  1466. public static function getRevenue(){
  1467. //$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}';
  1468. //return json_decode($data,true);
  1469. $date_from = null;
  1470. $date_to = null;
  1471. if (isset($_REQUEST['date_start']) && !empty($_REQUEST['date_start'])){
  1472. $date_start = common::dateFormatToYM($_REQUEST['date_start']);
  1473. $date_from = $date_start."-01";
  1474. }
  1475. if (isset($_REQUEST['date_end']) && !empty($_REQUEST['date_end'])){
  1476. $date_end = common::dateFormatToYM($_REQUEST['date_end']);
  1477. $date_to = date('Y-m-t', strtotime($date_end."-01"));
  1478. }
  1479. $param = '{"user_login":"'._getLoginName().'","report_type":"ALL","date_from":"'.$date_from.'","date_to":"'.$date_to.'"}';
  1480. $sql = "SELECT * FROM get_customer_revenue_report('$param');FETCH ALL FROM r2;";
  1481. error_log("Revenue_sql:".$sql);
  1482. $r2_data = common::excuteListSql($sql);
  1483. //$r2_data = common::excuteListSql("select * from _test_data_table");
  1484. $barList = array();
  1485. $groupedItems = array();
  1486. foreach ($r2_data as $item) {
  1487. if(!utils::in_array($item['month'],$barList)){
  1488. $barList[] = $item['month'];
  1489. }
  1490. $groupedItems[$item['currency']][] = $item;
  1491. }
  1492. //补齐所有货币的月份
  1493. foreach($groupedItems as $ckey =>$cvalueArr){
  1494. $currency = array();
  1495. foreach($barList as $month){
  1496. $currency[] = common::findCurrencyByMonth($month,$ckey,$cvalueArr);
  1497. }
  1498. $groupedItems[$ckey] = $currency;
  1499. }
  1500. //处理barSeries
  1501. $barSeries = array();
  1502. //先准备4种颜色
  1503. $color = array("#FF7500","#FFAC66","#FFE3CC");
  1504. $index = 0;
  1505. $max = 0;
  1506. foreach($groupedItems as $currency => $series){
  1507. $series_max = 0;
  1508. $num = $index % 3;
  1509. $index = $index +1;
  1510. $tem_series = array();
  1511. $tem_series["name"] = $currency;
  1512. $tem_series["type"] = "bar";
  1513. $tem_series["emphasis"] = array("disabled"=>true,"focus"=>"none");
  1514. $tem_series["itemStyle"] = array("color"=>$color[$num],"borderRadius"=>6);
  1515. $tem_series["label"] = array("show"=>false,"color"=>"#646A73","position"=>"top","fontFamily"=>"Lato-Light","hideWhenMouseLeave"=>false);
  1516. //准备series data
  1517. $data = array();
  1518. $total = 0;
  1519. foreach($series as $_series){
  1520. $invoice_amount = empty($_series['invoice_amount'])? 0 : round($_series['invoice_amount'], 4);
  1521. $data[]=$invoice_amount;
  1522. $total = $total + $invoice_amount;
  1523. $max = $max<$_series['invoice_amount'] ? $_series['invoice_amount'] : $max;
  1524. $series_max = $series_max<$_series['invoice_amount'] ? $_series['invoice_amount'] : $series_max;
  1525. }
  1526. //计算Y坐标的间隔 每种货币的
  1527. $interval = utils::calculateTicks(0,$series_max,5);
  1528. if($interval == 0){
  1529. //处理返回默认值
  1530. $interval = 2;
  1531. }
  1532. $tem_series["Max"] = $interval*5;
  1533. $tem_series["interval"] = $interval;
  1534. $tem_series["data"] = $data;
  1535. $tem_series["total"] = floatval(number_format($total, 4, '.', ''));
  1536. $barSeries[] = $tem_series;
  1537. }
  1538. //计算Y坐标的间隔
  1539. $interval = utils::calculateTicks(0,$max,5);
  1540. if($interval == 0){
  1541. //处理返回默认值
  1542. $interval = 2;
  1543. }
  1544. $revenueBarData = array("bar_title" =>"Total:","barList" => $barList,
  1545. "barSeries" =>$barSeries,"download_name"=>"Rvenue","isShowTooltips"=>true,"Max" =>$interval*5,"interval" =>$interval);
  1546. return $revenueBarData;
  1547. }
  1548. public static function findCurrencyByMonth($month,$ckey,$cvalueArr){
  1549. $data = array("month" =>$month,"currency"=>$ckey,"invoice_amount"=>0,"sort_month"=>"");
  1550. foreach($cvalueArr as $realmonth){
  1551. if($realmonth['month'] == $month){
  1552. $data = $realmonth;
  1553. }
  1554. }
  1555. return $data;
  1556. }
  1557. public static function getdefaultManagement(){
  1558. $Management = array();
  1559. $Management[] = array("id"=>1 ,
  1560. "title"=>"KPI",
  1561. "switchValue"=>true,
  1562. "text"=>"Pie chart showing figures of shipments KPI of Departure and Arrival.");
  1563. $Management[] = array("id"=>2 ,
  1564. "title"=>"Pending",
  1565. "switchValue"=>true,
  1566. "text"=>"Pie chart showing figures of shipments which are soon to depart/arrive (Calculated from ETD/ETA).");
  1567. $Management[] = array("id"=>3 ,
  1568. "title"=>"ETD to ETA (Days)",
  1569. "switchValue"=>true,
  1570. "text"=>"Pie chart showing figures of shipments which are soon to depart/arrive (Calculated from ETD/ETA).");
  1571. $Management[] = array("id"=>4 ,
  1572. "title"=>"Container Count",
  1573. "switchValue"=>true,
  1574. "text"=>"Pie chart showing figures of shipments which are soon to depart/arrive (Calculated from ETD/ETA).");
  1575. //if(_isRevenueDisplay()){
  1576. $Management[] = array("id"=>5 ,
  1577. "title"=>"Revenue Spent",
  1578. "switchValue"=>_isRevenueDisplay(),
  1579. "text"=>"Revenue data for the past 12 months.",
  1580. "isRevenueDisplay"=>_isRevenueDisplay());
  1581. //}
  1582. $Management[] = array("id"=>6 ,
  1583. "title"=>"Top 10 Origin/Destination",
  1584. "switchValue"=>true,
  1585. "text"=>"Figure of the top 10 origin/destination.",
  1586. "title1"=>"Top 10 Origin",
  1587. "title2"=>"Top 10 Destination");
  1588. $Management[] = array("id"=>7 ,
  1589. "title"=>"CO2e Emission by Origin (Top 10)",
  1590. "switchValue"=>true,
  1591. "text"=>"Figure of the CO2e Emission by origin.");
  1592. $Management[] = array("id"=>8 ,
  1593. "title"=>"CO2e Emission by Destination (Top 10)",
  1594. "switchValue"=>true,
  1595. "text"=>"Figure of the CO2e Emission by destination.");
  1596. $Management[] = array("id"=>9 ,
  1597. "title"=>"Recent Status",
  1598. "switchValue"=>true,
  1599. "text"=>"A shipment list with latest status update on top.");
  1600. return $Management;
  1601. }
  1602. /**
  1603. * Destroy Session
  1604. */
  1605. public static function sessionDestroy() {
  1606. session_destroy();
  1607. setcookie(session_name(), '', time() - 3600);
  1608. $_SESSION = array();
  1609. }
  1610. public static function dateFormatToYM($dateString){
  1611. $date = DateTime::createFromFormat('m/Y', $dateString);
  1612. $formattedDate = $date->format('Y-m'); // YYYY-MM
  1613. return $formattedDate;
  1614. }
  1615. public static function retStationInfo($address_1,$address_2,$address_3,$address_4,$city,$state,$country,$zipcode){
  1616. $stationInfo = "";
  1617. if(!empty($address_1)){
  1618. $stationInfo .= $address_1;
  1619. }
  1620. if(!empty($address_2)){
  1621. $stationInfo .= " ".$address_2;
  1622. }
  1623. if(!empty($address_3)){
  1624. $stationInfo .= " ".$address_3;
  1625. }
  1626. if(!empty($address_4)){
  1627. $stationInfo .= " ".$address_4;
  1628. }
  1629. $temp_str = "";
  1630. if(!empty($city)){
  1631. $temp_str .= $city." ";
  1632. }
  1633. if(!empty($state)){
  1634. $temp_str .= $state." ";
  1635. }
  1636. if(!empty($zipcode)){
  1637. $temp_str .= $zipcode." ";
  1638. }
  1639. if(!empty($country)){
  1640. $temp_str .= $country." ";
  1641. }
  1642. if(!empty($temp_str)){
  1643. return $stationInfo." ".trim($temp_str);
  1644. }
  1645. return $stationInfo;
  1646. }
  1647. public static function getInsertSqlNull($table_name, $values) {
  1648. $field = "";
  1649. $value = "";
  1650. foreach ($values as $k => $v) {
  1651. if ($k == 'tmp' || $k == 'action' || $k == 'operate' || $k == 'x' || $k == 'y') {
  1652. continue;
  1653. }
  1654. if (is_array($v)) {
  1655. $v = utils::implode(",", $v);
  1656. }
  1657. if (empty($field)) {
  1658. $field = $k;
  1659. if (utils::checkExist($v, 'now()')) {
  1660. $value = $v;
  1661. } elseif ($v == null) {
  1662. $value .= 'null';
  1663. } elseif ($v == 'TRUE' || $v == 'FALSE') {
  1664. $value .= $v;
  1665. } else {
  1666. $value = '\'' . common::check_input($v) . '\'';
  1667. }
  1668. } else {
  1669. $field .= ',' . $k;
  1670. if (utils::checkExist($v, 'now()'))
  1671. $value .= ', now()';
  1672. elseif ($v == null) {
  1673. $value .= ',null';
  1674. } else if ($v == 'TRUE' || $v == 'FALSE') {
  1675. $value .= ',' . $v;
  1676. } else {
  1677. $value .= ', \'' . common::check_input($v) . '\'';
  1678. }
  1679. }
  1680. }
  1681. return 'insert into ' . $table_name . '(' . $field . ') values (' . $value . ')';
  1682. }
  1683. //密码规则验证
  1684. public static function checkPasswordRule($login, $new_password){
  1685. $sql="select item_value from config where item='passwordCheckRules'";
  1686. $rs = common::excuteObjectSql($sql);
  1687. $str = "";
  1688. if (!empty($rs)) {
  1689. $passwordCheckRules = json_decode($rs["item_value"],true);
  1690. //校验使用次数
  1691. if (!empty($passwordCheckRules["pastPasswordCheckNum"])) {
  1692. $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"];
  1693. $passwords = common::excuteListSql($sql);
  1694. foreach ($passwords as $pwd) {
  1695. if ($pwd['password'] == $new_password) {
  1696. $str = "This password has been recently used";
  1697. }
  1698. }
  1699. }
  1700. if(empty($str)){
  1701. $str = utils::checkPassword($new_password,$passwordCheckRules,$login);
  1702. }
  1703. }else{
  1704. $str = utils::checkPassword($new_password);
  1705. }
  1706. return $str;
  1707. }
  1708. public static function getMilestonesInfo($ocean,$transport_mode,$_schemas,$EDI315TimeAndLocation=array()){
  1709. //Milestones info列名固定
  1710. $Milestones_column = array();
  1711. $Milestones_column[] = array("title" =>"Milestones","field" =>"milestones","formatter" =>"normal","type" =>"normal");
  1712. $Milestones_column[] = array("title" =>"Date Time","field" =>"date_time","formatter" =>"dateTime","type" =>"normal");
  1713. $Milestones_column[] = array("title" =>"Locations","field" =>"locations","formatter" =>"normal","type" =>"normal");
  1714. $Milestones_column[] = array("title" =>"Remarks","field" =>"remarks","formatter" =>"normal","type" =>"normal");
  1715. //EDI315 有关联查询,以那个为准。但是如果是手工录入或者不是EDI 进去的Milestone的情况,这以这个为准
  1716. $Milestones_NO_Mapping = common::getMilestones_NO_Mapping_Data($ocean);
  1717. //Milestones 数据信息待定
  1718. $Milestones_data = array();
  1719. if($transport_mode == 'sea'){
  1720. $Milestones_data_arr = common::excuteListSql("select sn.description,act_date||' '||COALESCE(act_time,'') as date_time,
  1721. remark,timezone,a.code
  1722. from public.ocean_milestone a
  1723. inner join public.customer_service_milestone_sno sn on sn.code=a.code and sn.type = 'sea'
  1724. where a.serial_no='".$ocean["serial_no"]."' and act_date is not null order by sn.sno asc");
  1725. }else{
  1726. $Milestones_data_arr = common::excuteListSql("select sn.description,act_date||' '||COALESCE(act_time,'') as date_time,
  1727. remark,timezone,a.code
  1728. from $_schemas.air_milestone a
  1729. inner join public.customer_service_milestone_sno sn on sn.code=a.code and sn.type = 'air'
  1730. where a.serial_no='".$ocean["serial_no"]."' and act_date is not null order by sn.sno asc");
  1731. }
  1732. foreach($Milestones_data_arr as $mda){
  1733. $timezone = "";
  1734. $IFFICC_locations ="";
  1735. if(!empty($EDI315TimeAndLocation[$mda['code']])){
  1736. $edi315Info = $EDI315TimeAndLocation[$mda['code']];
  1737. if(!empty($edi315Info)){
  1738. $timezone = $edi315Info['timezone'];
  1739. }
  1740. //IFFICC 比较特殊用EDI的locations
  1741. if($mda['code'] == "IFFICC"){
  1742. $IFFICC_locations = $edi315Info['location'];
  1743. }
  1744. }else{
  1745. $edi315Info = $Milestones_NO_Mapping[$mda['code']];
  1746. if(!empty($edi315Info)){
  1747. $timezone = $edi315Info['timezone'];
  1748. }
  1749. }
  1750. //locations 以配置的信息为准
  1751. $locations = "";
  1752. $edi315Info = $Milestones_NO_Mapping[$mda['code']];
  1753. if(!empty($edi315Info)){
  1754. $locations = $edi315Info['location'];
  1755. if($mda['code'] == "IFFICC" && !empty($IFFICC_locations)){
  1756. $locations = $IFFICC_locations;
  1757. }
  1758. }
  1759. $Milestones_data[] = array("milestones"=>$mda['description'],"date_time"=>$mda['date_time'],"timezone" =>$timezone,
  1760. "locations" => $locations, "remarks" =>$mda['remark']);
  1761. }
  1762. $Milestones = array("Milestones_column"=>$Milestones_column,"Milestones_data" =>$Milestones_data);
  1763. return $Milestones;
  1764. }
  1765. /**
  1766. * 查询uncode 对应的时区
  1767. */
  1768. public static function getCityPortsInfo($uncodes){
  1769. $data =array();
  1770. $sql = "select time_zone as timezonecode,uncode as ctrycitycode from public.city_timezone where lower(uncode) ". common::getInNotInSql($uncodes);
  1771. $uncode_rs = common::excuteListSql($sql);
  1772. foreach($uncode_rs as $value){
  1773. $data[$value['ctrycitycode']] = $value['timezonecode'];
  1774. }
  1775. return $data;
  1776. }
  1777. /**
  1778. * EDI315 有关联查询,以那个为准。但是如果是手工录入或者没有对应的情况,这以这个为准
  1779. */
  1780. public static function getMilestones_NO_Mapping_Data($ocean){
  1781. $Milestones_NO_Mapping = array();
  1782. //取origin $ocean['aa_city'] 不是必需,对应文件里未提location来源
  1783. $Milestones_NO_Mapping['IFFBCF'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1784. $Milestones_NO_Mapping['IFFBCR'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1785. $Milestones_NO_Mapping['IFFCPU'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1786. $Milestones_NO_Mapping['IFFSIL'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1787. $Milestones_NO_Mapping['IFFEDO'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1788. $Milestones_NO_Mapping['IFFECC'] = array("code"=>"origin","timezone"=>$ocean['aa_timezone'],"location"=>"");
  1789. //Place of Receipt
  1790. $Milestones_NO_Mapping['IFFREC'] = array("code"=>"por/pol","timezone"=>$ocean['por_timezone'],"location"=>$ocean['por_uncity']);
  1791. $Milestones_NO_Mapping['IFFECP'] = array("code"=>"por/pol","timezone"=>$ocean['por_timezone'],"location"=>$ocean['por_uncity']);
  1792. //Port of loading
  1793. $Milestones_NO_Mapping['IFFONB'] = array("code"=>"por/pol","timezone"=>$ocean['pol_timezone'],"location"=>$ocean['pol_uncity']);
  1794. $Milestones_NO_Mapping['IFFDEP'] = array("code"=>"por/pol","timezone"=>$ocean['pol_timezone'],"location"=>$ocean['pol_uncity']);
  1795. //取destination $ocean['dd_city']不是必需
  1796. $Milestones_NO_Mapping['IFFCSN'] = array("code"=>"destination","timezone"=>$ocean['dd_timezone'],"location"=>"");
  1797. $Milestones_NO_Mapping['IFFIDO'] = array("code"=>"destination","timezone"=>$ocean['dd_timezone'],"location"=>"");
  1798. //取Port of discharge
  1799. $Milestones_NO_Mapping['IFFARR'] = array("code"=>"mpod","timezone"=>$ocean['mpod_timezone'],"location"=>$ocean['mpod_uncity']);
  1800. $Milestones_NO_Mapping['IFFUND'] = array("code"=>"mpod/pod/fd","timezone"=>$ocean['mpod_timezone'],"location"=>$ocean['mpod_uncity']);
  1801. $Milestones_NO_Mapping['IFFICC'] = array("code"=>"mpod","timezone"=>$ocean['mpod_timezone'],"location"=>$ocean['mpod_uncity']);
  1802. //Place of Delivery
  1803. $Milestones_NO_Mapping['IFFAFD'] = array("code"=>"pod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1804. $Milestones_NO_Mapping['IFFCTA'] = array("code"=>"pod/mpod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1805. $Milestones_NO_Mapping['IFFADW'] = array("code"=>"pod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1806. $Milestones_NO_Mapping['IFFDDW'] = array("code"=>"pod","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1807. $Milestones_NO_Mapping['IFFPPD'] = array("code"=>"mpod/pod/fd","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1808. $Milestones_NO_Mapping['IFFECR'] = array("code"=>"mpod/pod/fd","timezone"=>$ocean['pod_timezone'],"location"=>$ocean['pod_uncity']);
  1809. //final_destination $ocean['fd_city']不是必需
  1810. $Milestones_NO_Mapping['IFFDEL'] = array("code"=>"fd","timezone"=>$ocean['_fd_timezone'],"location"=>"");
  1811. $Milestones_NO_Mapping['IFFHBL'] = array("code"=>"fd","timezone"=>$ocean['_fd_timezone'],"location"=>"");
  1812. return $Milestones_NO_Mapping;
  1813. }
  1814. /**
  1815. * 这个详细查询已经带模式了
  1816. */
  1817. public static function getEDI315StatusForDetail($serial_no){
  1818. $data = array();
  1819. $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
  1820. WHERE o.serial_no='$serial_no'";
  1821. $ctnr_data = common::excuteListSql($ctnr_sql);
  1822. $containerStatusData = array();
  1823. $VD = "";
  1824. $VA = "";
  1825. $VD_RELAY = "";
  1826. $VA_RELAY = "";
  1827. foreach ($ctnr_data as $cd){
  1828. //存在柜号为空的数据情况
  1829. if(empty($cd['ctnr'])){
  1830. continue;
  1831. }
  1832. //(select uncity from public.ports where uncode = s.event_code) as uncity, 按新版的逻辑这个先取消掉
  1833. $ctnr_status_sql = "select s.source_id, s.event_base as event,
  1834. to_char(to_timestamp(s.event_date, 'YYYYMMDD'), 'YYYY-MM-DD') as eventdate,
  1835. to_char(to_timestamp(s.event_time, 'HH24MI'), 'HH24:MI') as eventtime,
  1836. e.description,s.event_type as eventtype,
  1837. s.event_code as eventcode, s.event_city as eventcity,
  1838. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1839. s.event_city as uncity,
  1840. case when s.event_base ='I' or s.event_base ='TR' then 'IFFREC'::text
  1841. when s.event_base ='AE' then 'IFFONB'::text
  1842. when s.event_base ='VD' then 'IFFDEP'::text
  1843. when s.event_base ='EB' or s.event_base ='VA' then 'IFFARR'::text
  1844. when s.event_base ='UV' then 'IFFUND'::text
  1845. when s.event_base ='VA' then 'IFFAFD'::text
  1846. when s.event_base ='AV' then 'IFFCTA'::text
  1847. when s.event_base ='CT' then 'IFFICC'::text
  1848. when s.event_base ='OA' or s.event_base ='D' then 'IFFPPD'::text
  1849. when s.event_base ='RD' then 'IFFECR'::text
  1850. when s.event_base ='EE' then 'IFFECP'::text
  1851. else '' ::text
  1852. end as milestone_code
  1853. from public.ra_online_container_status_v s
  1854. left join public.ra_online_edi_event e on s.event_base = e.ra_name
  1855. where s.serial_no = '" . pg_escape_string($cd['serial_no']) . "'
  1856. and s.container_no = '" . pg_escape_string($cd['ctnr']) . "' and is_display = true
  1857. order by to_timestamp(s.event_date, 'YYYYMMDD') desc,
  1858. to_timestamp(s.event_time, 'HH24MI') desc,e.ra_order desc";
  1859. $ctnr_status = common::excuteListSql($ctnr_status_sql);
  1860. //Container_Status 新版只显示几个状态, CTNR# EE I AE VD VA
  1861. $container_status_column = array("EE","I","AE","VD","VA");
  1862. $containerStatusDataTemp = array();
  1863. $content = array();
  1864. //按顺序处理 新版只显示几个状态
  1865. //foreach($container_status_column as $status){
  1866. foreach($ctnr_status as $event){
  1867. //if(strtolower($event['event']) == strtolower($status)){
  1868. $eventdate = $event["eventdate"];
  1869. if (empty($event["source_id"]) || $event["source_id"]==0) {
  1870. $eventdate.= " " . $event["eventtime"];
  1871. }
  1872. $location_code = $event["eventcode"];
  1873. $content[] = array("code" =>$event['event'],"title" =>$event['description'],"date"=>$eventdate,"country"=>$location_code,"timezone"=>$event['timezone'],
  1874. "uncity"=>$event['uncity']);
  1875. if(strtolower($event['event']) == "vd" && !empty($eventdate)){
  1876. $VD = $eventdate;
  1877. }
  1878. if(strtolower($event['event']) == "va" && !empty($eventdate)){
  1879. $VA = $eventdate;
  1880. }
  1881. if(strtolower($event['event']) == strtolower("VD_RELAY") && !empty($eventdate)){
  1882. $VD_RELAY = $eventdate;
  1883. }
  1884. if(strtolower($event['event']) == strtolower("VA_RELAY") && !empty($eventdate)){
  1885. $VA_RELAY = $eventdate;
  1886. }
  1887. //}
  1888. }
  1889. //}
  1890. //记录所有的信息
  1891. $EDI315TimeAndLocation = array();
  1892. foreach($ctnr_status as $event){
  1893. if(!empty($EDI315TimeAndLocation['IFFARR']) && $EDI315TimeAndLocation['IFFARR']['code'] == "EB"){
  1894. //如果存在EB 的EB 的优先级最高
  1895. continue;
  1896. }
  1897. if(!empty($EDI315TimeAndLocation['IFFPPD']) && $EDI315TimeAndLocation['IFFARR']['code'] == "OA"){
  1898. //如果存在OA 的OA 的优先级最高
  1899. continue;
  1900. }
  1901. $EDI315TimeAndLocation[$event['milestone_code']] = array("code"=>$event['event'],"timezone"=>$event['timezone'],"location"=>$event['uncity']);
  1902. }
  1903. $containerStatusDataTemp['label'] = $cd['ctnr']." / ".$cd['size'];
  1904. $containerStatusDataTemp['ctnr_label'] = $cd['ctnr'];
  1905. $containerStatusDataTemp['content'] = $content;
  1906. $containerStatusData[] = $containerStatusDataTemp;
  1907. }
  1908. $data['containerStatusData'] = $containerStatusData;
  1909. $data['EDI315TimeAndLocation'] = $EDI315TimeAndLocation;
  1910. $data['VD'] = $VD;
  1911. $data['VA'] = $VA;
  1912. $data['VD_RELAY'] = $VD_RELAY;
  1913. $data['VA_RELAY'] = $VA_RELAY;
  1914. return $data;
  1915. }
  1916. public static function getEDI315Time($serial_no,$_schemas){
  1917. //Timezone From 来自于EDI315
  1918. $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
  1919. WHERE o.serial_no='$serial_no'";
  1920. $ctnr_data = common::excuteListSql($ctnr_sql);
  1921. $EDI315TimeAndLocation = array();
  1922. foreach ($ctnr_data as $cd){
  1923. //存在柜号为空的数据情况
  1924. if(empty($cd['ctnr'])){
  1925. continue;
  1926. }
  1927. $ctnr_status_sql = "select
  1928. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1929. case when s.event_base ='I' or s.event_base ='TR' then 'IFFREC'::text
  1930. when s.event_base ='AE' then 'IFFONB'::text
  1931. when s.event_base ='VD' then 'IFFDEP'::text
  1932. when s.event_base ='EB' or s.event_base ='VA' then 'IFFARR'::text
  1933. when s.event_base ='UV' then 'IFFUND'::text
  1934. when s.event_base ='VA' then 'IFFAFD'::text
  1935. when s.event_base ='AV' then 'IFFCTA'::text
  1936. when s.event_base ='CT' then 'IFFICC'::text
  1937. when s.event_base ='OA' or s.event_base ='D' then 'IFFPPD'::text
  1938. when s.event_base ='RD' then 'IFFECR'::text
  1939. when s.event_base ='EE' then 'IFFECP'::text
  1940. else '' ::text
  1941. end as milestone_code
  1942. from public.ra_online_container_status_v s
  1943. left join public.ra_online_edi_event e on s.event_base = e.ra_name
  1944. where s.serial_no = '" . pg_escape_string($cd['serial_no']) . "'
  1945. and s.container_no = '" . pg_escape_string($cd['ctnr']) . "' and is_display = true
  1946. order by to_timestamp(s.event_date, 'YYYYMMDD') asc,
  1947. to_timestamp(s.event_time, 'HH24MI') asc,e.ra_order asc";
  1948. $ctnr_status = common::excuteListSql($ctnr_status_sql);
  1949. //记录所有的信息、替换最后一个柜子
  1950. $EDI315TimeAndLocation = array();
  1951. foreach($ctnr_status as $event){
  1952. if(!empty($EDI315TimeAndLocation['IFFARR']) && $EDI315TimeAndLocation['IFFARR']['code'] == "EB"){
  1953. //如果存在EB 的EB 的优先级最高
  1954. continue;
  1955. }
  1956. if(!empty($EDI315TimeAndLocation['IFFPPD']) && $EDI315TimeAndLocation['IFFARR']['code'] == "OA"){
  1957. //如果存在OA 的OA 的优先级最高
  1958. continue;
  1959. }
  1960. $EDI315TimeAndLocation[$event['milestone_code']] = array("code"=>$event['event'],"timezone"=>$event['timezone']);
  1961. }
  1962. }
  1963. return $EDI315TimeAndLocation;
  1964. }
  1965. public static function getMilestoneTimeAndlocations($milestone_code,$transport_mode,$serial_no,$order_from){
  1966. $EDI315TimeAndLocation = array();
  1967. if($transport_mode == "sea"){
  1968. $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
  1969. WHERE o.serial_no='$serial_no'";
  1970. $ctnr_data = common::excuteListSql($ctnr_sql);
  1971. foreach ($ctnr_data as $cd){
  1972. //存在柜号为空的数据情况
  1973. if(empty($cd['ctnr'])){
  1974. continue;
  1975. }
  1976. $ctnr_status_sql = "select s.source_id, s.event_base as event,
  1977. to_char(to_timestamp(s.event_date, 'YYYYMMDD'), 'YYYY-MM-DD') as eventdate,
  1978. to_char(to_timestamp(s.event_time, 'HH24MI'), 'HH24:MI') as eventtime,
  1979. e.description,s.event_type as eventtype,
  1980. s.event_code as eventcode, s.event_city as eventcity,
  1981. (select time_zone from public.city_timezone where uncode = s.event_code) as timezone,
  1982. (select uncity from public.ports where uncode = s.event_code) as uncity,
  1983. case when s.event_base ='I' then 'IFFREC'::text
  1984. when s.event_base ='AE' then 'IFFONB'::text
  1985. when s.event_base ='VD' then 'IFFDEP'::text
  1986. when s.event_base ='EB' or s.event_base ='VA' then 'IFFARR'::text
  1987. when s.event_base ='UV' then 'IFFUND'::text
  1988. when s.event_base ='VA' then 'IFFAFD'::text
  1989. when s.event_base ='AV' then 'IFFCTA'::text
  1990. when s.event_base ='CT' then 'IFFICC'::text
  1991. when s.event_base ='OA' or s.event_base ='D' then 'IFFPPD'::text
  1992. when s.event_base ='EE' then 'IFFECP'::text
  1993. else '' ::text
  1994. end as milestone_code
  1995. from public.ra_online_container_status_v s
  1996. left join ra_online_edi_event e on s.event_base = e.ra_name
  1997. where s.serial_no = '" . pg_escape_string($cd['serial_no']) . "'
  1998. and s.container_no = '" . pg_escape_string($cd['ctnr']) . "' and is_display = true
  1999. order by to_timestamp(s.event_date, 'YYYYMMDD') asc,
  2000. to_timestamp(s.event_time, 'HH24MI') asc,e.ra_order asc";
  2001. $ctnr_status = common::excuteListSql($ctnr_status_sql);
  2002. //记录所有的信息
  2003. $EDI315TimeAndLocation = array();
  2004. foreach($ctnr_status as $event){
  2005. if(!empty($EDI315TimeAndLocation['IFFARR']) && $EDI315TimeAndLocation['IFFARR']['code'] == "EB"){
  2006. //如果存在EB 的EB 的优先级最高
  2007. continue;
  2008. }
  2009. if(!empty($EDI315TimeAndLocation['IFFPPD']) && $EDI315TimeAndLocation['IFFARR']['code'] == "OA"){
  2010. //如果存在OA 的OA 的优先级最高
  2011. continue;
  2012. }
  2013. $EDI315TimeAndLocation[$event['milestone_code']] = array("code"=>$event['event'],"timezone"=>$event['timezone'],"location"=>$event['uncity']);
  2014. }
  2015. }
  2016. }
  2017. //当前数据的所有time city 查询
  2018. $sql = common::trackingSql($serial_no,$order_from);
  2019. $data_arr = common::excuteListSql($sql);
  2020. $data = $data_arr[0];
  2021. //EDI315 有关联查询,以那个为准。但是如果是手工录入或者不是EDI 进去的Milestone的情况,这以这个为准
  2022. $Milestones_NO_Mapping = common::getMilestones_NO_Mapping_Data($data);
  2023. $timezone = "";
  2024. $IFFICC_locations ="";
  2025. if(!empty($EDI315TimeAndLocation[$milestone_code])){
  2026. $edi315Info = $EDI315TimeAndLocation[$milestone_code];
  2027. if(!empty($edi315Info)){
  2028. $timezone = $edi315Info['timezone'];
  2029. }
  2030. //IFFICC 比较特殊用EDI的locations
  2031. if($milestone_code == "IFFICC"){
  2032. $IFFICC_locations = $edi315Info['location'];
  2033. }
  2034. }else{
  2035. $edi315Info = $Milestones_NO_Mapping[$milestone_code];
  2036. if(!empty($edi315Info)){
  2037. $timezone = $edi315Info['timezone'];
  2038. }
  2039. }
  2040. //locations 以配置的信息为准
  2041. $locations = "";
  2042. $edi315Info = $Milestones_NO_Mapping[$milestone_code];
  2043. if(!empty($edi315Info)){
  2044. $locations = $edi315Info['location'];
  2045. if($milestone_code == "IFFICC" && !empty($IFFICC_locations)){
  2046. $locations = $IFFICC_locations;
  2047. }
  2048. }
  2049. return array("timezone" =>$timezone,"locations" =>$locations);
  2050. }
  2051. public static function trackingSql($serial_no,$order_from){
  2052. $_schemas = $order_from;
  2053. if($_schemas == 'public'){
  2054. $_schemas = "ocean";
  2055. }
  2056. $sql = "with o as(
  2057. SELECT oo.*,m_bol as _m_bol, h_bol as _h_bol,
  2058. (select time_zone from public.city_timezone where uncode = oo.fport_of_loading_un limit 1) as pol_timezone,
  2059. case when oo.transport_mode ='sea'
  2060. then (select uncity from $order_from.ports where uncode = oo.fport_of_loading_un limit 1)
  2061. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.fport_of_loading_un limit 1)
  2062. end as pol_uncity,
  2063. (select time_zone from public.city_timezone where uncode = oo.mport_of_discharge_un limit 1) as mpod_timezone,
  2064. case when oo.transport_mode ='sea'
  2065. then (select uncity from $order_from.ports where uncode = oo.mport_of_discharge_un limit 1)
  2066. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.mport_of_discharge_un limit 1)
  2067. end as mpod_uncity,
  2068. (select time_zone from public.city_timezone where uncode = oo.place_of_receipt_un limit 1) as por_timezone,
  2069. case when oo.transport_mode ='sea'
  2070. then (select uncity from $order_from.ports where uncode = oo.place_of_receipt_un limit 1)
  2071. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.place_of_receipt_un limit 1)
  2072. end as por_uncity,
  2073. (select time_zone from public.city_timezone where uncode = oo.place_of_delivery_un limit 1) as pod_timezone,
  2074. case when oo.transport_mode ='sea'
  2075. then (select uncity from $order_from.ports where uncode = oo.place_of_delivery_un limit 1)
  2076. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.place_of_delivery_un limit 1)
  2077. end as pod_uncity,
  2078. (select time_zone from public.city_timezone where uncode = oo.final_desination_uncode limit 1) as _fd_timezone,
  2079. case when oo.transport_mode ='sea'
  2080. then (select uncity from $order_from.ports where uncode = oo.final_desination_uncode limit 1)
  2081. else (select city from sfs.airport where coalesce(airport.country_abb,'')||airport.airport_code = oo.final_desination_uncode limit 1)
  2082. end as _pd_uncity,
  2083. CASE
  2084. 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
  2085. 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
  2086. WHEN (m_iffdep is not null and m_iffarr is null and m_iffdel is null) THEN 'Departure'::text
  2087. WHEN (m_iffarr is not null and m_iffdel is null) THEN 'Arrived'::text
  2088. WHEN (m_iffdel is not null) THEN 'Completed'::text
  2089. ELSE 'Created'::text
  2090. END AS new_status
  2091. from public.kln_ocean oo where oo.serial_no = '" . $serial_no . "' and oo.order_from = '$order_from'
  2092. )
  2093. SELECT o.* ,sh.*, cn.*,aa.*,dd.*,fd.*
  2094. from o
  2095. LEFT JOIN LATERAL ( SELECT company as cn_company,
  2096. address_1 as cn_address_1,
  2097. address_2 as cn_address_2,
  2098. address_3 as cn_address_3,
  2099. address_4 as cn_address_4,
  2100. city as cn_city, state as cn_state, zipcode as cn_zipcode, country as cn_country,
  2101. phone_1 as cn_phone
  2102. FROM $_schemas.contacts c WHERE o.consignee_id::text = c.contact_id::text) cn ON true
  2103. LEFT JOIN LATERAL ( SELECT company as sh_company,
  2104. address_1 as sh_address_1,
  2105. address_2 as sh_address_2,
  2106. address_3 as sh_address_3,
  2107. address_4 as sh_address_4,
  2108. city as sh_city, state as sh_state, zipcode as sh_zipcode, country as sh_country,
  2109. phone_1 as sh_phone
  2110. FROM $_schemas.contacts c WHERE o.shipper_id::text = c.contact_id::text) sh ON true
  2111. LEFT JOIN LATERAL ( SELECT company as aa_company,
  2112. address_1 as aa_address_1,
  2113. address_2 as aa_address_2,
  2114. address_3 as aa_address_3,
  2115. address_4 as aa_address_4,
  2116. city as aa_city, state as aa_state, zipcode as aa_zipcode, country as aa_country,
  2117. phone_1 as aa_phone,
  2118. (select time_zone from public.city_timezone where uncode = LEFT(c.country, 2) || COALESCE(c.city_code,'') limit 1) as aa_timezone
  2119. FROM $_schemas.contacts c WHERE o.origin::text = c.contact_id::text) aa ON true
  2120. LEFT JOIN LATERAL ( SELECT company as dd_company,
  2121. address_1 as dd_address_1,
  2122. address_2 as dd_address_2,
  2123. address_3 as dd_address_3,
  2124. address_4 as dd_address_4,
  2125. city as dd_city, state as dd_state, zipcode as dd_zipcode, country as dd_country,
  2126. phone_1 as dd_phone,
  2127. (select time_zone from public.city_timezone where uncode = LEFT(c.country, 2) || COALESCE(c.city_code,'') limit 1) as dd_timezone
  2128. FROM $_schemas.contacts c WHERE o.agent::text = c.contact_id::text) dd ON true
  2129. LEFT JOIN LATERAL ( SELECT
  2130. city as fd_city,
  2131. (select time_zone from public.city_timezone where uncode = LEFT(c.country, 2) || COALESCE(c.city_code,'') limit 1) as fd_timezone
  2132. FROM $_schemas.contacts c WHERE o.final_desination::text = c.contact_id::text) fd ON true";
  2133. return $sql;
  2134. }
  2135. public static function getDashboardTransportationSqlWhere(){
  2136. $transportation = $_REQUEST["transportation"];
  2137. if(!is_array($transportation)){
  2138. $transportation = array($transportation);
  2139. }
  2140. $mode_param = "";
  2141. if(utils::count($transportation) == 1 && strtolower($transportation[0]) == 'all' ){
  2142. $mode_param = "'sea','air','road'";
  2143. }else{
  2144. $transport_mode = utils::implode(';', $transportation);
  2145. $mode_param = common::getInNotInSqlForSearch($transport_mode);
  2146. }
  2147. return " and transport_mode in ($mode_param)";
  2148. }
  2149. /*
  2150. * Create Directory
  2151. */
  2152. public static function mkdirs($path, $mode = 0777) { //creates directory tree recursively
  2153. if (!file_exists($path)) {
  2154. if (!mkdir($path, $mode, TRUE))
  2155. return FALSE;
  2156. }
  2157. return TRUE;
  2158. }
  2159. /**
  2160. * checked is_subscribe
  2161. */
  2162. public static function checkedSubscribe($serial_no) { //creates directory tree recursively
  2163. $is_subscribe_exist = common::excuteOneSql("select user_login from public.kln_user_subscribed us
  2164. where lower(us.user_login) = '".strtolower(_getLoginName())."' and us.subscribed_serial_no = '".$serial_no."'");
  2165. if(empty($is_subscribe_exist)){
  2166. $is_subscribe = false;
  2167. }else{
  2168. $is_subscribe = true;
  2169. }
  2170. return $is_subscribe;
  2171. }
  2172. /**
  2173. * get webiste
  2174. */
  2175. public static function getWebiste($carrier) {
  2176. $website = "";
  2177. if (!empty($carrier)){
  2178. $website = common::excuteOneSql("select website from vessel_company where scac = '$carrier'");
  2179. }
  2180. if (strpos($website, ";") === FALSE){
  2181. }else{
  2182. $site = explode(";", $website);
  2183. $website = $site[0];
  2184. }
  2185. return $website;
  2186. }
  2187. public static function getWeek($week){
  2188. if ($week == "0"){
  2189. $week = "Sunday";
  2190. } elseif ($week == "1"){
  2191. $week = "Monday";
  2192. } elseif ($week == "2"){
  2193. $week = "Tuesday";
  2194. } elseif ($week == "3"){
  2195. $week = "Wednesday";
  2196. } elseif ($week == "4"){
  2197. $week = "Thursday";
  2198. } elseif ($week == "5"){
  2199. $week = "Friday";
  2200. } elseif ($week == "6"){
  2201. $week = "Sunday";
  2202. }
  2203. return $week;
  2204. }
  2205. /**
  2206. * 这里基准event 写死, 根据online查询页面的通用的来, 这里需提问确定
  2207. */
  2208. public static function getEDICtnrEvent(){
  2209. $event =array(array("event_name"=>"EE","description"=>"Empty Equipment Dispatched"),
  2210. array("event_name"=>"I","description"=>"Gate in full for a booking"),
  2211. array("event_name"=>"AE","description"=>"Container loaded on vessel"),
  2212. array("event_name"=>"VD","description"=>"Vessel Departure"),
  2213. array("event_name"=>"VA_RELAY","description"=>"Arrive Relay Port"),
  2214. array("event_name"=>"UV_RELAY","description"=>"Unloaded at Relay Port"),
  2215. array("event_name"=>"AE_RELAY","description"=>"Loaded at Relay Port"),
  2216. array("event_name"=>"VD_RELAY","description"=>"Depart Relay Port"),
  2217. array("event_name"=>"CU","description"=>"Carrier and Customs Release"),
  2218. array("event_name"=>"CT","description"=>"Customs release"),
  2219. array("event_name"=>"CR","description"=>"Carrier release"),
  2220. array("event_name"=>"VA","description"=>"Vessel Arrival"),
  2221. array("event_name"=>"UV","description"=>"Unloaded From Vessel"),
  2222. array("event_name"=>"AG","description"=>"Estimated Delivery"),
  2223. array("event_name"=>"OA","description"=>"Gate out full from final discharge port"),
  2224. array("event_name"=>"FT","description"=>"Free Time Expired"),
  2225. array("event_name"=>"AL","description"=>"Container loaded on Rail"),
  2226. array("event_name"=>"AR","description"=>"Container unloaded from Rail"),
  2227. array("event_name"=>"AV","description"=>"Shipment available for pickup or delivery"),
  2228. array("event_name"=>"D","description"=>"Gate out for delivery to customer"),
  2229. array("event_name"=>"RD","description"=>"Container returned empty"),
  2230. array("event_name"=>"C","description"=>"Vessel Estimated Time of Departure"),
  2231. array("event_name"=>"C_RELAY","description"=>"Estimated Time of Departure from Tranship Port"),
  2232. array("event_name"=>"AG_DES","description"=>"Estimated Delivery Destination"),
  2233. array("event_name"=>"IFFADW","description"=>"Shipment in CFS warehouse"),
  2234. array("event_name"=>"IFFDDW","description"=>"Shipment Out from CFS House"));
  2235. return $event;
  2236. }
  2237. /**
  2238. * 处理daily 和 week 不同周或者天的数据分组
  2239. */
  2240. public static function handleDailyWeekedData($notificationsArr){
  2241. $uniqe = array();
  2242. $ret = array();
  2243. foreach($notificationsArr as $info){
  2244. $uniqe_group_str = $info['insert_date_format'];
  2245. if(utils::in_array($uniqe_group_str,$uniqe)){
  2246. $tempArr = $ret[$uniqe_group_str];
  2247. $tempArr[] = $info;
  2248. $ret[$uniqe_group_str] = $tempArr;
  2249. } else {
  2250. $ret[$uniqe_group_str] = array($info);
  2251. $uniqe[] = $uniqe_group_str;
  2252. }
  2253. }
  2254. return $ret;
  2255. }
  2256. /**
  2257. * /unit=="Day(s)" ? "days":"hours";
  2258. */
  2259. public static function convertoVue($unit){
  2260. if(empty($unit))
  2261. return $unit;
  2262. if ($unit == "days"){
  2263. return "Day(s)";
  2264. }else{
  2265. return "Hour(s)";
  2266. }
  2267. }
  2268. /**
  2269. * vue to int
  2270. */
  2271. public static function convertoint($num){
  2272. if($num == "0"){
  2273. return intval($num);
  2274. }
  2275. return !empty($num) ? intval($num): $num;
  2276. }
  2277. //检查user name length
  2278. public static function checkUserNameLength($input) {
  2279. if(!empty($input) && strlen($input) > 50){
  2280. $data = array(
  2281. 'code' => 'no_exist',
  2282. 'login_version' => '',
  2283. 'msg' => 'The username or password you entered is incorrect'
  2284. );
  2285. common::echo_json_encode(500, $data);
  2286. exit();
  2287. }
  2288. }
  2289. public static function checkInputInval($input) {
  2290. $data = true;
  2291. // 定义危险 SQL 关键字列表
  2292. $dangerousKeywords = [
  2293. 'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'DROP', 'ALTER', 'CREATE',
  2294. 'UNION', 'EXEC', 'EXECUTE', 'TRUNCATE', 'GRANT', 'REVOKE',
  2295. 'WAITFOR', 'DELAY', 'PG_SLEEP', '--', ';'
  2296. ];
  2297. // 检查是否包含危险关键字(不区分大小写)
  2298. foreach ($dangerousKeywords as $keyword) {
  2299. if (stripos($input, $keyword) !== false) {
  2300. $data = false;
  2301. }
  2302. }
  2303. // 检查是否包含 SQL 注入常见模式
  2304. if (preg_match('/\b(OR|AND)\s+1\s*=\s*1\b/i', $input) ||
  2305. preg_match('/\bUNION\s+SELECT\b/i', $input)) {
  2306. $data = false;
  2307. }
  2308. if(!empty($input) && strlen($input) > 50){
  2309. $data = false;
  2310. }
  2311. return $data;
  2312. }
  2313. public static function checkSafeSql($input) {
  2314. $data = true;
  2315. // 定义危险 SQL 关键字列表
  2316. $dangerousKeywords = [
  2317. 'INSERT', 'UPDATE', 'DELETE', 'DROP', 'ALTER', 'CREATE',
  2318. 'UNION', 'EXEC', 'EXECUTE', 'TRUNCATE', 'GRANT', 'REVOKE',
  2319. 'WAITFOR', 'DELAY', 'PG_SLEEP'
  2320. ];
  2321. // 检查是否包含危险关键字(不区分大小写)
  2322. foreach ($dangerousKeywords as $keyword) {
  2323. $pattern = '/\b' . preg_quote($keyword, '/') . '\b/i'; // \b 表示单词边界
  2324. if (preg_match($pattern, $input)) {
  2325. $data = false;
  2326. break; // 提高性能,发现一个就返回
  2327. }
  2328. }
  2329. // 可选:进一步确认是否为 SELECT 查询
  2330. if (!preg_match('/^\s*SELECT\b/i', trim($input))) {
  2331. $data = false; // 不是以 SELECT 开头
  2332. }
  2333. // 转为小写统一处理
  2334. $sqlLower = strtolower($input);
  2335. // 查找 'from' 出现的位置
  2336. $fromPos = stripos($sqlLower, 'from');
  2337. if ($fromPos === false) {
  2338. return false; // 没有 from,不可能有 where,直接返回 false
  2339. }
  2340. // 从 from 之后的部分中查找 where
  2341. $afterFrom = substr($sqlLower, $fromPos + 4); // +4 是跳过 'from'
  2342. if (stripos($afterFrom, 'WHERE') === false && stripos($afterFrom, 'limit') === false){
  2343. $data = false; // 简单的判断是否带条件查询
  2344. }
  2345. return $data;
  2346. }
  2347. //预加载写法
  2348. public static function excuteObjectPrepareSql($sql,$param) {
  2349. if (empty($sql))
  2350. exit(json_encode("Program encountered an error."));
  2351. global $db;
  2352. $stmt = $db->Prepare($sql);
  2353. $result = $db->Execute($stmt, $param);
  2354. if ($result && $result->RecordCount() > 0) {
  2355. $row = $result->fields;
  2356. return $row;
  2357. }
  2358. return null;
  2359. }
  2360. //拼接换行
  2361. public static function splicedLlineBreaks() {
  2362. return "
  2363. ";
  2364. }
  2365. /**
  2366. * chat获取自然序列号
  2367. */
  2368. public static function getChatAiSequence(){
  2369. $sequence = common::excuteOneSql("select count(*) from kln_robot_chat_log where request_time >= CURRENT_DATE");
  2370. $sequence = empty($sequence)? "1" : $sequence + 1;
  2371. if($sequence >99999){
  2372. return $sequence;
  2373. }
  2374. $sequence = sprintf("%05d", $sequence);
  2375. return $sequence;
  2376. }
  2377. /**
  2378. * 处理chat 返回的json字符串
  2379. */
  2380. public static function getChatAimessage($message){
  2381. //格式:"```json ```"
  2382. return str_replace(["```json", "```"], "", $message);
  2383. }
  2384. public static function extractSelectFields($sql){
  2385. // 正则表达式匹配 SELECT 和 FROM 之间的内容
  2386. if (preg_match('/SELECT\s+(.*?)\s+FROM/si', $sql, $matches)) {
  2387. $selectPart = $matches[1];
  2388. // 去除注释和换行
  2389. $selectPart = preg_replace('/--.*$/m', '', $selectPart); // 去除单行注释
  2390. $selectPart = preg_replace('/\/\*.*?\*\//s', '', $selectPart); // 去除多行注释
  2391. $selectPart = str_replace(["\r", "\n"], ' ', $selectPart); // 换行替换成空格
  2392. // 分割字段
  2393. $fields = [];
  2394. foreach (explode(',', $selectPart) as $field) {
  2395. $field = trim($field);
  2396. if (empty($field)) continue;
  2397. // 匹配 AS 别名
  2398. if (preg_match('/(?:AS\s+)?(\w+)$/i', $field, $aliasMatch)) {
  2399. // 如果有别名,则使用别名
  2400. $fields[] = strtolower($aliasMatch[1]);
  2401. } else {
  2402. // 否则直接添加字段名
  2403. $fields[] = strtolower(trim($field));
  2404. }
  2405. }
  2406. return array_unique($fields);
  2407. }
  2408. return []; // 如果没有找到 SELECT 字段
  2409. }
  2410. public static function getUserCountry(){
  2411. $contact_id = $_SESSION['ONLINE_USER']['contact_id'];
  2412. if(empty($contact_id)){
  2413. return "claude";
  2414. }
  2415. $model = "deepseek";
  2416. $belong_schemas = $_SESSION['ONLINE_USER']['belong_schemas'];
  2417. if(empty($belong_schemas)){
  2418. $belong_schemas = "public";
  2419. }
  2420. if(stripos($belong_schemas, "public") !== false){
  2421. $data = common::excuteListSql("select LEFT(country, 2) as country from ocean.contacts where contact_id = '$contact_id'");
  2422. foreach($data as $country){
  2423. if($country['country'] != "CN"){
  2424. $model = "claude";
  2425. }
  2426. }
  2427. }
  2428. if(stripos($belong_schemas, "sfs") !== false){
  2429. $data = common::excuteListSql("select LEFT(country, 2) as country from sfs.contacts where contact_id = '$contact_id'");
  2430. foreach($data as $country){
  2431. if($country['country'] != "CN"){
  2432. $model = "claude";
  2433. }
  2434. }
  2435. }
  2436. return $model;
  2437. }
  2438. public static function FixedAnswerAndLogData($fixedChat,$question_content){
  2439. $reference = "";
  2440. //返回格式相同的放到一起处理
  2441. if($fixedChat["fixed_faq"] == "Shipments arriving in the next 7 days."
  2442. || $fixedChat["fixed_faq"] == "What is the current status of my active shipments?"){
  2443. $reference = $fixedChat["answer_style"];
  2444. $sql = $fixedChat["fixed_sql"];
  2445. if($_POST['is_demo'] == 't'){
  2446. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2447. }
  2448. $sqlArr = explode(";", $sql);
  2449. $sqlCount = $sqlArr[0];
  2450. //拼接用户权限
  2451. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2452. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2453. error_log("countSql:".$sqlCount);
  2454. $count = common::excuteOneSql($sqlCount);
  2455. //替换总数
  2456. $total = array("total" =>$count);
  2457. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2458. $sqlDetail = $sqlArr[1];
  2459. //拼接用户权限
  2460. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2461. error_log("detail:".$sqlDetail);
  2462. $data = common::excuteListSql($sqlDetail);
  2463. if($fixedChat["fixed_faq"] == "Shipments arriving in the next 7 days."){
  2464. foreach($data as $key =>$d){
  2465. $serial_no = common::deCode($d['serial_no'], 'E');
  2466. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2467. $data[$key]['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2468. }
  2469. }
  2470. if($fixedChat["fixed_faq"] == "What is the current status of my active shipments?"){
  2471. $refer_data =array();
  2472. foreach($data as $key =>$d){
  2473. $temp = array();
  2474. $temp['h_bol'] = $d['h_bol'];
  2475. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  2476. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  2477. $temp['description'] = $d['description'];
  2478. $temp['time'] = common::dealDateTime($d['act_date'],$d['act_time'],$d['timezone'],"m/d/Y");
  2479. $temp['locations'] = $d['locations'];
  2480. $temp['cargo_type'] = $d['cargo_type'];
  2481. $serial_no = common::deCode($d['serial_no'], 'E');
  2482. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2483. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2484. $refer_data[] = $temp;
  2485. }
  2486. $data = $refer_data;
  2487. }
  2488. $reference = utils::replacementsFixedMultilineForFixed($data,$reference,$fixedChat['table_format_tr']);
  2489. $total = array("Download_Complete" =>"");
  2490. if ($count > 10){
  2491. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2492. $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.';
  2493. $total = array("Download_Complete" =>$download_complete);
  2494. }
  2495. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2496. }
  2497. if($fixedChat["fixed_faq"] == "Show shipments delayed in the last 30 days."){
  2498. $reference = $fixedChat["answer_style"];
  2499. $sql = $fixedChat["fixed_sql"];
  2500. if($_POST['is_demo'] == 't'){
  2501. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2502. }
  2503. $sqlArr = explode(";", $sql);
  2504. $sqlCount = $sqlArr[0];
  2505. //拼接用户权限
  2506. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2507. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2508. error_log("countSql:".$sqlCount);
  2509. $count = common::excuteOneSql($sqlCount);
  2510. //替换总数
  2511. $total = array("total" =>$count);
  2512. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2513. $sqlDetail = $sqlArr[1];
  2514. //拼接用户权限
  2515. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2516. error_log("detail:".$sqlDetail);
  2517. $data = common::excuteListSql($sqlDetail);
  2518. $refer_data =array();
  2519. foreach($data as $key =>$d){
  2520. $temp = array();
  2521. $temp['h_bol'] = $d['h_bol'];
  2522. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  2523. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  2524. $temp['log_type'] = $d['log_type'];
  2525. $temp['planned_time'] = common::dealDateTime($d['event_old_date'],$d['event_old_time'],'',"m/d/Y");
  2526. $temp['actual_time'] = common::dealDateTime($d['event_date'],$d['event_time'],'',"m/d/Y");
  2527. $temp['duration'] = $d['duration'] <= 0 ? '< 1 Days' : $d['duration'].' Days';
  2528. $serial_no = common::deCode($d['serial_no'], 'E');
  2529. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2530. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2531. $refer_data[] = $temp;
  2532. }
  2533. $reference = utils::replacementsFixedMultilineForFixed($refer_data,$reference,$fixedChat['table_format_tr']);
  2534. $total = array("Download_Complete" =>"");
  2535. if ($count > 10){
  2536. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2537. $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.';
  2538. $total = array("Download_Complete" =>$download_complete);
  2539. }
  2540. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2541. }
  2542. if($fixedChat["fixed_faq"] == "List shipments with milestone updates in the last 7 days."){
  2543. $reference = $fixedChat["answer_style"];
  2544. $sql = $fixedChat["fixed_sql"];
  2545. if($_POST['is_demo'] == 't'){
  2546. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2547. }
  2548. $sqlArr = explode(";", $sql);
  2549. $sqlCount = $sqlArr[0];
  2550. //拼接用户权限
  2551. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2552. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2553. error_log("countSql:".$sqlCount);
  2554. $count = common::excuteOneSql($sqlCount);
  2555. //替换总数
  2556. $total = array("total" =>$count);
  2557. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2558. $sqlDetail = $sqlArr[1];
  2559. //拼接用户权限
  2560. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2561. error_log("detail:".$sqlDetail);
  2562. $data = common::excuteListSql($sqlDetail);
  2563. $refer_data =array();
  2564. foreach($data as $key =>$d){
  2565. $temp = array();
  2566. $temp['h_bol'] = $d['h_bol'];
  2567. $temp['description'] = $d['description'];
  2568. $temp['update_date'] = common::dealDateTime($d['update_date'],"",$d['timezone'],"m/d/Y H:i:s");
  2569. $temp['locations'] = $d['locations'];
  2570. $serial_no = common::deCode($d['serial_no'], 'E');
  2571. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2572. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2573. $refer_data[] = $temp;
  2574. }
  2575. $reference = utils::replacementsFixedMultilineForFixed($refer_data,$reference,$fixedChat['table_format_tr']);
  2576. //Timeline View
  2577. $sqlview = $sqlArr[2];
  2578. //拼接用户权限
  2579. $sqlview = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlview);
  2580. error_log($sqlview);
  2581. $dateGroups = common::excuteListSql($sqlview);
  2582. $timeline_view = "";
  2583. if(!empty($dateGroups)){
  2584. $timeline_view = "## Timeline View: \n";
  2585. }
  2586. foreach($dateGroups as $key => $tv_count){
  2587. $timeline_view.="- ".$tv_count['update_date_format'].": ".$tv_count['total_count']." shipments reached milestones \n";
  2588. }
  2589. $total = array("Timeline View" =>$timeline_view);
  2590. $reference = utils::replacementsFixed($total,$reference,array("Timeline View"));
  2591. $total = array("Download_Complete" =>"");
  2592. if ($count > 10){
  2593. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2594. $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.';
  2595. $total = array("Download_Complete" =>$download_complete);
  2596. }
  2597. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2598. error_log($reference);
  2599. }
  2600. if($fixedChat["fixed_faq"] == "Show me the full history of my container."){
  2601. $reference = $fixedChat["answer_style"];
  2602. $sql = $fixedChat["fixed_sql"];
  2603. if($_POST['is_demo'] == 't'){
  2604. $question_content = 'DRYU9375994';
  2605. }
  2606. $sqlArr = explode(";", $sql);
  2607. $sqlOne = $sqlArr[0];
  2608. //拼接用户权限
  2609. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2610. $sqlOne = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlOne);
  2611. $sqlOne = str_replace('<{ctnr}>', strtolower($question_content), $sqlOne);
  2612. error_log($sqlOne);
  2613. $data = common::excuteListSql($sqlOne);
  2614. if(empty($data)){
  2615. return "No valid Container number detected. Please try clicking on other FAQ questions or input your own question. Thank you.";
  2616. }
  2617. //如果数据为空,用这个fileds配置的 把模板里值逐个替换为空
  2618. $fileds = array("ctnr","size","h_bol","carrier","vessel","voyage","grs_kgs","ams_commodity","seal_no",
  2619. "place_of_receipt_exp","place_of_delivery_exp","last_status_315_code","last_status_city","last_status_315_date");
  2620. //Container Information替换
  2621. $reference = utils::replacementsFixed($data[0],$reference,$fileds);
  2622. //Related Shipments替换,如果有的话
  2623. if (!empty($data[0]['cleaned_ctnrs'])){
  2624. $related_Shipments = "## Related Shipments \n";
  2625. $related_Shipments .= "- **Other Containers on same Bill of Lading**: ".$data[0]['cleaned_ctnrs'];
  2626. $rsdata = array("Related Shipments" =>$related_Shipments);
  2627. $reference = utils::replacementsFixed($rsdata,$reference,[]);
  2628. }else{
  2629. $rsdata = array("Related Shipments" =>"");
  2630. $reference = utils::replacementsFixed($rsdata,$reference,[]);
  2631. }
  2632. //Complete Container Status
  2633. //根据第一个sql 查出来的serial_no,和 container_no.
  2634. $complete_container_status = "";
  2635. if (!empty($data)) {
  2636. $sqltwo = $sqlArr[1];
  2637. $sqltwo = str_replace('<{serial_no}>', $data[0]['serial_no'], $sqltwo);
  2638. $sqltwo = str_replace('<{container_no}>', $data[0]['ctnr'], $sqltwo);
  2639. $csdata = common::excuteListSql($sqltwo);
  2640. foreach($csdata as $csd){
  2641. $complete_container_status .= "- **".$csd['eventdate']." ".$csd['eventtime']."** ".$csd['description']." | ".$csd['uncity']." \n";
  2642. }
  2643. }
  2644. $rsdata = array("complete_container_status" =>$complete_container_status);
  2645. $reference = utils::replacementsFixed($rsdata,$reference,[]);
  2646. }
  2647. if($fixedChat["fixed_faq"] == "Show me the full history of my shipment."){
  2648. $reference = $fixedChat["answer_style"];
  2649. $sql = $fixedChat["fixed_sql"];
  2650. if($_POST['is_demo'] == 't'){
  2651. $question_content = 'XSTSNA003195';
  2652. }
  2653. $sqlArr = explode(";", $sql);
  2654. $sqlOne = $sqlArr[0];
  2655. //拼接用户权限
  2656. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2657. $sqlOne = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlOne);
  2658. $sqlOne = str_replace('<h_bol>', strtolower($question_content), $sqlOne);
  2659. error_log($sqlOne);
  2660. $data = common::excuteListSql($sqlOne);
  2661. if(empty($data)){
  2662. return "No valid Shipment number detected. Please try clicking on other FAQ questions or input your own question. Thank you.";
  2663. }
  2664. //如果数据为空,用这个fileds配置的 把模板里值逐个替换为空
  2665. $fileds = array("h_bol","carrier_booking","po_no","service","incoterms","shipper_city","consignee_city","etd","eta",
  2666. "shipper","consignee","notify_party","origin_agent","destination_agent","carrier");
  2667. //Container Information替换
  2668. $reference = utils::replacementsFixed($data[0],$reference,$fileds);
  2669. $ref_data = array();
  2670. $serial_no = common::deCode($data[0]['serial_no'], 'E');
  2671. $httpUrl = SERVER_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$data[0]['order_from'];
  2672. $ref_data['Track Shipment'] = '<a href="'.$httpUrl.'" target="_blank">Track Shipment</a>';
  2673. $reference = utils::replacementsFixed($ref_data,$reference,$fileds);
  2674. //Complete Container Status
  2675. //根据第一个sql 查出来的serial_no,和 container_no.
  2676. $complete_container_status = "";
  2677. if (!empty($data)) {
  2678. $sqltwo = $sqlArr[1];
  2679. $sqltwo = str_replace('<{serial_no}>', $data[0]['serial_no'], $sqltwo);
  2680. $csdata = common::excuteListSql($sqltwo);
  2681. foreach($csdata as $csd){
  2682. $complete_container_status .= "- **".$csd['eventdate']." ".$csd['eventtime']."** ".$csd['description']." | ".$csd['uncity']." \n";
  2683. }
  2684. }
  2685. $rsdata = array("complete_container_status" =>$complete_container_status);
  2686. $reference = utils::replacementsFixed($rsdata,$reference,[]);
  2687. }
  2688. if($fixedChat["fixed_faq"] == "List shipments with container status updates in the last 7 days."){
  2689. $reference = $fixedChat["answer_style"];
  2690. $sql = $fixedChat["fixed_sql"];
  2691. if($_POST['is_demo'] == 't'){
  2692. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2693. }
  2694. $sqlArr = explode(";", $sql);
  2695. $sqlCount = $sqlArr[0];
  2696. //拼接用户权限
  2697. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2698. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2699. error_log("countSql:".$sqlCount);
  2700. $count = common::excuteOneSql($sqlCount);
  2701. //替换总数
  2702. $total = array("total" =>$count);
  2703. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2704. $sqlDetail = $sqlArr[1];
  2705. //拼接用户权限
  2706. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2707. error_log("detail:".$sqlDetail);
  2708. $data = common::excuteListSql($sqlDetail);
  2709. $refer_data =array();
  2710. foreach($data as $key =>$d){
  2711. $temp = array();
  2712. $temp['container_no'] = $d['container_no'];
  2713. $temp['description'] = $d['description'];
  2714. $temp['time'] = common::dealDateTime($d['eventdate'],$d['eventtime'],$d['timezone'],"m/d/Y");
  2715. $temp['uncity'] = $d['uncity'];
  2716. $serial_no = common::deCode($d['serial_no'], 'E');
  2717. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2718. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2719. $refer_data[] = $temp;
  2720. }
  2721. $reference = utils::replacementsFixedMultilineForFixed($refer_data,$reference,$fixedChat['table_format_tr']);
  2722. //Timeline View
  2723. $sqlview = $sqlArr[2];
  2724. //拼接用户权限
  2725. $sqlview = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlview);
  2726. error_log("viewSql:".$sqlview);
  2727. $dateGroups = common::excuteListSql($sqlview);
  2728. $timeline_view = "";
  2729. if(!empty($dateGroups)){
  2730. $timeline_view = "## Timeline View: \n";
  2731. }
  2732. foreach($dateGroups as $key => $tv_count){
  2733. $timeline_view.="- ".$tv_count['_insert_date'].": ".$tv_count['total_count']." containers have been updated \n";
  2734. }
  2735. $total = array("Timeline View" =>$timeline_view);
  2736. $reference = utils::replacementsFixed($total,$reference,array("Timeline View"));
  2737. $total = array("Download_Complete" =>"");
  2738. if ($count > 10){
  2739. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2740. $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.';
  2741. $total = array("Download_Complete" =>$download_complete);
  2742. }
  2743. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2744. }
  2745. if($fixedChat["fixed_faq"] == "Today's shipments summary."){
  2746. $reference = $fixedChat["answer_style"];
  2747. $sql = $fixedChat["fixed_sql"];
  2748. if($_POST['is_demo'] == 't'){
  2749. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2750. }
  2751. $sqlArr = explode(";", $sql);
  2752. $sqlCount = $sqlArr[0];
  2753. //拼接用户权限
  2754. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2755. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2756. error_log("countSql:".$sqlCount);
  2757. $count = common::excuteOneSql($sqlCount);
  2758. //替换总数
  2759. $total = array("total" =>$count);
  2760. $reference = utils::replacementsFixed($total,$reference,array("total"));
  2761. $sqlDetail = $sqlArr[1];
  2762. //拼接用户权限
  2763. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2764. error_log("detail:".$sqlDetail);
  2765. $data = common::excuteListSql($sqlDetail);
  2766. $refer_data =array();
  2767. foreach($data as $key =>$d){
  2768. $temp = array();
  2769. $temp['h_bol'] = $d['h_bol'];
  2770. $temp['transport_mode'] = $d['transport_mode'];
  2771. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  2772. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  2773. $temp['action_type'] = $d['action_type'];
  2774. $temp['time'] = common::dealDateTime($d['act_date'],$d['act_time'],$d['timezone'],"m/d/Y");
  2775. $temp['locations'] = $d['locations'];
  2776. $serial_no = common::deCode($d['serial_no'], 'E');
  2777. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2778. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2779. $refer_data[] = $temp;
  2780. }
  2781. $reference = utils::replacementsFixedMultilineForFixed($refer_data,$reference,$fixedChat['table_format_tr']);
  2782. //替换开头日期
  2783. $d1_day = empty($data) ? "" : $data[0]['_update_date'];
  2784. $dateData = array("date" => $d1_day);
  2785. $reference = utils::replacementsFixed($dateData,$reference,[]);
  2786. //dep arr del total
  2787. $sqlview = $sqlArr[2];
  2788. //拼接用户权限
  2789. $sqlview = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlview);
  2790. error_log("depArrDelSql:".$sqlview);
  2791. $dateGroups = common::excuteListSql($sqlview);
  2792. $total = array("dep" =>$dateGroups[0]['dep'],"arr" => $dateGroups[0]['arr'],"del" => $dateGroups[0]['del']);
  2793. $reference = utils::replacementsFixed($total,$reference,[]);
  2794. $total = array("Download_Complete" =>"");
  2795. if ($count > 10){
  2796. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2797. $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.';
  2798. $total = array("Download_Complete" =>$download_complete);
  2799. }
  2800. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2801. }
  2802. if($fixedChat["fixed_faq"] == "Show me the current location of my shipment."){
  2803. $reference = $fixedChat["answer_style"];
  2804. $sql = $fixedChat["fixed_sql"];
  2805. if($_POST['is_demo'] == 't'){
  2806. $question_content = 'DRYU9375994';
  2807. }
  2808. $sqlArr = explode(";", $sql);
  2809. $sqlOne = $sqlArr[0];
  2810. //拼接用户权限
  2811. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2812. $sqlOne = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlOne);
  2813. $sqlOne = str_replace('<{ctnr}>', strtolower($question_content), $sqlOne);
  2814. error_log($sqlOne);
  2815. $data = common::excuteListSql($sqlOne);
  2816. if(empty($data)){
  2817. return "No valid Container/BOL number detected. Please try clicking on other FAQ questions or input your own question. Thank you.";
  2818. }
  2819. //如果数据为空,用这个fileds配置的 把模板里值逐个替换为空
  2820. $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");
  2821. $ref_data = array();
  2822. if(!empty($data)){
  2823. $ref_data = $data[0];
  2824. $ref_data['question_content'] = $question_content;
  2825. $serial_no = common::deCode($data[0]['serial_no'], 'E');
  2826. $httpUrl = SERVER_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$data[0]['order_from'];
  2827. $ref_data['Shipment Detail Page Link'] = '<a href="'.$httpUrl.'" target="_blank">Shipment Detail Page Link</a>';
  2828. }
  2829. $reference = utils::replacementsFixed($ref_data,$reference,$fileds);
  2830. }
  2831. if($fixedChat["fixed_faq"] == "Sort my active shipments by earliest arrival date."){
  2832. $reference = $fixedChat["answer_style"];
  2833. $sql = $fixedChat["fixed_sql"];
  2834. if($_POST['is_demo'] == 't'){
  2835. $sql = utils::getDmoeSqlForAi($fixedChat["fixed_faq"]);
  2836. }
  2837. $sqlArr = explode(";", $sql);
  2838. $sqlCount = $sqlArr[0];
  2839. //拼接用户权限
  2840. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2841. $sqlCount = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlCount);
  2842. error_log("countSql:".$sqlCount);
  2843. $count = common::excuteOneSql($sqlCount);
  2844. $sqlDetail = $sqlArr[1];
  2845. //拼接用户权限
  2846. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  2847. $sqlDetail = str_replace('<{ExtendHand_KLN}>', $sqlWhere, $sqlDetail);
  2848. error_log("detail:".$sqlDetail);
  2849. $data = common::excuteListSql($sqlDetail);
  2850. $refer_data =array();
  2851. foreach($data as $key =>$d){
  2852. $temp = array();
  2853. $temp['eta'] = $d['eta'];
  2854. $temp['h_bol'] = $d['h_bol'];
  2855. $temp['transport_mode'] = $d['transport_mode'];
  2856. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  2857. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  2858. $temp['day_to_arr'] = $d['day_to_arr'];
  2859. $serial_no = common::deCode($d['serial_no'], 'E');
  2860. $httpUrl = SERVER_Vue_PAHT."tracking/detail?a=".$serial_no."&_schemas=".$d["order_from"];
  2861. $temp['action'] = '<a href="'.$httpUrl.'" target="_blank">Details</a> <a href="'.SERVER_Vue_PAHT.'SystemSettings" target="_blank">Notify</a>';
  2862. $refer_data[] = $temp;
  2863. }
  2864. $data = $refer_data;
  2865. $reference = utils::replacementsFixedMultilineForFixed($data,$fixedChat['answer_style'],$fixedChat['table_format_tr']);
  2866. $total = array("Download_Complete" =>"");
  2867. if ($count > 10){
  2868. $httpUrl = SERVER_PAHT."main_new_version.php?action=robot_chat&operate=download&faq=". common::deCode($fixedChat["fixed_faq"]);
  2869. $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.';
  2870. $total = array("Download_Complete" =>$download_complete);
  2871. }
  2872. $reference = utils::replacementsFixed($total,$reference,array("Download_Complete"));
  2873. }
  2874. if($fixedChat["fixed_faq"] == "Set up automatic notifications for shipment updates."
  2875. || $fixedChat["fixed_faq"] == "How can I view the detailed shipping route of my package?" ){
  2876. $reference = $fixedChat["answer_style"];
  2877. }
  2878. error_log($reference);
  2879. return $reference;
  2880. }
  2881. public static function dealDateTime($date,$time,$zone,$format){
  2882. if(empty($date)){
  2883. return "";
  2884. }
  2885. //处理掉多余空格
  2886. if(!empty($time)){
  2887. $time_str = " ".$time;
  2888. } else {
  2889. $time_str = "";
  2890. }
  2891. if(!empty($date) && !empty($zone)){
  2892. $utc = common::getUTCOffsetFormatted($zone);
  2893. return date($format, strtotime($date)).$time_str." UTC".$utc;
  2894. }
  2895. return date($format, strtotime($date)).$time_str;
  2896. }
  2897. public static function getUTCOffsetFormatted($timezone) {
  2898. $timezone = new DateTimeZone($timezone);
  2899. $now = new DateTime('now', $timezone);
  2900. $offset = $timezone->getOffset($now);
  2901. $hours = floor($offset / 3600 * 10) / 10;
  2902. if( $hours > 0 ){
  2903. $hours = "+".$hours;
  2904. }
  2905. return $hours;
  2906. }
  2907. /**
  2908. * 获取固定问题的查询sql
  2909. */
  2910. public static function getFaqSql($faq){
  2911. $sqlObj = common::excuteObjectSql("select fixed_sql from public.kln_robot_chat_fixed where fixed_faq = '$faq'");
  2912. $fixed_sql = $sqlObj['fixed_sql'];
  2913. $sqlDetail = '';
  2914. $sqlArr = explode(";", $fixed_sql);
  2915. if(count($sqlArr) > 1){
  2916. $sqlDetail = $sqlArr[1];
  2917. $search = 'limit 10';
  2918. $sqlDetail = str_ireplace($search, '', $sqlDetail);
  2919. }
  2920. return $sqlDetail;
  2921. }
  2922. /**
  2923. * 获取固定问题列
  2924. */
  2925. public static function getFaqColumnSql($faq){
  2926. //返回格式相同的放到一起处理
  2927. if($faq == "Shipments arriving in the next 7 days."){
  2928. // | HBL/HAWB No. | Origin | Destination | Latest Milestone | ETA | Cargo Type | Actions |
  2929. // |--------------|------------------|------------------|------------------|-----------|---------------|------------------|
  2930. // | {{h_bol}} | {{place_of_receipt_exp}} | {{place_of_delivery_exp}} | {{description}} | {{eta}} | {{cargo_type}} | {{action}} |
  2931. $columns = array();
  2932. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2933. $columns[] = array("display_name" => "Origin","database_column_name"=>"place_of_receipt_exp");
  2934. $columns[] = array("display_name" => "Destination","database_column_name"=>"place_of_delivery_exp");
  2935. $columns[] = array("display_name" => "Latest Milestone","database_column_name"=>"description");
  2936. $columns[] = array("display_name" => "ETA","database_column_name"=>"eta");
  2937. $columns[] = array("display_name" => "Cargo Type","database_column_name"=>"cargo_type");
  2938. }
  2939. if($faq == "Show shipments delayed in the last 30 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" => "Delayed Type","database_column_name"=>"log_type");
  2948. $columns[] = array("display_name" => "Planned Date","database_column_name"=>"planned_time");
  2949. $columns[] = array("display_name" => "Actual/Revised Date","database_column_name"=>"actual_time");
  2950. $columns[] = array("display_name" => "Delay Duration","database_column_name"=>"duration");
  2951. }
  2952. if($faq == "List shipments with milestone updates in the last 7 days."){
  2953. // | HBL/HAWB No. | Latest Milestone | Time | Location | Actions |
  2954. // |--------------|----------------------------|------------------------------|---------------------------|------------------|
  2955. // | {{h_bol}} | {{description}} | {{update_date}} | {{locations}} | {{action}} |
  2956. $columns = array();
  2957. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2958. $columns[] = array("display_name" => "Latest Milestone","database_column_name"=>"description");
  2959. $columns[] = array("display_name" => "Time","database_column_name"=>"update_date");
  2960. $columns[] = array("display_name" => "Location","database_column_name"=>"locations");
  2961. }
  2962. if($faq == "What is the current status of my active shipments?"){
  2963. // | HBL/HAWB No. | Origin | Destination | Latest Milestone | Time | Location | Cargo Type | Actions |
  2964. // |--------------|------------------|------------------|----------------------------|------------------------------|---------------------------|---------------|------------------|
  2965. // | {{h_bol}} | {{place_of_receipt_exp}} | {{place_of_delivery_exp}} | {{description}} | {{time}} | {{locations}} | {{cargo_type}} | {{action}} |
  2966. $columns = array();
  2967. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2968. $columns[] = array("display_name" => "Origin","database_column_name"=>"place_of_receipt_exp");
  2969. $columns[] = array("display_name" => "Destination","database_column_name"=>"place_of_delivery_exp");
  2970. $columns[] = array("display_name" => "Latest Milestone","database_column_name"=>"description");
  2971. $columns[] = array("display_name" => "Time","database_column_name"=>"time");
  2972. $columns[] = array("display_name" => "Location","database_column_name"=>"locations");
  2973. $columns[] = array("display_name" => "Cargo Type","database_column_name"=>"cargo_type");
  2974. }
  2975. if($faq == "List shipments with container status updates in the last 7 days."){
  2976. // | Container No. | Container Status | Time | Location | Actions |
  2977. // |---------------|----------------------------|------------------------------|---------------------------|------------------|
  2978. // | {{container_no}} | {{description}} | {{time}} | {{uncity}} | {{action}} |
  2979. $columns = array();
  2980. $columns[] = array("display_name" => "Container No.","database_column_name"=>"container_no");
  2981. $columns[] = array("display_name" => "Container Status","database_column_name"=>"description");
  2982. $columns[] = array("display_name" => "Time","database_column_name"=>"time");
  2983. $columns[] = array("display_name" => "Location","database_column_name"=>"uncity");
  2984. }
  2985. if($faq == "Today's shipments summary."){
  2986. // | HBL/HAWB No. | Mode | Origin | Destination | Action Type | Action Time | Action Location | Actions |
  2987. // |--------------|------|------------------|------------------|-------------|-------------------------|-----------------|------------------|
  2988. // | {{h_bol}} | {{transport_mode}} | {{place_of_receipt_exp}} | {{place_of_delivery_exp}} | {{action_type}} | {{time}} | {{locations}} | {{action}} |
  2989. $columns = array();
  2990. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  2991. $columns[] = array("display_name" => "Mode","database_column_name"=>"transport_mode");
  2992. $columns[] = array("display_name" => "Origin","database_column_name"=>"place_of_receipt_exp");
  2993. $columns[] = array("display_name" => "Destination","database_column_name"=>"place_of_delivery_exp");
  2994. $columns[] = array("display_name" => "Action Type","database_column_name"=>"action_type");
  2995. $columns[] = array("display_name" => "Action Time","database_column_name"=>"time");
  2996. $columns[] = array("display_name" => "Action Location","database_column_name"=>"locations");
  2997. }
  2998. if($faq == "Sort my active shipments by earliest arrival date."){
  2999. // | ETA | HBOL/HAWB No. | Mode | Origin | Destination | Days to Arrival | Actions |
  3000. // |--------|---------------|-------|------------------|------------------|-----------------|------------------|
  3001. // | {{eta}} | {{h_bol}} | {{transport_mode}} | {{place_of_receipt_exp}} | {{place_of_delivery_exp}} | {{day_to_arr}} | {{action}} |
  3002. $columns = array();
  3003. $columns[] = array("display_name" => "ETA","database_column_name"=>"eta");
  3004. $columns[] = array("display_name" => "HBL/HAWB No.","database_column_name"=>"h_bol");
  3005. $columns[] = array("display_name" => "Mode","database_column_name"=>"transport_mode");
  3006. $columns[] = array("display_name" => "Origin","database_column_name"=>"place_of_receipt_exp");
  3007. $columns[] = array("display_name" => "Destination","database_column_name"=>"place_of_delivery_exp");
  3008. $columns[] = array("display_name" => "Days to Arrival","database_column_name"=>"day_to_arr");
  3009. }
  3010. return $columns;
  3011. }
  3012. /**
  3013. * 处理数据问题
  3014. */
  3015. public static function dealDataWithFaq($faq,$data){
  3016. $refer_data = array();
  3017. //返回格式相同的放到一起处理
  3018. if($faq == "Shipments arriving in the next 7 days."){
  3019. $refer_data = $data;
  3020. }
  3021. if($faq == "Show shipments delayed in the last 30 days."){
  3022. foreach($data as $key =>$d){
  3023. $temp = array();
  3024. $temp['h_bol'] = $d['h_bol'];
  3025. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  3026. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  3027. $temp['log_type'] = $d['log_type'];
  3028. $temp['planned_time'] = common::dealDateTime($d['event_old_date'],$d['event_old_time'],'',"m/d/Y");
  3029. $temp['actual_time'] = common::dealDateTime($d['event_date'],$d['event_time'],'',"m/d/Y");
  3030. $temp['duration'] = $d['duration'] <= 0 ? '< 1 Days' : $d['duration'].' Days';
  3031. $refer_data[] = $temp;
  3032. }
  3033. }
  3034. if($faq == "List shipments with milestone updates in the last 7 days."){
  3035. foreach($data as $key =>$d){
  3036. $temp = array();
  3037. $temp['h_bol'] = $d['h_bol'];
  3038. $temp['description'] = $d['description'];
  3039. $temp['update_date'] = common::dealDateTime($d['update_date'],"",$d['timezone'],"m/d/Y H:i:s");
  3040. $temp['locations'] = $d['locations'];
  3041. $refer_data[] = $temp;
  3042. }
  3043. }
  3044. if($faq == "What is the current status of my active shipments?"){
  3045. foreach($data as $key => $d){
  3046. $temp = array();
  3047. $temp['h_bol'] = $d['h_bol'];
  3048. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  3049. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  3050. $temp['description'] = $d['description'];
  3051. $temp['time'] = common::dealDateTime($d['act_date'],$d['act_time'],$d['timezone'],"m/d/Y");
  3052. $temp['locations'] = $d['locations'];
  3053. $temp['cargo_type'] = $d['cargo_type'];
  3054. $refer_data[] = $temp;
  3055. }
  3056. }
  3057. if($faq == "List shipments with container status updates in the last 7 days."){
  3058. foreach($data as $key =>$d){
  3059. $temp = array();
  3060. $temp['container_no'] = $d['container_no'];
  3061. $temp['description'] = $d['description'];
  3062. $temp['time'] = common::dealDateTime($d['eventdate'],$d['eventtime'],$d['timezone'],"m/d/Y");
  3063. $temp['uncity'] = $d['uncity'];
  3064. $refer_data[] = $temp;
  3065. }
  3066. }
  3067. if($faq == "Today's shipments summary."){
  3068. foreach($data as $key =>$d){
  3069. $temp = array();
  3070. $temp['h_bol'] = $d['h_bol'];
  3071. $temp['transport_mode'] = $d['transport_mode'];
  3072. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  3073. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  3074. $temp['action_type'] = $d['action_type'];
  3075. $temp['time'] = common::dealDateTime($d['act_date'],$d['act_time'],$d['timezone'],"m/d/Y");
  3076. $temp['locations'] = $d['locations'];
  3077. $refer_data[] = $temp;
  3078. }
  3079. }
  3080. if($faq == "Sort my active shipments by earliest arrival date."){
  3081. foreach($data as $key =>$d){
  3082. $temp = array();
  3083. $temp['eta'] = $d['eta'];
  3084. $temp['h_bol'] = $d['h_bol'];
  3085. $temp['transport_mode'] = $d['transport_mode'];
  3086. $temp['place_of_receipt_exp'] = $d['place_of_receipt_exp'];
  3087. $temp['place_of_delivery_exp'] = $d['place_of_delivery_exp'];
  3088. $temp['day_to_arr'] = $d['day_to_arr'];
  3089. $refer_data[] = $temp;
  3090. }
  3091. }
  3092. return $refer_data;
  3093. }
  3094. public static function destination_delivery_window_radio($radio){
  3095. if($radio == "No_Restrictions"){
  3096. return 1;
  3097. }
  3098. if($radio == "Restrictions_ETD_ATD"){
  3099. return 2;
  3100. }
  3101. if($radio == "Restrictions_ETA_ATA"){
  3102. return 3;
  3103. }
  3104. }
  3105. public static function destination_delivery_recommended($radio){
  3106. if($radio == "No_Recommended"){
  3107. return 1;
  3108. }
  3109. if($radio == "Delivery_ETA_ATA"){
  3110. return 2;
  3111. }
  3112. }
  3113. public static function checkOverlap($post_arr,$name) {
  3114. $errors = "";
  3115. $num = count($post_arr);
  3116. //$_POST['rule_type'];
  3117. for ($i = 0; $i < $num; $i++) {
  3118. for ($j = $i + 1; $j < $num; $j++) {
  3119. $set1 = $post_arr[$i] ?? [];
  3120. $set2 = $post_arr[$j] ?? [];
  3121. $intersection = common::array_intersect_own($set1, $set2,$_POST['rule_type'][$i]);
  3122. $intersectionC = "";
  3123. //这个特殊。如果ports 存在一样的,那检查carrier 是否存在一样的。
  3124. if ($name == "Sea Rule") {
  3125. $setC1 = explode(",",$_POST['carrier'][$i]) ?? [];
  3126. $setC2 = explode(",",$_POST['carrier'][$j]) ?? [];
  3127. $intersectionC = array_intersect($setC1, $setC2);
  3128. if (!empty($intersection) && !empty($intersectionC)) {
  3129. $errors = "$name " . ($i + 1) . " and $name " . ($j + 1) . " have overlapping";
  3130. if (!empty($intersection)) {
  3131. $errors .= " ports: " . implode(', ', $intersection);
  3132. }
  3133. if (!empty($intersectionC)) {
  3134. $errors .= " carrier: " . implode(', ', $intersectionC);
  3135. }
  3136. }
  3137. } else {
  3138. if (!empty($intersection)) {
  3139. $errors = "$name " . ($i + 1) . " and $name " . ($j + 1) . " have overlapping ports: " . implode(', ', $intersection);
  3140. }
  3141. }
  3142. }
  3143. }
  3144. return $errors;
  3145. }
  3146. public static function array_intersect_own($set1, $set2,$rule_type){
  3147. $intersection = array_intersect($set1, $set2);
  3148. if ($rule_type <> '*Default Rule' && ($set1 == 'ALL' || $set2 == 'ALL')){
  3149. $intersection = "ALL";
  3150. }
  3151. return $intersection;
  3152. }
  3153. public static function sendDestinationDeliveryReminder($data,$shipmentsData,$status){
  3154. $html_tr = "";
  3155. foreach($shipmentsData['data'] as $shipment){
  3156. $html_tr .="<tr style=\"color: #ED6D00;\">
  3157. <td align=\"center\" style=\" width: 162px;padding: 10px;word-wrap: break-word; word-break: break-all; white-space: normal;\">".$shipment['h_bol']."</td>
  3158. <td align=\"center\" style=\" width: 162px;padding: 10px;word-wrap: break-word; word-break: break-all; white-space: normal;\">".$shipment['ctnr']."</td>
  3159. <td align=\"center\" style=\" width: 162px;padding: 10px;word-wrap: break-word; word-break: break-all; white-space: normal;\">".$shipment['package_type']."</td>
  3160. <td align=\"center\" style=\" width: 162px;padding: 10px;word-wrap: break-word; word-break: break-all; white-space: normal;\">".$shipment['kgw']."</td>
  3161. </tr>";
  3162. }
  3163. $kln_pic_email = $data['kln_pic'];
  3164. //这票的创建者email
  3165. $customer_email = common::excuteOneSql("select email from public.ra_online_user where user_login = '".$data['create_by']."'");
  3166. if ($status == "Reject" || $status == "Cancel") {
  3167. $log = common::excuteObjectSql("select *,
  3168. TO_CHAR(created_time, 'Mon-DD-YYYY') as _created_time
  3169. from public.kln_destination_delivery_operation_log
  3170. where serial_no = '".$data['serial_no']."' order by id desc limit 1");
  3171. }
  3172. $links = "";
  3173. if ($status == "Pending Approval" || $status == "Modify") {
  3174. $links = '<a href="https://online-beta.kln.com/" style="color: #ED6D00; font-size: 14px;">https://online-beta.kln.com/</a>';
  3175. }
  3176. if ($status == "Approve") {
  3177. $links = '<a href="https://online-beta.kln.com/" style="color: #ED6D00; font-size: 14px;">https://online-beta.kln.com/</a>';
  3178. }
  3179. //邮件模板填充字段准备
  3180. $address = json_decode($data["delivery_address_detail"],true);
  3181. $tplData = array("customer_email"=>$customer_email,
  3182. "customer_name"=>$data['create_by'],
  3183. "delivery_mode"=>$data['delivery_mode'],
  3184. "delivery_date"=>$data['_delivery_date'],
  3185. "location_name"=>empty($address['contact_person']) ? "" : $address['contact_person'].":".$address['contact_number'],
  3186. "address_1"=>$address['address_1'],
  3187. "contact"=>"",
  3188. "kln_pic_email"=>$kln_pic_email,
  3189. "booking_no" =>$data['booking_no'],
  3190. "status" =>$status,
  3191. "action_time" =>$log['_created_time'],
  3192. "created_time" =>$data['_created_time'],
  3193. "update_time" =>$data['_update_time'],
  3194. "action_by" =>$log['create_by'],
  3195. "action_reason" =>"",
  3196. "action_comments" =>$log['notes'],
  3197. "link" =>$links,
  3198. "html_tr" =>$html_tr);
  3199. $contents = common::excuteObjectSql("select subject, ra_content as content from ra_online_email_tpl where ra_type = 'Delivery_".$status."'");
  3200. //检查type长度
  3201. $report_type = "delivery_email";
  3202. $report_type = strlen($report_type) > 20 ? substr($report_type, 0, 20) : $report_type;
  3203. $subject = common::check_input($contents['subject']);
  3204. $email_from = "US.KApex.Online@kerryapex.com";
  3205. $to_email = $customer_email;
  3206. $cc_email = $kln_pic_email;
  3207. error_log($contents['content']);
  3208. // 动态构建替换数组(格式:[key] => value)
  3209. $replacements = [];
  3210. foreach ($tplData as $key => $value) {
  3211. $replacements["{{$key}}"] = $value;
  3212. $replacements["{{{$key}}}"] = $value;
  3213. }
  3214. $content = strtr($contents['content'], $replacements);
  3215. $content = common::check_input($content);
  3216. error_log($content);
  3217. $sql = "INSERT INTO email_record(type, title, from_email, to_email, content, insert_date, cc_email, attachment_path)
  3218. VALUES ('" . $report_type . "', '" . $subject . "', '" . $email_from . "', '".$to_email . "', '" . $content . "', now(), '" . $cc_email . "', '');";
  3219. if(empty($contents) || empty($to_email)){
  3220. return "";
  3221. }
  3222. return $sql;
  3223. }
  3224. public static function deliveryStatusConvert($status){
  3225. if ($status == 'Approve'){
  3226. return 'Approved';
  3227. }
  3228. if ($status == 'Reject'){
  3229. return 'Rejected';
  3230. }
  3231. if ($status == 'Cancel'){
  3232. return 'Cancelled';
  3233. }
  3234. return $status;
  3235. }
  3236. public static function customizeParsing ($rawString){
  3237. // 您提供的字符串
  3238. // $rawString = '{ "can_query": false, "query_type": "", "reason": "用户询问是否有其他联系邮箱,因为support@kln.com邮箱返回无法送达。这个问题无法通过数据表查询得到答案,因为表中不包含KLN公司的联系邮箱信息。", "sql": "", "reference": "", "response": "I understand that you\'re having trouble with the email address support@kln.com returning as undeliverable. For customer support inquiries, please use our official customer service email: customer.service@kln.com or alternatively, you can contact our global service desk at global.service@kln.com.
  3239. // You can also reach us through our customer portal at https://www.kln.com/contact-us or call our customer service hotline at +852 2796 6666.
  3240. // We apologize for any inconvenience and are happy to assist you with your logistics needs." }';
  3241. // 要提取的键
  3242. $keysToExtract = ['can_query', 'sql', 'reference', 'response'];
  3243. // 存储结果的数组
  3244. $extractedValues = [];
  3245. foreach ($keysToExtract as $key) {
  3246. $fullKey = '"' . $key . '"'; // 构建完整的键,如 "can_query"
  3247. $keyPos = strpos($rawString, $fullKey);
  3248. if ($keyPos === false) {
  3249. $extractedValues[$key] = null; // 键未找到
  3250. continue;
  3251. }
  3252. // 找到键后,定位冒号 :
  3253. $colonPos = strpos($rawString, ':', $keyPos + strlen($fullKey));
  3254. if ($colonPos === false) {
  3255. $extractedValues[$key] = null; // 冒号未找到
  3256. continue;
  3257. }
  3258. // 跳过冒号和可能的空白,定位值的开始
  3259. $valueStart = $colonPos + 1;
  3260. while ($valueStart < strlen($rawString) && ctype_space($rawString[$valueStart])) {
  3261. $valueStart++;
  3262. }
  3263. if ($valueStart >= strlen($rawString)) {
  3264. $extractedValues[$key] = null; // 值开始位置越界
  3265. continue;
  3266. }
  3267. $value = '';
  3268. $char = $rawString[$valueStart];
  3269. // 情况1: 值以双引号开头 (字符串)
  3270. if ($char === '"') {
  3271. // 从 valueStart+1 开始寻找结束的双引号,需要处理转义
  3272. $pos = $valueStart + 1;
  3273. $strValue = '';
  3274. $escaped = false;
  3275. while ($pos < strlen($rawString)) {
  3276. $currentChar = $rawString[$pos];
  3277. if ($escaped) {
  3278. // 处理转义字符,简单处理常见情况
  3279. switch ($currentChar) {
  3280. case 'n': $strValue .= "\n"; break;
  3281. case 't': $strValue .= "\t"; break;
  3282. case 'r': $strValue .= "\r"; break;
  3283. case '"': $strValue .= '"'; break;
  3284. case '\\': $strValue .= '\\'; break;
  3285. default: $strValue .= $currentChar; break; // 其他转义,原样保留?
  3286. }
  3287. $escaped = false;
  3288. } else {
  3289. if ($currentChar === '\\') {
  3290. $escaped = true;
  3291. } elseif ($currentChar === '"') {
  3292. // 找到了未转义的结束引号
  3293. break;
  3294. } else {
  3295. $strValue .= $currentChar;
  3296. }
  3297. }
  3298. $pos++;
  3299. }
  3300. // 如果找到了结束引号,$strValue 就是解码后的字符串
  3301. // 如果没找到(pos >= strlen),说明字符串没闭合,这里按找到的处理
  3302. $value = trim($strValue);
  3303. }
  3304. // 情况2: 值不是以双引号开头 (false, true, null, "", 数字等)
  3305. else {
  3306. // 寻找值的结束位置:遇到逗号,、右花括号}、右括号] 或空白序列(如果后面是分隔符)
  3307. $pos = $valueStart;
  3308. $literalValue = '';
  3309. while ($pos < strlen($rawString)) {
  3310. $currentChar = $rawString[$pos];
  3311. // 检查是否到了值的边界
  3312. if ($currentChar === ',' || $currentChar === '}' || $currentChar === ']') {
  3313. break; // 遇到分隔符,值结束
  3314. }
  3315. // 如果遇到空白,检查后面的字符是否是分隔符或空白,如果是,则值可能结束
  3316. if (ctype_space($currentChar)) {
  3317. // 查看下一个非空白字符
  3318. $nextPos = $pos + 1;
  3319. while ($nextPos < strlen($rawString) && ctype_space($rawString[$nextPos])) {
  3320. $nextPos++;
  3321. }
  3322. if ($nextPos >= strlen($rawString) || $rawString[$nextPos] === ',' || $rawString[$nextPos] === '}' || $rawString[$nextPos] === ']') {
  3323. break; // 后面是分隔符或结束,当前空白是值的结束
  3324. }
  3325. // 否则,空白是值的一部分?(通常字面量不含内部空白)
  3326. }
  3327. // 对于字面量,我们通常认为它不包含内部空白,所以遇到空白且后面不是分隔符时,可能也该停止?
  3328. // 但为了简单,我们主要依赖 , } ] 分隔符。
  3329. // 追加当前字符
  3330. $literalValue .= $currentChar;
  3331. $pos++;
  3332. }
  3333. // $literalValue 现在包含从 valueStart 到分隔符前的所有字符
  3334. // 但可能包含尾部空白,trim 一下
  3335. $value = trim($literalValue);
  3336. // 特别处理空字符串字面量 ""
  3337. // 如果原始字符串在 valueStart 位置是 ",但我们上面的 else 分支没进,所以不会到这里
  3338. // 如果原始是 "", 它会被上面的 else 分支捕获为字符串 '""',但我们希望它的值是空字符串 ''
  3339. // 所以需要检查 $value 是否等于 '""'
  3340. if ($value === '""') {
  3341. $value = '';
  3342. }
  3343. // 注意:在您的例子中,"sql": "" 和 "reference": "" 在 JSON 中是空字符串,但在 else 分支会被识别为 '""'
  3344. // 我们在这里统一处理。
  3345. }
  3346. $extractedValues[$key] = $value;
  3347. }
  3348. return $extractedValues;
  3349. }
  3350. public static function secondaryReplacement($brokenJson){
  3351. // 用 \n 替换实际换行符 '/"\w+"\s*:\s*"\K[^"]*(?=")/s' 这种如果你字段名不是简单的 \w+(比如有 -、中文等),可以用:
  3352. $fixedJson = preg_replace_callback(
  3353. '/"\s*:\s*"\K[^"]*(?=")/s',
  3354. function ($matches) {
  3355. $text =$matches[0];
  3356. return str_replace(["\r\n", "\n", "\r"], "\\n", $text);
  3357. //return str_replace("\n", "\\n", $matches[0])
  3358. //return str_replace(["\r\n", "\n", "\r"], "\\n", $text);
  3359. },
  3360. $brokenJson
  3361. );
  3362. return $fixedJson;
  3363. }
  3364. /**
  3365. * 客户和 内部员工在不同status下。运行的操作限制
  3366. */
  3367. public static function checkedActionLegal($serial_no,$operate){
  3368. $is_employee = _isApexLogin();
  3369. $status = common::excuteOneSql("select status from public.kln_destination_delivery where serial_no = '$serial_no'");
  3370. $legal = false;
  3371. if ($status == 'Pending Approval'){
  3372. if ($is_employee){
  3373. //Pending Approval 状态下 内部 能审核,拒绝,和看详细
  3374. if ($operate == "review" && ($_POST['status'] == "Approve" || $_POST['status'] == "Reject")){
  3375. $legal = true;
  3376. }
  3377. if ($operate == "view_detail"){
  3378. $legal = true;
  3379. }
  3380. } else {
  3381. //Pending Approval 状态下 客户的 能取消,看详细,和编辑
  3382. if ($operate == "review" && $_POST['status'] == "Cancel"){
  3383. $legal = true;
  3384. }
  3385. if ($operate == "view_detail"){
  3386. $legal = true;
  3387. }
  3388. if ($operate == "add"){
  3389. $legal = true;
  3390. }
  3391. }
  3392. } else if ($status == 'Approve'){
  3393. if ($is_employee){
  3394. //Approve 下 内部的能看详细
  3395. if ($operate == "view_detail"){
  3396. $legal = true;
  3397. }
  3398. } else {
  3399. //Approve 下 客户的 能发邮件留言,能看详细
  3400. if ($operate == "email_message_board"){
  3401. $legal = true;
  3402. }
  3403. if ($operate == "view_detail"){
  3404. $legal = true;
  3405. }
  3406. }
  3407. } else if ($status == 'Reject'){
  3408. if ($is_employee){
  3409. //Reject 下 员工 看详细
  3410. if ($operate == "view_detail"){
  3411. $legal = true;
  3412. }
  3413. } else {
  3414. //Reject 下 客户 能编辑 看详细
  3415. if ($operate == "add"){
  3416. $legal = true;
  3417. }
  3418. if ($operate == "view_detail"){
  3419. $legal = true;
  3420. }
  3421. }
  3422. } else if ($status == 'Cancel'){
  3423. //不分账户类型,只能看详细
  3424. if ($operate == "view_detail"){
  3425. $legal = true;
  3426. }
  3427. }
  3428. //固定
  3429. //$legal = true;
  3430. if(!$legal){
  3431. $data = array("msg" =>"Illegal access");
  3432. common::echo_json_encode(200,$data);
  3433. exit();
  3434. }
  3435. }
  3436. public static function saveDAddressTempTable($delivery_serial_no,$consignee_id){
  3437. //deliver address is new
  3438. $addressSql = "";
  3439. $_sync_key_add = "";
  3440. $address_1 = $_POST['address_1'];
  3441. foreach($address_1 as $key => $_address_1){
  3442. $_address_1 = common::check_input($_address_1);
  3443. $_address_2 = common::check_input($_POST['address_2'][$key]);
  3444. $_address_3 = common::check_input($_POST['address_3'][$key]);
  3445. $_address_4 = common::check_input($_POST['address_4'][$key]);
  3446. $_country = common::check_input($_POST['country'][$key]);
  3447. $_city = common::check_input($_POST['city'][$key]);
  3448. $_postal_code = common::check_input($_POST['postal_code'][$key]);
  3449. $_contact_person = common::check_input($_POST['contact_person'][$key]);
  3450. $_contact_number = common::check_input($_POST['contact_number'][$key]);
  3451. $_contact_id = common::check_input($_POST['contact_id'][$key]);
  3452. $_sync_key = common::check_input($_POST['sync_key'][$key]);
  3453. $_from_station = common::check_input($_POST['from_station'][$key]);
  3454. $_contact_type = common::check_input($_POST['contact_type'][$key]);
  3455. $_create_user = common::check_input($_POST['create_user'][$key]);
  3456. $uniqueAC =array();
  3457. if ($_contact_type == "Add"){
  3458. foreach($consignee_id as $ck => $_consignee_id){
  3459. $_add_create_user = "Online_D_Address";
  3460. if(is_array($_consignee_id,$uniqueAC)){
  3461. continue;
  3462. }
  3463. $_sync_key = common::uuid();
  3464. $_from_station = "";
  3465. $addressSql .= "INSERT INTO public.contacts_address_online(
  3466. delivery_serial_no,action,
  3467. addr_type,contact_id, addr1, addr2,addr3, addr4,
  3468. ctry_code, city_code, postal_code,
  3469. create_user, create_date, modify_user, modify_date,
  3470. is_sync_country, sync_key, from_station,contact_person,contact_number)
  3471. VALUES ('$delivery_serial_no','$_contact_type',
  3472. 'D','$_consignee_id','$_address_1','$_address_2','$_address_3','$_address_4',
  3473. '$_country','$_city','$_postal_code',
  3474. '$_add_create_user',now(),'$_add_create_user',now(),
  3475. true,'$_sync_key','$_from_station','$_contact_person','$_contact_number');";
  3476. $_sync_key_add = $_sync_key;
  3477. }
  3478. } else {
  3479. if(!empty($_sync_key)){
  3480. $_add_create_user = "Online_D_Address";
  3481. if($_contact_type == "Unedit"){
  3482. $_add_create_user = $_create_user;
  3483. }
  3484. $exist = common::excuteObjectSql("select sync_key,action from public.contacts_address_online where sync_key = '$_sync_key' and delivery_serial_no = '$delivery_serial_no'");
  3485. if(empty($exist)){
  3486. $addressSql .= "INSERT INTO public.contacts_address_online(
  3487. delivery_serial_no,action,
  3488. addr_type,contact_id, addr1, addr2,addr3, addr4,
  3489. ctry_code, city_code, postal_code,
  3490. create_user, create_date, modify_user, modify_date,
  3491. is_sync_country, sync_key, from_station,contact_person,contact_number)
  3492. VALUES ('$delivery_serial_no','$_contact_type',
  3493. 'D','$_contact_id','$_address_1','$_address_2','$_address_3','$_address_4',
  3494. '$_country','$_city','$_postal_code',
  3495. '$_add_create_user',now(),'$_add_create_user',now(),
  3496. true,'$_sync_key','$_from_station','$_contact_person','$_contact_number');";
  3497. } else {
  3498. if ($_contact_type == "Delete" && $exist['action'] == "Add"){
  3499. //代表未审核新加的,这次提交为删除
  3500. $addressSql .= "delete from public.contacts_address_online where sync_key = '$_sync_key' and delivery_serial_no = '$delivery_serial_no';";
  3501. }
  3502. // elseif ($_contact_type == "Delete" && ($exist['action'] == "Modify" || $exist['action'] == "Unedit")){
  3503. // //代表未审核编辑的,这次提交为删除,修改action固定为Detele
  3504. // $addressSql .="UPDATE public.contacts_address_online
  3505. // SET addr1='$_address_1', addr2='$_address_2', addr3='$_address_3', addr4='$_address_4',
  3506. // ctry_code='$_country', city_code='$_city', postal_code='$_postal_code',
  3507. // modify_user='$_add_create_user', modify_date=now(),
  3508. // contact_person='$_contact_person', contact_number='$_contact_number',
  3509. // action='Delete'
  3510. // WHERE sync_key = '$_sync_key' and delivery_serial_no = '$delivery_serial_no';";
  3511. // }
  3512. else {
  3513. //Modify Unedit :如果是用户完全新加的,这里不做action的修改,保留记录的Add
  3514. $temp_action = $_contact_type;
  3515. if ($exist['action'] == "Add"){
  3516. $temp_action = "Add";
  3517. }
  3518. $addressSql .="UPDATE public.contacts_address_online
  3519. SET addr1='$_address_1', addr2='$_address_2', addr3='$_address_3', addr4='$_address_4',
  3520. ctry_code='$_country', city_code='$_city', postal_code='$_postal_code',
  3521. modify_user='$_add_create_user', modify_date=now(),
  3522. contact_person='$_contact_person', contact_number='$_contact_number',
  3523. action='$temp_action'
  3524. WHERE sync_key = '$_sync_key' and delivery_serial_no = '$delivery_serial_no';";
  3525. }
  3526. }
  3527. }
  3528. }
  3529. }
  3530. common::excuteUpdateSql($addressSql);
  3531. return $_sync_key_add;
  3532. }
  3533. public static function returnDAddressRecord($address_country,$onine_address){
  3534. //deliver address is new
  3535. $addressSql = "";
  3536. $address_country = json_decode($address_country,true);
  3537. foreach($onine_address as $key => $_onine_address){
  3538. $_address_1 = common::check_input($_onine_address['addr1']);
  3539. $_address_2 = common::check_input($_onine_address['addr2']);
  3540. $_address_3 = common::check_input($_onine_address['addr3']);
  3541. $_address_4 = common::check_input($_onine_address['addr4']);
  3542. $_country = common::check_input($_onine_address['ctry_code']);
  3543. $_city = common::check_input($_onine_address['city_code']);
  3544. $_postal_code = common::check_input($_onine_address['postal_code']);
  3545. $_contact_person = common::check_input($_onine_address['contact_person']);
  3546. $_contact_number = common::check_input($_onine_address['contact_number']);
  3547. $_contact_id = common::check_input($_onine_address['contact_id']);
  3548. $_sync_key = common::check_input($_onine_address['sync_key']);
  3549. $_from_station = common::check_input($_onine_address['from_station']);
  3550. $_contact_type = common::check_input($_onine_address['action']);
  3551. //适应前端逻辑,如果遇到Unedit 代表该地址未变动,移除变动记录里
  3552. if ($_contact_type == "Unedit"){
  3553. continue;
  3554. }
  3555. foreach($address_country as $ck => $_country){
  3556. //如果需要新加的时候 用户固定名称,用作标记 //contact_person,contact_number '$_contact_person','$_contact_number'
  3557. $_add_create_user = "Online_D_Address";
  3558. if ($_contact_type == "Add"){
  3559. $sync_key = common::uuid();
  3560. $from_station = "Online_".strtoupper($_country);
  3561. $addressSql .= "INSERT INTO public.contacts_address(
  3562. addr_type,contact_id, addr1, addr2,addr3, addr4,
  3563. ctry_code, city_code, postal_code,
  3564. create_user, create_date, modify_user, modify_date,
  3565. is_sync_country, sync_key, from_station)
  3566. VALUES ('D','$_contact_id','$_address_1','$_address_2','$_address_3','$_address_4',
  3567. '$_country','$_city','$_postal_code',
  3568. '$_add_create_user',now(),'$_add_create_user',now(),
  3569. true,'$sync_key','$from_station');";
  3570. }
  3571. if ($_contact_type == "Modify"){
  3572. //代表在一个国家内的编辑 //contact_person='$_contact_person', contact_number='$_contact_number'
  3573. $from_station_country = "";
  3574. if (strpos($_from_station, "Online_") === 0) { // 确保字符串以 Online_ 开头
  3575. $from_station_country = substr($_from_station, strlen("Online_"));
  3576. }
  3577. if($from_station_country == $_country){
  3578. $addressSql .= "UPDATE public.contacts_address
  3579. SET addr1='$_address_1', addr2='$_address_2',
  3580. ctry_code='$_country', city_code='$_city', postal_code='$_postal_code',
  3581. modify_user='"._getLoginName()."', modify_date=now()
  3582. WHERE sync_key = '$_sync_key';";
  3583. } else {
  3584. $sync_key = common::uuid();
  3585. $from_station = "Online_".strtoupper($_country);
  3586. $addressSql .= "INSERT INTO public.contacts_address(
  3587. addr_type,contact_id, addr1, addr2,addr3, addr4,
  3588. ctry_code, city_code, postal_code,
  3589. create_user, create_date, modify_user, modify_date,
  3590. is_sync_country, sync_key, from_station)
  3591. VALUES ('D','$_contact_id','$_address_1','$_address_2','$_address_3','$_address_4',
  3592. '$_country','$_city','$_postal_code',
  3593. '$_add_create_user',now(),'$_add_create_user',now(),
  3594. true,'$sync_key','$from_station');";
  3595. }
  3596. }
  3597. if ($_contact_type == "Delete"){
  3598. $from_station_country = "";
  3599. if (strpos($_from_station, "Online_") === 0) { // 确保字符串以 Online_ 开头
  3600. $from_station_country = substr($_from_station, strlen("Online_"));
  3601. }
  3602. if($from_station_country == $_country){
  3603. $addressSql .= "DELETE FROM public.contacts_address WHERE sync_key = '$_sync_key';";
  3604. }
  3605. }
  3606. }
  3607. }
  3608. return $addressSql;
  3609. }
  3610. public static function returnDAddress($_sync_key_add=""){
  3611. //deliver address is new
  3612. $$delivery_address = "";
  3613. $address_1 = $_POST['address_1'];
  3614. foreach($address_1 as $key => $_address_1){
  3615. $_address_1 = $_address_1;
  3616. $_address_2 = $_POST['address_2'][$key];
  3617. $_address_3 = $_POST['address_3'][$key];
  3618. $_address_4 = $_POST['address_4'][$key];
  3619. $_country = $_POST['country'][$key];
  3620. $_city = $_POST['city'][$key];
  3621. $_postal_code = $_POST['postal_code'][$key];
  3622. $_contact_person = $_POST['contact_person'][$key];
  3623. $_contact_number = $_POST['contact_number'][$key];
  3624. $_contact_id = $_POST['contact_id'][$key];
  3625. $_sync_key = $_POST['sync_key'][$key];
  3626. $_from_station = $_POST['from_station'][$key];
  3627. $_contact_type = $_POST['contact_type'][$key];
  3628. if($_contact_type == "Add"){
  3629. //add 这么生成的唯一key
  3630. $_sync_key = $_sync_key_add;
  3631. }
  3632. if ($_contact_type <> "Delete"){
  3633. $delivery_address = array("address_1"=>$_address_1,
  3634. "address_2"=>$_address_2,
  3635. "address_3"=>$_address_3,
  3636. "address_4"=>$_address_4,
  3637. "country"=>$_country,
  3638. "city"=>$_city,
  3639. "postal_code"=>$_postal_code,
  3640. "contact_person"=>$_contact_person,
  3641. "contact_number"=>$_contact_number,
  3642. "contact_id"=>$_contact_id,
  3643. "sync_key"=>$_sync_key,
  3644. "from_station"=>$_from_station,
  3645. "contact_type"=>"Unedit");
  3646. }
  3647. }
  3648. return $delivery_address;
  3649. }
  3650. }
  3651. ?>