common.class.php 257 KB

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