common.class.php 208 KB

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