common.class.php 260 KB

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