common.class.php 260 KB

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