common.class.php 200 KB

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