common.class.php 258 KB

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