common.class.php 252 KB

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