common.class.php 209 KB

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