common.class.php 184 KB

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