Pārlūkot izejas kodu

service code commit

ShuanghongS 1 gadu atpakaļ
vecāks
revīzija
dc144816f0

+ 174 - 0
service/ajax.class.php

@@ -0,0 +1,174 @@
+<?php
+
+if (!defined('IN_ONLINE')) {
+    exit('Access Denied');
+}
+
+/**
+ * Description of auto
+ *
+ * @author Administrator
+ */
+class ajax {
+
+    private static $_ajax;
+
+    public static function getInstance() {
+        if (!self::$_ajax) {
+            $c = __CLASS__;
+            self::$_ajax = new $c;
+        }
+        return self::$_ajax;
+    }
+
+    public function run() {
+        $time = time() - $_SESSION["LAST_OPERATE_TIME"];
+        if ($time > $_SESSION['SESSION_TIMEOUT']) {
+            exit(json_encode("session_time_out"));
+        } else {
+            $_SESSION["LAST_OPERATE_TIME"] = time();
+        }
+        $operate = utils::_get('operate');
+        $operate = strtolower($operate);
+        switch ($operate) {
+            case 'save_setting_display':
+                $this->save_setting_display();
+                break;
+            case 'autody':
+                return json_encode($this->autody());
+                break;
+            case 'autoport':
+                return json_encode($this->autoPort());
+                break;        
+            default :
+                break;
+        }
+    }
+
+    public function save_setting_display() {
+        $ids = $_POST['ids'];
+        if(!empty($ids)){
+            column::getInstance()->saveSettingDisplay(implode(",", $_POST['ids']),"", $_POST['model_name']);
+            $data = array(
+                'msg' => 'success'
+            );
+            common::echo_json_encode(200,$data);
+        }else{
+            $data = array(
+                'msg' => 'data error'
+            );
+            common::echo_json_encode(500,$data);
+        }
+    }
+
+    public function autoPort() {
+        $cp = common::check_input($_POST ['cp']); //current_page
+        $ps = common::check_input($_POST ['ps']); //ps
+        if (empty($ps))
+            $ps = 20;
+
+        $term = $_POST['term'];
+        $term = trim($term);
+        $_curr_schemas = $_POST['model'];
+        if (empty($_curr_schemas)) {
+            $_curr_schemas = $_SESSION['ONLINE_USER']['main_schemas'];
+            if (empty($_curr_schemas)) {
+                $_curr_schemas = "public";
+            }
+        }
+
+        $rc = $_POST ['rc'];
+        if ($rc == - 1) {
+            $sql = "SELECT count(1) from $_curr_schemas.ports where (isoname ilike '" . common::check_input($term) . "%' 
+                or uncity ilike '" . common::check_input($term) . "%' or uncode ilike '" . common::check_input($term) . "%')";
+            $rc = common::excuteOneSql($sql);
+        }
+        $tp = ceil($rc / $ps);
+        if ($rc > 0) {
+            $sql = "SELECT isoname as country, uncity as city,uncode from $_curr_schemas.ports where (isoname ilike '" . common::check_input($term) . "%' 
+                    or uncity ilike '" . common::check_input($term) . "%' or uncode ilike '" . common::check_input($term) . "%')";
+            $sql .= " order by code limit " . $ps . " offset " . ($cp - 1) * $ps;
+
+            $rs = common::excuteListSql($sql);
+            //前端要加上id 从1开始
+            foreach($rs as $key => $val){
+                $rs[$key]["id"] = $key +1;
+            }
+
+            $arrTmp = array('searchData' => $rs, 
+                    'rc' => $rc,
+                    'ps' => $ps,
+                    'cp' => $cp,
+                    'tp' => $tp);
+            common::echo_json_encode(200,$arrTmp);
+            exit();
+        }else{
+            $arrTmp = array('searchData' => "nodata");
+            common::echo_json_encode(200, $arrTmp);
+            exit();
+        }
+    }
+
+    public function autody() {
+        $term = $_POST['term'];
+        $type = $_POST['type'];
+        
+        $term = trim($term);
+        if (strtolower($type) == "apex") {
+            $_curr_schemas = $_POST['model'];
+            if (empty($_curr_schemas)) {
+                $_curr_schemas = $_SESSION['ONLINE_USER']['main_schemas'];
+                if (empty($_curr_schemas)) {
+                    $_curr_schemas = "public";
+                }
+            }
+            if ($_curr_schemas == "public") {
+                $sql = "select contact_id as code from ocean.contacts where ('Apex-DST'=any(regexp_split_to_array(contact_type::text, ';'::text))"
+                        . " or 'Apex-AGT'=any(regexp_split_to_array(contact_type::text, ';'::text))) "
+                        . "and active=true and coalesce(hblcode, '')<>'' and  (contact_id ilike '" . common::check_input($term) . "%' or company ilike '" . common::check_input($term) . "%')";
+            } else {
+                $sql = "select contact_id as code from $_curr_schemas.contacts where ('Apex-DST'=any(regexp_split_to_array(contact_type::text, ';'::text))"
+                        . " or 'Apex-AGT'=any(regexp_split_to_array(contact_type::text, ';'::text))) "
+                        . "and active=true and coalesce(hblcode, '')<>'' and  (contact_id ilike '" . common::check_input($term) . "%' or company ilike '" . common::check_input($term) . "%')";
+            }
+            $sql .= " order by contact_id limit 20";
+            $rs = common::excuteListSql($sql);
+        }
+
+        //Shipper 和Consignee  的查询 但是表contact_v ,从ocean和air. 如果不做区分的话,可以上面的apex的Origin Agent/Destination Agent,合并
+        if (strtolower($type) == "contanct") {
+            $sql = "SELECT company as code from contact_v where active = true and (contact_id ilike '" . common::check_input($term) . "%' or company ilike '" . common::check_input($term) . "%')";
+            $sql .= " order by contact_id limit 20";
+            $rs = common::excuteListSql($sql);
+            
+        }
+
+        if (strtolower($type) == "sales") {
+            $_curr_schemas = $_POST['model'];
+            if (empty($_curr_schemas)) {
+                $_curr_schemas = $_SESSION['ONLINE_USER']['main_schemas'];
+                if (empty($_curr_schemas)) {
+                    $_curr_schemas = "public";
+                }
+            }
+            $sql = "SELECT salesopcode as code from $_curr_schemas.employee where salesopcode is not null and salesopcode !='' and (salesopcode ilike '" . common::check_input($term) . "%' or employee_id ilike '" . common::check_input($term) . "%')";
+            $sql .= " order by salesopcode limit 20";
+        }
+
+        if (strtolower($type) == "vessel") {
+            $vessel = $_POST['vessel'];
+            $sql = "SELECT carrier, vessel as code, flag from vessel_infor where vessel ilike '" . common::check_input($vessel) . "%'";
+            $sql .= " order by vessel limit 20";
+        }
+
+        $rs = common::excuteListSql($sql);
+        $array = array();
+        foreach($rs as $v){
+            $array[] = $v['code'];
+        }
+        common::echo_json_encode(200,$array);
+        exit();
+    }
+}
+
+?>

+ 264 - 0
service/column.class.php

@@ -0,0 +1,264 @@
+<?php
+
+if (!defined('IN_ONLINE')) {
+    exit('Access Denied');
+}
+
+class column {
+
+    private static $_column;
+
+    public static function getInstance() {
+        if (!self::$_column) {
+            $c = __CLASS__;
+            self::$_column = new $c;
+        }
+        return self::$_column;
+    }
+
+    public function settingDisplay($model_name, $url, $type = null) {
+        $data = array();
+        //判断是否重置
+        if(!empty($_REQUEST['reset']) && $_REQUEST['reset'] == "yes"){
+            common::excuteUpdateSql("update ra_online_search_display_config_cso set ids = '' 
+                 where lower(login_name)='" . strtolower(_getLoginName()) . "' and lower(model_name) = '" . strtolower($model_name) . "'");
+        }
+        if (empty($type)) {
+            $allData = $this->getDisplayColumnAllReomveDefault($model_name);
+            $groupColumns_all = $this->allGroupColumns($allData);
+
+            //总分组的检索要去掉右边的已经选中的部分
+            $dataLeft = $this->getDisplayColumn($model_name,false);
+            $groupColumns_left = $this->allGroupColumns($dataLeft);
+
+            $setting = $this->getDisplayColumn($model_name);
+            $groupSetting = $this->groupColumnsSetting($setting);
+            
+            $data['GroupColumnsAll'] = $groupColumns_all;
+            $data['GroupColumnsLeft'] = $groupColumns_left;
+            $data['GroupColumnsRight'] = $groupSetting;
+        } 
+        //search目前页面没有
+        //$data['search_setting'] = search::getInstance()->getDisplayColumn($model_name);
+        //$data['search_diff'] = search::getInstance()->getDisplayColumn($model_name, FALSE);
+        $data['model_name'] = $model_name;
+        $data['url'] = $url;
+        common::echo_json_encode(200,$data);
+        exit;
+    }
+
+    //改为从新的配置表和配置信息,与旧的分开
+    public function getDisplayColumn($model_name, $isin = true) {
+        $rs = null;
+        $sql = "select ids from public.ra_online_search_display_config_cso where lower(login_name)='" . strtolower(_getLoginName()) . "' and lower(model_name) = '" . strtolower($model_name) . "'";
+        $rs = common::excuteOneSql($sql);
+        if (empty($rs)) {
+            $sql = "select array_to_string(array(select id from public.ra_online_search_display_cso where active = true and default_display = true and lower(model_name) = '" . strtolower($model_name) . "'";
+            if (_isCustomerLogin())
+                $sql .= " and customer_display = true";
+            $sql .= " order by default_order asc), ',')";
+            $rs = common::excuteOneSql($sql);
+        }
+        if ($isin) {
+            $sql = $this->_getSql($rs);
+            $rss = common::excuteListSql($sql);
+        } else {
+            $sql = "SELECT id, display_name as name, database_column_name, column_width,group_name FROM public.ra_online_search_display_cso WHERE active = true and lower(model_name) = '" . strtolower($model_name) . "' and id not in ($rs)";
+            if (_isCustomerLogin())
+                $sql .= ' and customer_display=true';
+            $rss = common::excuteListSql($sql);
+        }
+        //旧版本去除新加__字段
+        $action = strtolower($_REQUEST['action']);
+        if (Soure == 'TopOcean' &&  empty(common::isNewVersion())
+                && ($action =="ocean_order" || $action == "ocean_booking" || $action == "containers")){
+            $rss = common::removeTopOceanOldVersionSpecialField($rss);
+        }
+        
+        return $rss;
+    }
+
+    public function _getSql($ids) {
+        $ids_arr = explode(',', $ids);
+        $sql = "";
+        foreach ($ids_arr as $value) {
+            if (!empty($value)) {
+                if (empty($sql)) {
+                    $sql .= 'SELECT id, display_name as name,  database_column_name,column_width,group_name FROM public.ra_online_search_display_cso where active=true and id = ' . $value;
+                    if (_isCustomerLogin())
+                        $sql .= ' and CUSTOMER_DISPLAY = true';
+                } else {
+                    $sql .= ' union all SELECT id, display_name as name, database_column_name,column_width,group_name FROM public.ra_online_search_display_cso where active=true and id = ' . $value;
+                    if (_isCustomerLogin())
+                        $sql .= ' and CUSTOMER_DISPLAY = true';
+                }
+            }
+        }
+        return $sql;
+    }
+
+    public function saveSettingDisplay($newid, $search_id, $model_name) {
+        global $db;
+        $login_name = _getLoginName();
+        $db->StartTrans();
+        if ($this->checkUserDisplaySetting($model_name) === TRUE) {
+            $sql = "UPDATE public.ra_online_search_display_config_cso SET ids = '" . common::check_input($newid) . "' WHERE lower(model_name) = '" . common::check_input(strtolower($model_name)) . "' AND lower(login_name) = '" . common::check_input(strtolower($login_name)) . "'";
+        } else {
+            $sql = "INSERT INTO public.ra_online_search_display_config_cso (LOGIN_NAME, MODEL_NAME, ids) VALUES ('" . common::check_input($login_name) . "', '" . common::check_input($model_name) . "', '" . common::check_input($newid) . "')";
+        }
+        //search 部分的数据不做查询
+        //search::getInstance()->saveSettingDisplay($search_id, $model_name);
+        common::excuteUpdateSql($sql);
+        $db->CompleteTrans();
+    }
+
+    /*
+     * check user had setting display
+    */
+    public function checkUserDisplaySetting($model_name) {
+        $login_name = _getLoginName();
+        $sql = "select ids from public.ra_online_search_display_config_cso where lower(login_name)='" . strtolower($login_name) . "' and lower(model_name) = '" . strtolower($model_name) . "'"; //check login_name is setting
+        $rs = common::excuteObjectSql($sql);
+        if (!empty($rs)) {
+            return TRUE;
+        }
+        return FALSE;
+    }
+
+    public function getSearchSql($model_name) {
+        $sql = "";
+        $ss = "SELECT database_column_name, display_name FROM public.ra_online_search_display_cso WHERE lower(model_name) = '" . strtolower($model_name) . "'";
+        if (_isCustomerLogin())
+            $ss .= ' and customer_display=true';
+        error_log($ss);
+        $rss = common::excuteListSql($ss);
+        
+        //旧版本去除新加__字段
+        $action = strtolower($_REQUEST['action']);
+        $rss = common::removeTopOceanOldVersionSpecialField($rss);
+        
+        //不和以前重命名有冲突,改为database_column_name,display 显示由固定配置设置
+        foreach ($rss as $v) {
+            if ($sql == '')
+                $sql .=  $v['database_column_name'];
+            else
+                $sql .= ',' . $v['database_column_name'];
+        }
+        return ' ' . $sql . ' ';
+    }
+
+    public function getDisplayColumnAll($model_name) {
+        $sql = "SELECT id, display_name as name, database_column_name as db,database_column_name, column_width,group_name FROM public.ra_online_search_display_cso WHERE default_display = true and active=true and lower(model_name) = '" . strtolower($model_name) . "'";
+        if (_isCustomerLogin())
+            $sql .= ' and customer_display=true';
+        $sql .= " order by order_by";
+        $rss = common::excuteListSql($sql);
+        return $rss;
+    }
+
+    public function getDisplayColumnAllReomveDefault($model_name) {
+        $sql = "SELECT id, display_name as name, database_column_name as db,database_column_name, column_width,group_name FROM public.ra_online_search_display_cso WHERE  active=true and lower(model_name) = '" . strtolower($model_name) . "'";
+        if (_isCustomerLogin())
+            $sql .= ' and customer_display=true';
+        $sql .= " order by order_by";
+        $rss = common::excuteListSql($sql);
+        return $rss;
+    }
+   
+    public function tableColumns($type,$column){
+        $tableColumns = array();
+        foreach ($column as $key => $rs) {
+            $temp = array();
+            $temp['field'] = $rs['database_column_name'];
+            $temp['title'] = $rs['name'];
+            $spconfig = $this->specialTableConfig($type);
+            if (!empty($spconfig[$rs['database_column_name']]['type'])){
+                $temp['type'] = $spconfig[$rs['database_column_name']]['type'];
+
+            }else{
+                $temp['type'] = "normal";
+            }
+            //formatter
+            if (!empty($spconfig[$rs['database_column_name']]['formatter'])){
+                $temp['formatter'] = $spconfig[$rs['database_column_name']]['formatter'];
+
+            }else{
+                $temp['formatter'] = "";
+            }
+
+            $tableColumns[] = $temp;
+        }
+        return $tableColumns;
+    }
+
+    public function groupColumnsSetting($column){
+        $groupSetting = array();
+        foreach ($column as $key => $rs) {
+            $temp = array();
+            $temp['ids'] = $rs['id'];
+            $temp['field'] = $rs['database_column_name'];
+            $temp['label'] = $rs['name'];
+            $groupSetting[] = $temp;
+        }
+        return $groupSetting;
+    }
+
+    public function specialTableConfig($type){
+        if ($type == "Booking_Search"){
+            return array("booking_no" =>array("type" =>"link"),
+            "h_bol" =>array("type" =>"link"),
+            "mode" =>array("type" =>"mode"),
+            "status" =>array("type" =>"status"),
+            "created_time" =>array("formatter" =>"dateTime"),
+            "confirmation_time" =>array("formatter" =>"dateTime"),
+            "f_etd" =>array("formatter" =>"date"),
+            "f_eta" =>array("formatter" =>"date"));
+        }
+        if ($type == "Ocean_Search"){
+            return array("booking_no" =>array("type" =>"link"),
+            "h_bol" =>array("type" =>"link"),
+            "mode" =>array("type" =>"mode"),
+            "status" =>array("type" =>"status"),
+            "created_time" =>array("formatter" =>"dateTime"),
+            "etd" =>array("formatter" =>"dateTime"),
+            "f_eta" =>array("formatter" =>"date"));
+        }
+    }
+
+    /**
+     * 通用返回setting 分组数据
+     */
+    public function allGroupColumns($allData){
+        $children = array();
+        //预先初始化,空的也要保留
+        $children['All'] = array();
+        $children['Reference No.'] = array();
+        $children['General'] = array();
+        $children['Parties'] = array();
+        $children['Time'] = array();
+        $children['Places'] = array();
+        $children['Transportation'] = array();
+        $children['Others'] = array();
+        foreach ($allData as $key => $data) {
+            //固定ALl的分组
+            if (array_key_exists("All", $children)) {
+                $temp = $children['All'];
+                $temp[] = array("ids"=>$data['id'],"label"=>$data['name'],"field"=>$data['database_column_name']);
+                $children['All'] = $temp;
+            } 
+            if (array_key_exists($data['group_name'], $children)) {
+                $temp = $children[$data['group_name']];
+                $temp[] = array("ids"=>$data['id'],"label"=>$data['name'],"field"=>$data['database_column_name']);
+                $children[$data['group_name']] = $temp;
+            } 
+        }
+
+        $groupColumns  = array();
+        foreach ($children as $k => $ch) {
+            $groupColumns[] = array("name"=>$k,"children" =>$ch);
+        }
+        return $groupColumns;
+    }
+}
+
+?>

+ 1111 - 0
service/login.class.php

@@ -0,0 +1,1111 @@
+<?php
+
+if (!defined('IN_ONLINE')) {
+    exit('Access Denied');
+}
+
+/**
+ * Description of login
+ *
+ * @author Administrator
+ */
+class login {
+
+    private static $_login;
+
+    public static function getInstance() {
+        if (!self::$_login) {
+            $c = __CLASS__;
+            self::$_login = new $c;
+        }
+        return self::$_login;
+    }
+
+    private function getLoginSql($uname) {
+        return "select user_login,(select active from public.employee ee where ee.employee_id=u.employee_id) as employee_id_active, can_visit_vgm,can_add_booking, can_add_tk_status,truck_driver,po_booking,o_final_delivery_u,ipad_view_po,can_view_doc,can_upload_doc,can_add_catalog,can_add_po,packing_list_company,is_only_vgm,contact_id_user,is_demo, ra_password as password,employee_id, contact_id, user_type, last_pwd_change, EXTRACT(DAY from (now() - last_pwd_change)) as last_pwd_change_date, email, user_webtype_id, active, is_online, station, allow_login_remote, can_see_amslog,can_view_eccn, can_see_isflog, can_see_isflog_withaddress, 
+        customer_search_type, customer_destination, can_add_ams, can_add_isf, air_station, air_sales, ocean_station, ocean_sales,ocean_following_sales,ocean_following_sales_or,air_following_sales,air_following_sales_or, trucking_station, ocean_dest_op, can_see_password, can_add_opsales_code, ocean_station_or, ocean_agent_or, ocean_sales_or, ocean_dest_op_or, air_station_or, air_sales_or, trucking_station_or, 
+        can_add_user, can_add_employee, can_add_contact, company_name, ams_email, isf_email, customer_discharge, online_active, is_super, ocean_agent,active, can_send_email, view_file_format as docdownload, container_status, consolidated_cbsa_code, can_add_aci, 
+        air_customers, air_customer_search_type,trucking_customers,trucking_customer_search_type, upload_document, view_file_format, event_type, belong_schemas, main_schemas, error_login_count, EXTRACT(EPOCH FROM (now()-COALESCE(error_login_time, now()))) as second, po_status, view_air_file_format, 
+        special_customer_event, can_edi_vgm, isf_aci_ams_station,login_version,is_kerry_shipment,can_visit_delivery,currency_group from public.ra_online_user u where lower(user_login) = '" . strtolower($uname) . "'";
+    }
+
+    public function do_login() {
+        $login_error_times = common::excuteOneSql("select ra_value from ra_online_config where ra_name='Login_Error_Times'");
+        $lock_user_seconds = common::excuteOneSql("select ra_value from ra_online_config where ra_name='Lock_User_Seconds'");
+        if (!empty($uname) || !empty($password)) {
+
+            
+        } else {
+            $uname = common::check_input($_POST['uname']);
+            $verifcation_code = common::check_input($_POST['verifcation_code']);
+            //首先校验验证码
+            if (strtolower($_SESSION['captcha']) != strtolower($verifcation_code)) {    
+                $data = array(
+                    'msg' => 'verifcation_error',
+                    'data' => ''
+                );
+                common::echo_json_encode(400, $data);
+                exit();
+            }
+
+            $sql = $this->getLoginSql($uname);
+            $rs = common::excuteObjectSql($sql);
+            if (empty($rs['belong_schemas'])) {
+                $rs['belong_schemas'] = "public";
+            }
+            if (empty($rs['main_schemas'])) {
+                $rs['main_schemas'] = "public";
+            }
+
+            if (!empty($rs)) {
+                //验证employee是否active
+                if (!empty($rs["employee_id"]) && $rs["employee_id_active"] != "t") {
+                    if (strtolower(Soure) =='topocean'){
+                        if (strtolower($rs['user_type']) == "employee" && utils::endWith($rs['email'], "cn")) {
+                            $data = "<a href='mailto:lilyyang@topocean.com.cn'>lilyyang@topocean.com.cn</a>";
+                        }else{
+                            $data = "<a href='mailto:winnie@topocean.com'>winnie@topocean.com</a>";
+                        }
+                    }
+                    if (strtolower(Soure) =='apex'){
+                        $data = "<a href='mailto:maria.wang@apexshipping.com.cn'>maria.wang@apexshipping.com.cn</a>";
+                    }
+                    
+                    $data = array(
+                        'msg' => 'no_active',
+                        'login_version' => $rs["login_version"],
+                        'data' => $data
+                    );
+                    common::echo_json_encode(500, $data);
+                    $this->failedLogin($uname, 'Employee not active');
+                    exit();
+                }
+
+                //处理登录状态
+                $userInfo = common::check_input($_COOKIE['userInfo']);
+
+                $noCheckPwd = false;
+
+                if (!empty($userInfo)) {
+                    $userInfoSplit = explode("_", $userInfo);
+                    if ($uname == $userInfoSplit[0]) {
+                        if ($userInfoSplit[1] == md5($rs['password'])) {
+                            $noCheckPwd = true;
+                        }
+                    }
+                }
+            
+                if ($rs['error_login_count'] > $login_error_times && $rs['second'] < $lock_user_seconds) {
+                        $data = array(
+                            'msg' => 'error_times',
+                            'login_version' => $rs["login_version"],
+                            'data' => ceil(($lock_user_seconds - $rs['second']) / 60)
+                        );
+                        common::echo_json_encode(400, $data);
+                        
+                        $this->failedLogin($uname, 'Failed login too times');
+                        exit();
+                }
+                if ($rs['is_online'] != 't') {
+                    if (strtolower($rs['user_type']) != "employee") {
+                        $data =array(
+                            'msg' => 'no_online',
+                            'login_version' => $rs["login_version"],
+                            'data' => ''
+                        );
+                        common::echo_json_encode(500, $data);
+                        $this->failedLogin($uname, 'Online is not active');
+                        exit();
+                    }
+                }
+
+                //if ($rs['decrypt_password'] != $_POST['psw']) {
+				if ($noCheckPwd) {
+
+				}else{
+                    if ($rs['password'] != $_POST['psw']) {    
+                        common::excuteUpdateSql("update public.ra_online_user set error_login_count=error_login_count+1, error_login_time=now() where lower(user_login) = '" . strtolower($uname) . "'");
+                        $data = array(
+                            'msg' => 'password_error',
+                            'login_version' => $rs["login_version"],
+                            'data' => ''
+                        );
+                        common::echo_json_encode(400, $data);
+                        $this->failedLogin($uname, 'Password is wrong');
+                        exit();
+                    }
+				}
+                   
+                if ($rs['online_active'] != 't') {
+                    $data = array(
+                        'msg' => 'no_active',
+                        'login_version' => $rs["login_version"],
+                        'data' => ''
+                    );
+                    common::echo_json_encode(500, $data);
+                    $this->failedLogin($uname, 'Online is not active');
+                    exit();
+                }
+                //check password length
+                $tar = utils::checkPassword($rs['password']);
+                if (!empty($tar)) {
+                    $data = array(
+                        'msg' => $tar,
+                        'login_version' => $rs["login_version"],
+                        'data' => ''
+                    );
+                    common::echo_json_encode(500, $data);
+                    exit();
+                }
+                if (empty($rs['last_pwd_change'])) {
+                    $data = array(
+                        'msg' => 'first_login',
+                        'login_version' => $rs["login_version"],
+                        'data' => ''
+                    );
+                    common::echo_json_encode(500, $data);
+                    exit();
+                }
+                
+
+                //get more infor by employee_id or contact_id
+                $sql = '';
+                $diffdate = $rs['last_pwd_change_date'];
+                $user_type = $rs['user_type'];
+                //if user is customer, check company
+                if (strtolower($user_type) == 'customer') {
+                    $company = $rs['company_name'];
+                } else {
+                    if (!empty($rs['station']))
+                        $company = $rs['station'];
+                }
+                if (strtolower($uname) == 'ra.admin') {
+                    $company = 'Admin';
+                }
+                // get system config
+                $sql = "SELECT lower(ra_name) as ra_name, ra_value from ra_online_config where lower(ra_name) in ('employee_session_timeout', 'customer_session_timeout', 'password_change_alert', 'employee_password_change_cycle', 'customer_password_change_cycle')";
+                $rs1s = common::excuteListSql($sql);
+                foreach ($rs1s as $rs1) {
+                    if ($rs1['ra_name'] == 'employee_session_timeout')
+                        $EMPLOYEE_SESSION_TIMEOUT = $rs1['ra_value'];
+                    if ($rs1['ra_name'] == 'customer_session_timeout')
+                        $CUSTOMER_SESSION_TIMEOUT = $rs1['ra_value'];
+                    if ($rs1['ra_name'] == 'password_change_alert')
+                        $PASSWORD_CHANGE_ALERT = $rs1['ra_value'];
+                    if ($rs1['ra_name'] == 'employee_password_change_cycle')
+                        $EMPLOYEE_PASSWORD_CHANGE_CYCLE = $rs1['ra_value'];
+                    if ($rs1['ra_name'] == 'customer_password_change_cycle')
+                        $CUSTOMER_PASSWORD_CHANGE_CYCLE = $rs1['ra_value'];
+                }
+                $sql="select item_value from config where item='passwordChangePeriod'";
+                $pcp = common::excuteObjectSql($sql);
+                $passwordChangePeriod = json_decode($pcp["item_value"],true);
+
+                if (strtolower($rs['user_type']) == 'employee') {
+                    $PASSWORD_CHANGE_CYCLE = $EMPLOYEE_PASSWORD_CHANGE_CYCLE;
+                    $SESSION_TIMEOUT = $EMPLOYEE_SESSION_TIMEOUT;
+
+                    //如果有新配置,则采用新配置
+                    if (!empty($pcp)) {
+                        $PASSWORD_CHANGE_CYCLE = $passwordChangePeriod["Employee"]["days"];
+                        $PASSWORD_CHANGE_ALERT = $passwordChangePeriod["Employee"]["advanceDays"];
+                    }
+
+                } else {
+                    $PASSWORD_CHANGE_CYCLE = $CUSTOMER_PASSWORD_CHANGE_CYCLE;
+                    $SESSION_TIMEOUT = $CUSTOMER_SESSION_TIMEOUT;
+                    
+                    //如果有新配置,则采用新配置
+                    if (!empty($pcp)) {
+                        $PASSWORD_CHANGE_CYCLE = $passwordChangePeriod["Customer"]["days"];
+                        $PASSWORD_CHANGE_ALERT = $passwordChangePeriod["Customer"]["advanceDays"];
+                    }
+                }
+
+                $loginName = $rs['user_login'];
+                $email = $rs['email'];
+                //Timeout
+                if ($diffdate > $PASSWORD_CHANGE_CYCLE) {
+                    if(empty($email)){
+                        $data = array(
+                            'status' => '0',
+                            'msg' => 'login user email is empty',
+                            'login_version' => $rs["login_version"],
+                            'data' => ''
+                        );
+                        common::echo_json_encode(500, $data);
+                        exit();
+                    }else{
+                        //$this -> passwordExpires($loginName,$email);
+                    }
+                }
+
+                if ($diffdate == $PASSWORD_CHANGE_CYCLE) {// Due today
+                    $login_tmp = array(
+                        'msg' => 'today',
+                        'uname' => $uname,
+                        'login_version' => $rs["login_version"],
+                        'data' => ''
+                    );
+                } elseif ($diffdate >= ($PASSWORD_CHANGE_CYCLE - $PASSWORD_CHANGE_ALERT)) {// Password expires soon, JS Tips
+                    $login_tmp = array(
+                        'msg' => 'last',
+                        'uname' => $uname,
+                        'login_version' => $rs["login_version"],
+                        'data' => $PASSWORD_CHANGE_CYCLE - $diffdate,
+                        'is_only_vgm' => $rs["is_only_vgm"]
+                    );
+                }
+
+                //insert into log table
+                $ip = common::ip();
+                $sql = "insert into public.ra_online_user_login_log (user_name,manufacturer,from_app,ip,date_time, session_id) values ('" . common::check_input($uname) . "', '" . common::check_input($company) . "','Online','$ip',now(), '" . session_id() . "')";
+                if (common::excuteUpdateSql($sql)) {
+                    common::excuteUpdateSql("update public.ra_online_user set Last_Login_Time = now(), error_login_count=0, error_login_time=null where lower(user_login) = '" . strtolower($uname) . "'");
+                    if (isset($login_tmp)) {
+                        common::echo_json_encode(200, $login_tmp);
+                    } else {
+                        $data = array(
+                            'msg' => 'success',
+                            'uname' => $uname,
+                            'login_version' => $rs["login_version"],
+                            'data' => '',
+                            'is_only_vgm' => $rs["is_only_vgm"]
+                        );
+                        common::echo_json_encode(200, $data);
+                    }
+
+                    $online_user = $rs;
+                    $online_user['user_login'] = $uname;
+                    $online_user['company'] = $company;
+                    $online_user['password'] = "";
+                    if (!_isAdmin()) {
+                        if ($rs["is_only_vgm"] == "t") {//VGM用户写死
+                            $sql = "select array_to_string(ARRAY(select url_action from public.ra_online_permission where url_action in ('ocean_order','password','vgm') and menu_id in ('ship','profile') order by order_by asc), ',')";
+                            $rrrs = common::excuteOneSql($sql);
+                        } else {
+                            $sql = "select array_to_string(ARRAY(select p.url_action from public.ra_online_user_permission up left join public.ra_online_user u on up.user_name = u.user_login left join public.ra_online_permission p on up.p_id = p.id where lower(u.user_login) = '" . common::check_input(strtolower($uname)) . "'), ',')";
+                            $rrrs = common::excuteOneSql($sql);
+                            if (strtolower($rs['user_type']) == "employee" && empty($rrrs)) {
+                                $sql = "select array_to_string(ARRAY(select url_action from public.ra_online_permission where is_customer = true order by order_by asc), ',')";
+                                $rrrs = common::excuteOneSql($sql);
+                            }
+                        }
+                        $online_user['permission'] = $rrrs;
+                    }
+
+                    if (!empty($online_user['docdownload']))
+                        $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from ra_online_file_format where lower(serial_no) " . common::getInNotInSql($online_user['docdownload']) . " and active = true group by display_name order by min(id)";
+                    else {
+                        $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from ra_online_file_format where active = true";
+                        if (strtolower($online_user['user_type']) == "customer")
+                            $sql .= " and client_display = true";
+                        $sql .= " group by display_name order by min(id)";
+                    }
+                    $online_user['view_doc_type'] = common::excuteListSql($sql);
+
+                    if (!empty($online_user['view_air_file_format']))
+                        $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from air_file_format where lower(serial_no) " . common::getInNotInSql($online_user['view_air_file_format']) . " and active = true group by display_name order by min(id)";
+                    else {
+                        $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from air_file_format where active = true";
+                        if (strtolower($online_user['user_type']) == "customer")
+                            $sql .= " and client_display = true";
+                        $sql .= " group by display_name order by min(id)";
+                    }
+                    $online_user['view_air_doc_type'] = common::excuteListSql($sql);
+                    //补充aci and ams CustomerLogin station - public 
+                    $ocean_station_temp = $online_user['ocean_station'];
+                    $online_user['session_ocean_station'] = $this->getOriginOrAgent($ocean_station_temp);
+                    
+                    $ocean_agent_temp = $online_user['ocean_agent'];
+                    $online_user['session_ocean_agent'] = $this->getOriginOrAgent($ocean_agent_temp);
+                    
+
+                    $_SESSION['ONLINE_USER'] = $online_user;
+                    $_SESSION['LAST_OPERATE_TIME'] = time();
+                    $_SESSION['SESSION_TIMEOUT'] = $SESSION_TIMEOUT;
+                    
+
+                    //判断是否记录密码  add
+                    if ($_POST['rememberpwd'] === 'true') {
+                        if (!$noCheckPwd) {
+                            $user_info = $uname . "_" . md5($rs['password']);
+
+                            setcookie('userInfo', $user_info, time() + 30 * 24 * 3600, "/");
+                        }
+                    } else {
+                        setcookie('userInfo', '', time() - 1, "/");
+                    }
+
+                    if ($rs['is_super'] == "t") {
+                        $schemas_list = common::excuteListSql("select * from schemas_list");
+                    } else {
+                        $schemas_list = common::excuteListSql("select * from schemas_list where schemas_name=any(regexp_split_to_array('" . $rs['belong_schemas'] . "'::text, ';'::text))");
+                    }
+                    ///if (count($schemas_list) > 1) {
+                    foreach ($schemas_list as $sk => $sv) {
+                        if ($sv['schemas_name'] == "public") {
+                            continue;
+                        }
+                        $ttdd = common::excuteObjectSql("select contact_id_user, employee_id, contact_id, user_type, email, user_webtype_id, active, is_online, station, allow_login_remote, can_see_amslog,can_view_eccn, can_see_isflog, can_see_isflog_withaddress, 
+                        customer_search_type, customer_destination, can_add_ams, can_add_isf, air_station, air_sales, ocean_station, ocean_sales,ocean_following_sales,ocean_following_sales_or,air_following_sales,air_following_sales_or, trucking_station, ocean_dest_op, can_see_password, can_add_opsales_code, ocean_station_or, ocean_agent_or, ocean_sales_or, ocean_dest_op_or, air_station_or, air_sales_or, trucking_station_or, 
+                        can_add_user, can_add_employee, can_add_contact, company_name, ams_email, isf_email, customer_discharge, online_active, is_super, ocean_agent,active, can_send_email, view_file_format as docdownload, container_status, consolidated_cbsa_code, can_add_aci,
+                        air_customers, air_customer_search_type,trucking_customers,trucking_customer_search_type, upload_document, view_file_format, event_type, po_status, view_air_file_format, special_customer_event, can_edi_vgm, isf_aci_ams_station, is_kerry_shipment from " . $sv['schemas_name'] . ".ra_online_user where lower(user_login) = '" . strtolower($uname) . "'");
+                        if (empty($ttdd)) {
+                            unset($schemas_list[$sk]);
+                            continue;
+                        }
+
+                        if (!empty($ttdd['docdownload'])) {
+                            $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from " . $sv['schemas_name'] . ".ra_online_file_format where lower(serial_no) " . common::getInNotInSql($ttdd['docdownload']) . " and active = true group by display_name order by min(id)";
+                        } else {
+                            $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from " . $sv['schemas_name'] . ".ra_online_file_format where active = true";
+                            if (strtolower($ttdd['user_type']) == "customer")
+                                $sql .= " and client_display = true";
+                            $sql .= " group by display_name order by min(id)";
+                        }
+                        $ttdd['view_doc_type'] = common::excuteListSql($sql);
+
+                        if (!empty($ttdd['view_air_file_format'])) {
+                            $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from " . $sv['schemas_name'] . ".air_file_format where lower(serial_no) " . common::getInNotInSql($ttdd['view_air_file_format']) . " and active = true group by display_name order by min(id)";
+                        } else {
+                            $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from " . $sv['schemas_name'] . ".air_file_format where active = true";
+                            if (strtolower($ttdd['user_type']) == "customer")
+                                $sql .= " and client_display = true";
+                            $sql .= " group by display_name order by min(id)";
+                        }
+                        $ttdd['view_air_doc_type'] = common::excuteListSql($sql);
+                        
+                         //补充aci and ams CustomerLogin station - other like sfs
+                        $ocean_station_temp = $ttdd['ocean_station'];
+                        $ttdd['session_ocean_station'] = $this->getOriginOrAgent($ocean_station_temp);
+
+                        $ocean_agent_temp = $ttdd['ocean_agent'];
+                        $ttdd['session_ocean_agent'] = $this->getOriginOrAgent($ocean_agent_temp);
+
+                        $_SESSION[$sv['schemas_name'] . '_ONLINE_USER'] = $ttdd;
+                    }
+                    //}
+                    $_SESSION['schemas_list'] = $schemas_list;
+                    //不再返回登录页面,直接跳转
+                    if (isset($_GET['up'])) {
+                        if($_GET['v'] == 'new'){
+                           header("Location: main_new_version.php?action=main");
+                        }else{
+                           header("Location: main.php?action=main");
+                        }
+                    }
+                    exit();
+                } else {
+                    $data = array(
+                        'msg' => 'database_error',
+                        'login_version' => $rs["login_version"],
+                        'data' => ''
+                    );
+                    common::echo_json_encode(500, $data);
+                    exit();
+                }
+            } else {
+                $data = array(
+                    'msg' => 'no_exist',
+                    'login_version' => $rs["login_version"],
+                    'data' => ''
+                );
+                common::echo_json_encode(500, $data);
+                exit();
+            }
+        }
+    }
+
+    public function check_uname(){
+        $uname = common::check_input($_POST['uname']);
+        $sql = $this->getLoginSql($uname);
+        $rs = common::excuteObjectSql($sql);
+        if (!empty($rs)) {
+            //只是验证用户是否存在,是否激活
+            //验证employee是否active
+            if (!empty($rs["employee_id"]) && $rs["employee_id_active"] != "t") {
+                if (strtolower(Soure) =='topocean'){
+                    if (strtolower($rs['user_type']) == "employee" && utils::endWith($rs['email'], "cn")) {
+                        $data = "<a href='mailto:lilyyang@topocean.com.cn'>lilyyang@topocean.com.cn</a>";
+                    }else{
+                        $data = "<a href='mailto:winnie@topocean.com'>winnie@topocean.com</a>";
+                    }
+                }
+                if (strtolower(Soure) =='apex'){
+                    $data = "<a href='mailto:maria.wang@apexshipping.com.cn'>maria.wang@apexshipping.com.cn</a>";
+                }
+                $data = array(
+                    'msg' => 'no_active',
+                );
+                common::echo_json_encode(200, $data);
+                exit();
+            }
+            
+            if ($rs['is_online'] != 't') {
+                if (strtolower($rs['user_type']) != "employee") {
+                    $data =array(
+                        'msg' => 'no_online',
+                    );
+                    common::echo_json_encode(200, $data);
+                    exit();
+                }
+            }
+            if ($rs['online_active'] != 't') {
+                $data = array(
+                    'msg' => 'no_active',
+                );
+                common::echo_json_encode(200, $data);
+                exit();
+            }
+            //验证成功
+            $data = array(
+                'msg' => 'success',
+            );
+            common::echo_json_encode(200, $data);
+            exit();
+        } else {
+            $data = array(
+                'msg' => 'no_exist',
+            );
+            common::echo_json_encode(200, $data);
+            exit();
+        }
+
+    }
+
+    public function verifcation_code(){
+        // 生成一个4位随机数作为验证码
+        //$random_num = mt_rand(1000, 9999);
+        $random_num = $this->generateCaptcha(6);
+        $_SESSION['captcha'] = $random_num;
+        
+        // 创建一个宽度为80像素、高度为30像素的图片
+        $width = 130;
+        $height = 40;
+        $image = imagecreate($width, $height);
+        
+        // 设置颜色
+        $white = imagecolorallocate($image, 255, 255, 255); // 白色作为背景
+        $black = imagecolorallocate($image, 0, 0, 0); // 黑色作为文字
+        
+        // 填充背景
+        imagefilledrectangle($image, 0, 0, $width, $height, $white);
+        
+        // 在图片上绘制四个字符
+        $font_size = 18;
+        $x = 14;
+        $y = 12;
+        for ($i = 0; $i < 6; $i++) {
+            $char = substr($random_num, $i, 1);
+            imagestring($image, $font_size, $x, $y, $char, $black);
+            $x += $font_size+1;
+        }
+        
+        // 返回Base64编码
+        ob_start();
+        imagepng($image);
+        $image_data = ob_get_clean();
+        // 释放内存
+        imagedestroy($image);
+        $data = array("imagePngBase64" =>base64_encode($image_data));
+        common::echo_json_encode(200, $data);
+        exit();
+    }
+
+    //邮件密码原文
+    public function forgot_password() {
+        $login = common::check_input($_POST['login']);
+        $email = common::check_input($_POST['email']);
+        $verifcation_code = common::check_input($_POST['verifcation_code']);
+        //首先校验验证码
+        if ($_SESSION['captcha'] != $verifcation_code) {    
+            $data = array(
+                'msg' => 'verifcation_error',
+                'data' => ''
+            );
+            common::echo_json_encode(500, $data);
+            exit();
+        }
+        $msg = "";
+        if (!empty($email) || !empty($login)) {
+            $sql_p = "select User_Login, ra_password as password from public.ra_online_user where lower(user_login) = '" . strtolower($login) . "' and lower(email) = '" . strtolower($email) . "'";
+            $rs = common::excuteObjectSql($sql_p);
+            if (!empty($rs)) {
+                $r = utils::sendEmailByPassword($login, $rs['password'], $email);
+                if ($r == 'success') {
+                    $msg = "success";
+                } else {
+                    $msg = $r;
+                }
+            } else {
+                $msg = "Can not find this user with give login id and email, please confirm!";
+            }
+        } else {
+            $msg = "Login Name or Email Required !";
+        }
+
+        $data = array(
+            'msg' => $msg,
+        );
+        common::echo_json_encode(200, $data);
+        exit();
+    }
+
+    public function generateCaptcha($length = 6) {
+        $captcha = '';
+        for ($i = 0; $i < $length; $i++) {
+            // 随机选择字母或数字
+            $char = mt_rand(0, 1) ? rand(0, 9) : chr(rand(ord('A'), ord('Z')));
+            $captcha .= strval($char);
+        }
+        return $captcha;
+    }
+
+    public function do_login_auto() {
+        $uname = common::check_input($_GET['u']);
+        $password = common::check_input($_GET['p']);
+        $login_error_times = common::excuteOneSql("select ra_value from ra_online_config where ra_name='Login_Error_Times'");
+        $lock_user_seconds = common::excuteOneSql("select ra_value from ra_online_config where ra_name='Lock_User_Seconds'");
+        if (!empty($uname) || !empty($password)) {
+           
+        } else {
+            $uname = common::check_input($_POST['uname']);
+            $sql = $this->getLoginSql($uname);
+            $rs = common::excuteObjectSql($sql);
+            if (empty($rs['belong_schemas'])) {
+                $rs['belong_schemas'] = "public";
+            }
+            if (empty($rs['main_schemas'])) {
+                $rs['main_schemas'] = "public";
+            }
+
+            if (!empty($rs)) {
+                //验证employee是否active
+                if (!empty($rs["employee_id"]) && $rs["employee_id_active"] != "t") {
+                    if (strtolower(Soure) =='topocean'){
+                        if (strtolower($rs['user_type']) == "employee" && utils::endWith($rs['email'], "cn")) {
+                            $data = "<a href='mailto:lilyyang@topocean.com.cn'>lilyyang@topocean.com.cn</a>";
+                        }else{
+                            $data = "<a href='mailto:winnie@topocean.com'>winnie@topocean.com</a>";
+                        }
+                    }
+                    if (strtolower(Soure) =='apex'){
+                        $data = "<a href='mailto:maria.wang@apexshipping.com.cn'>maria.wang@apexshipping.com.cn</a>";
+                    }
+                    
+                    $data = array(
+                        'msg' => 'no_active',
+                        'login_version' => $rs["login_version"],
+                        'data' => $data
+                    );
+                    common::echo_json_encode(500, $data);
+                    $this->failedLogin($uname, 'Employee not active');
+                    exit();
+                }
+
+                //add  处理登录状态
+                $userInfo = common::check_input($_COOKIE['userInfo']);
+
+                $noCheckPwd = false;
+
+                if (!empty($userInfo)) {
+                    $userInfoSplit = explode("_", $userInfo);
+                    if ($uname == $userInfoSplit[0]) {
+                        if ($userInfoSplit[1] == md5($rs['password'])) {
+                            $noCheckPwd = true;
+                        }
+                    }
+                }
+                
+                //if (!$noCheckPwd) {
+                    if ($rs['error_login_count'] > $login_error_times && $rs['second'] < $lock_user_seconds) {
+                        $data = array(
+                            'msg' => 'error_times',
+                            'login_version' => $rs["login_version"],
+                            'data' => ceil(($lock_user_seconds - $rs['second']) / 60)
+                        );
+                        common::echo_json_encode(500, $data);
+                        
+                        $this->failedLogin($uname, 'Failed login too times');
+                        exit();
+                    }
+                    if ($rs['is_online'] != 't') {
+                        if (strtolower($rs['user_type']) != "employee") {
+                            $data =array(
+                                'msg' => 'no_online',
+                                'login_version' => $rs["login_version"],
+                                'data' => ''
+                            );
+                            common::echo_json_encode(500, $data);
+                            $this->failedLogin($uname, 'Online is not active');
+                            exit();
+                        }
+                    }
+
+                    //if ($rs['decrypt_password'] != $_POST['psw']) {
+					if ($noCheckPwd) {
+					}else{
+                    if ($rs['password'] != $_POST['psw']) {    
+                        common::excuteUpdateSql("update public.ra_online_user set error_login_count=error_login_count+1, error_login_time=now() where lower(user_login) = '" . strtolower($uname) . "'");
+                        $data = array(
+                            'msg' => 'password_error',
+                            'login_version' => $rs["login_version"],
+                            'data' => ''
+                        );
+                        common::echo_json_encode(500, $data);
+                        $this->failedLogin($uname, 'Password is wrong');
+                        exit();
+                    }
+					}
+                   
+                    if ($rs['online_active'] != 't') {
+                        $data = array(
+                            'msg' => 'no_active',
+                            'login_version' => $rs["login_version"],
+                            'data' => ''
+                        );
+                        common::echo_json_encode(500, $data);
+                        $this->failedLogin($uname, 'Online is not active');
+                        exit();
+                    }
+                    //check password length
+                    $tar = utils::checkPassword($rs['password']);
+                    if (!empty($tar)) {
+                        $data = array(
+                            'msg' => $tar,
+                            'login_version' => $rs["login_version"],
+                            'data' => ''
+                        );
+                        common::echo_json_encode(500, $data);
+                        exit();
+                    }
+                    if (empty($rs['last_pwd_change'])) {
+                        $data = array(
+                            'msg' => 'first_login',
+                            'login_version' => $rs["login_version"],
+                            'data' => ''
+                        );
+                        common::echo_json_encode(500, $data);
+                        exit();
+                    }
+                //}
+
+                //get more infor by employee_id or contact_id
+                $sql = '';
+                $diffdate = $rs['last_pwd_change_date'];
+                $user_type = $rs['user_type'];
+                //if user is customer, check company
+                if (strtolower($user_type) == 'customer') {
+                    $company = $rs['company_name'];
+                } else {
+                    if (!empty($rs['station']))
+                        $company = $rs['station'];
+                }
+                if (strtolower($uname) == 'ra.admin') {
+                    $company = 'Admin';
+                }
+                // get system config
+                $sql = "SELECT lower(ra_name) as ra_name, ra_value from ra_online_config where lower(ra_name) in ('employee_session_timeout', 'customer_session_timeout', 'password_change_alert', 'employee_password_change_cycle', 'customer_password_change_cycle')";
+                $rs1s = common::excuteListSql($sql);
+                foreach ($rs1s as $rs1) {
+                    if ($rs1['ra_name'] == 'employee_session_timeout')
+                        $EMPLOYEE_SESSION_TIMEOUT = $rs1['ra_value'];
+                    if ($rs1['ra_name'] == 'customer_session_timeout')
+                        $CUSTOMER_SESSION_TIMEOUT = $rs1['ra_value'];
+                    if ($rs1['ra_name'] == 'password_change_alert')
+                        $PASSWORD_CHANGE_ALERT = $rs1['ra_value'];
+                    if ($rs1['ra_name'] == 'employee_password_change_cycle')
+                        $EMPLOYEE_PASSWORD_CHANGE_CYCLE = $rs1['ra_value'];
+                    if ($rs1['ra_name'] == 'customer_password_change_cycle')
+                        $CUSTOMER_PASSWORD_CHANGE_CYCLE = $rs1['ra_value'];
+                }
+                $sql="select item_value from config where item='passwordChangePeriod'";
+                $pcp = common::excuteObjectSql($sql);
+                $passwordChangePeriod = json_decode($pcp["item_value"],true);
+
+                if (strtolower($rs['user_type']) == 'employee') {
+                    $PASSWORD_CHANGE_CYCLE = $EMPLOYEE_PASSWORD_CHANGE_CYCLE;
+                    $SESSION_TIMEOUT = $EMPLOYEE_SESSION_TIMEOUT;
+
+                    //如果有新配置,则采用新配置
+                    if (!empty($pcp)) {
+                        $PASSWORD_CHANGE_CYCLE = $passwordChangePeriod["Employee"]["days"];
+                        $PASSWORD_CHANGE_ALERT = $passwordChangePeriod["Employee"]["advanceDays"];
+                    }
+
+                } else {
+                    $PASSWORD_CHANGE_CYCLE = $CUSTOMER_PASSWORD_CHANGE_CYCLE;
+                    $SESSION_TIMEOUT = $CUSTOMER_SESSION_TIMEOUT;
+                    
+                    //如果有新配置,则采用新配置
+                    if (!empty($pcp)) {
+                        $PASSWORD_CHANGE_CYCLE = $passwordChangePeriod["Customer"]["days"];
+                        $PASSWORD_CHANGE_ALERT = $passwordChangePeriod["Customer"]["advanceDays"];
+                    }
+                }
+
+                /* if ($diffdate > $PASSWORD_CHANGE_CYCLE) {// Timeout 
+                    echo json_encode(array(
+                        'msg' => 'password_require_change',
+                        'login_version' => $rs["login_version"],
+                        'data' => ''
+                    ));
+                    $this->failedLogin($uname, 'Required password change');
+                    exit();
+                }*/
+
+                $loginName = $rs['user_login'];
+                $email = $rs['email'];
+                if ($diffdate > $PASSWORD_CHANGE_CYCLE) {// Timeout
+                    if(empty($email)){
+                        $data = array(
+                            'status' => '0',
+                            'msg' => 'login user email is empty',
+                            'login_version' => $rs["login_version"],
+                            'data' => ''
+                        );
+                        common::echo_json_encode(500, $data);
+                        exit();
+                    }else{
+                        //$this -> passwordExpires($loginName,$email);
+                    }
+                }
+
+                if ($diffdate == $PASSWORD_CHANGE_CYCLE) {// Due today
+                    $login_tmp = array(
+                        'msg' => 'today',
+                        'login_version' => $rs["login_version"],
+                        'data' => ''
+                    );
+                } elseif ($diffdate >= ($PASSWORD_CHANGE_CYCLE - $PASSWORD_CHANGE_ALERT)) {// Password expires soon, JS Tips
+                    $login_tmp = array(
+                        'msg' => 'last',
+                        'login_version' => $rs["login_version"],
+                        'data' => $PASSWORD_CHANGE_CYCLE - $diffdate,
+                        'is_only_vgm' => $rs["is_only_vgm"]
+                    );
+                }
+
+                //insert into log table
+                $ip = common::ip();
+                $sql = "insert into public.ra_online_user_login_log (user_name,manufacturer,from_app,ip,date_time, session_id) values ('" . common::check_input($uname) . "', '" . common::check_input($company) . "','Online','$ip',now(), '" . session_id() . "')";
+                if (common::excuteUpdateSql($sql)) {
+                    common::excuteUpdateSql("update public.ra_online_user set Last_Login_Time = now(), error_login_count=0, error_login_time=null where lower(user_login) = '" . strtolower($uname) . "'");
+                    //自动登录。为了方便调用,先注销掉
+                    if (isset($login_tmp)) {
+                        //common::echo_json_encode(500, $login_tmp);
+                    } else {
+                        $data = array(
+                            'msg' => 'success',
+                            'login_version' => $rs["login_version"],
+                            'data' => '',
+                            'is_only_vgm' => $rs["is_only_vgm"]
+                        );
+                        //common::echo_json_encode("200", $data);
+                    }
+
+                    $online_user = $rs;
+                    $online_user['user_login'] = $uname;
+                    $online_user['company'] = $company;
+                    $online_user['password'] = "";
+                    if (!_isAdmin()) {
+                        if ($rs["is_only_vgm"] == "t") {//VGM用户写死
+                            $sql = "select array_to_string(ARRAY(select url_action from public.ra_online_permission where url_action in ('ocean_order','password','vgm') and menu_id in ('ship','profile') order by order_by asc), ',')";
+                            $rrrs = common::excuteOneSql($sql);
+                        } else {
+                            $sql = "select array_to_string(ARRAY(select p.url_action from public.ra_online_user_permission up left join public.ra_online_user u on up.user_name = u.user_login left join public.ra_online_permission p on up.p_id = p.id where lower(u.user_login) = '" . common::check_input(strtolower($uname)) . "'), ',')";
+                            $rrrs = common::excuteOneSql($sql);
+                            if (strtolower($rs['user_type']) == "employee" && empty($rrrs)) {
+                                $sql = "select array_to_string(ARRAY(select url_action from public.ra_online_permission where is_customer = true order by order_by asc), ',')";
+                                $rrrs = common::excuteOneSql($sql);
+                            }
+                        }
+                        $online_user['permission'] = $rrrs;
+                    }
+
+                    if (!empty($online_user['docdownload']))
+                        $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from ra_online_file_format where lower(serial_no) " . common::getInNotInSql($online_user['docdownload']) . " and active = true group by display_name order by min(id)";
+                    else {
+                        $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from ra_online_file_format where active = true";
+                        if (strtolower($online_user['user_type']) == "customer")
+                            $sql .= " and client_display = true";
+                        $sql .= " group by display_name order by min(id)";
+                    }
+                    $online_user['view_doc_type'] = common::excuteListSql($sql);
+
+                    if (!empty($online_user['view_air_file_format']))
+                        $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from air_file_format where lower(serial_no) " . common::getInNotInSql($online_user['view_air_file_format']) . " and active = true group by display_name order by min(id)";
+                    else {
+                        $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from air_file_format where active = true";
+                        if (strtolower($online_user['user_type']) == "customer")
+                            $sql .= " and client_display = true";
+                        $sql .= " group by display_name order by min(id)";
+                    }
+                    $online_user['view_air_doc_type'] = common::excuteListSql($sql);
+                    //补充aci and ams CustomerLogin station - public 
+                    $ocean_station_temp = $online_user['ocean_station'];
+                    $online_user['session_ocean_station'] = $this->getOriginOrAgent($ocean_station_temp);
+                    
+                    $ocean_agent_temp = $online_user['ocean_agent'];
+                    $online_user['session_ocean_agent'] = $this->getOriginOrAgent($ocean_agent_temp);
+                    
+
+                    $_SESSION['ONLINE_USER'] = $online_user;
+                    $_SESSION['LAST_OPERATE_TIME'] = time();
+                    $_SESSION['SESSION_TIMEOUT'] = $SESSION_TIMEOUT;
+                    
+
+                    //判断是否记录密码  add
+                    if ($_POST['rememberpwd'] === 'true') {
+                        if (!$noCheckPwd) {
+                            $user_info = $uname . "_" . md5($rs['password']);
+
+                            setcookie('userInfo', $user_info, time() + 30 * 24 * 3600, "/");
+                        }
+                    } else {
+                        setcookie('userInfo', '', time() - 1, "/");
+                    }
+
+                    if ($rs['is_super'] == "t") {
+                        $schemas_list = common::excuteListSql("select * from schemas_list");
+                    } else {
+                        $schemas_list = common::excuteListSql("select * from schemas_list where schemas_name=any(regexp_split_to_array('" . $rs['belong_schemas'] . "'::text, ';'::text))");
+                    }
+                    ///if (count($schemas_list) > 1) {
+                    foreach ($schemas_list as $sk => $sv) {
+                        if ($sv['schemas_name'] == "public") {
+                            continue;
+                        }
+                        $ttdd = common::excuteObjectSql("select contact_id_user, employee_id, contact_id, user_type, email, user_webtype_id, active, is_online, station, allow_login_remote, can_see_amslog,can_view_eccn, can_see_isflog, can_see_isflog_withaddress, 
+        customer_search_type, customer_destination, can_add_ams, can_add_isf, air_station, air_sales, ocean_station, ocean_sales,ocean_following_sales,ocean_following_sales_or,air_following_sales,air_following_sales_or, trucking_station, ocean_dest_op, can_see_password, can_add_opsales_code, ocean_station_or, ocean_agent_or, ocean_sales_or, ocean_dest_op_or, air_station_or, air_sales_or, trucking_station_or, 
+        can_add_user, can_add_employee, can_add_contact, company_name, ams_email, isf_email, customer_discharge, online_active, is_super, ocean_agent,active, can_send_email, view_file_format as docdownload, container_status, consolidated_cbsa_code, can_add_aci,
+        air_customers, air_customer_search_type,trucking_customers,trucking_customer_search_type, upload_document, view_file_format, event_type, po_status, view_air_file_format, special_customer_event, can_edi_vgm, isf_aci_ams_station, is_kerry_shipment from " . $sv['schemas_name'] . ".ra_online_user where lower(user_login) = '" . strtolower($uname) . "'");
+                        if (empty($ttdd)) {
+                            unset($schemas_list[$sk]);
+                            continue;
+                        }
+
+                        if (!empty($ttdd['docdownload'])) {
+                            $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from " . $sv['schemas_name'] . ".ra_online_file_format where lower(serial_no) " . common::getInNotInSql($ttdd['docdownload']) . " and active = true group by display_name order by min(id)";
+                        } else {
+                            $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from " . $sv['schemas_name'] . ".ra_online_file_format where active = true";
+                            if (strtolower($ttdd['user_type']) == "customer")
+                                $sql .= " and client_display = true";
+                            $sql .= " group by display_name order by min(id)";
+                        }
+                        $ttdd['view_doc_type'] = common::excuteListSql($sql);
+
+                        if (!empty($ttdd['view_air_file_format'])) {
+                            $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from " . $sv['schemas_name'] . ".air_file_format where lower(serial_no) " . common::getInNotInSql($ttdd['view_air_file_format']) . " and active = true group by display_name order by min(id)";
+                        } else {
+                            $sql = "select string_agg(serial_no, ';') as serial_no, string_agg(m_h, ';') as m_h, display_name from " . $sv['schemas_name'] . ".air_file_format where active = true";
+                            if (strtolower($ttdd['user_type']) == "customer")
+                                $sql .= " and client_display = true";
+                            $sql .= " group by display_name order by min(id)";
+                        }
+                        $ttdd['view_air_doc_type'] = common::excuteListSql($sql);
+                        
+                         //补充aci and ams CustomerLogin station - other like sfs
+                        $ocean_station_temp = $ttdd['ocean_station'];
+                        $ttdd['session_ocean_station'] = $this->getOriginOrAgent($ocean_station_temp);
+
+                        $ocean_agent_temp = $ttdd['ocean_agent'];
+                        $ttdd['session_ocean_agent'] = $this->getOriginOrAgent($ocean_agent_temp);
+
+                        $_SESSION[$sv['schemas_name'] . '_ONLINE_USER'] = $ttdd;
+                    }
+                    //}
+                    $_SESSION['schemas_list'] = $schemas_list;
+                    //不再返回登录页面,直接跳转
+                    if (isset($_GET['up'])) {
+                        if($_GET['v'] == 'new'){
+                           header("Location: main_new_version.php?action=main");
+                        }else{
+                           header("Location: main.php?action=main");
+                        }
+                    }
+                    //自动登录。为了方便调用,先注销掉
+                    //exit();
+                } else {
+                    $data = array(
+                        'msg' => 'database_error',
+                        'login_version' => $rs["login_version"],
+                        'data' => ''
+                    );
+                    common::echo_json_encode(500, $data);
+                    exit();
+                }
+            } else {
+                $data = array(
+                    'msg' => 'no_exist',
+                    'login_version' => $rs["login_version"],
+                    'data' => ''
+                );
+                common::echo_json_encode(500, $data);
+                exit();
+            }
+        }
+    }
+
+    private function failedLogin($uname, $company){
+        $ip = common::ip();
+        common::excuteUpdateSql("insert into public.ra_online_user_login_log (user_name,manufacturer,from_app,ip,date_time, session_id) values ('" . common::check_input($uname) . "', '" . common::check_input($company) . "','Online','$ip',now(), '" . session_id() . "')");
+    }
+
+    //重置密码
+    public function passwordExpires($loginName,$email){
+        $result = array(
+            'msg' => "passwordExpires",
+        );
+        common::echo_json_encode(400, $result);
+        exit();
+    }
+
+    //submit change form -- change expires password 
+    public function update_pwd_expires(){
+        $loginName = common::check_input($_POST['uname']);
+        $old_password = common::check_input($_POST['old_password']);
+        $password = common::check_input($_POST['password']);
+        $verifcation_code = 
+
+        //首先校验验证码
+        $verifcation_code = common::check_input($_POST['verifcation_code']);
+        if (strtolower($_SESSION['captcha']) != strtolower($verifcation_code)) {    
+            $data = array(
+                'msg' => 'verifcation_error',
+                'data' => ''
+            );
+            common::echo_json_encode(400, $data);
+            exit();
+        }
+        
+        $sql = "select ra_password as password from ra_online_user where lower(user_login) = '" . strtolower($loginName) . "'";
+        $rs = common::excuteObjectSql($sql);
+        $str = '';
+        if (!empty($rs)) {
+            if ($rs['password'] != $old_password) {
+                $str = "Old password is incorrect!";
+            } 
+        } else {
+            $str = "Old password is incorrect!";
+        }
+        if(!empty($str)){
+            $data = array(
+                'msg' => $str,
+                'data' => ''
+            );
+            common::echo_json_encode(400, $data);
+            exit();
+        }
+
+        //验证通过,进行修改密码
+        $msg = $this->updateExpirePassword($loginName, $password);
+        if($msg == "success"){
+            $data = array(
+                'msg' => "success",
+                'data' => ''
+            );
+            common::echo_json_encode(200, $data);
+            exit();
+        } else {
+            $data = array(
+                'msg' => $str,
+                'data' => ''
+            );
+            common::echo_json_encode(400, $data);
+            exit();
+        }
+    }
+
+    //更新密码
+    public function updateExpirePassword($login,$new_password) {
+        $str = $this->checkPasswordRule($login, $new_password);
+
+        //更新密码,擦除expire pwd痕迹
+        if (empty($str)) {
+            $sql = "UPDATE public.ra_online_user SET ra_password = '" . common::check_input($new_password) . "',password_new=redant_encode('".$new_password."'),
+                 last_pwd_change = now(),password_expires_keycode = null,password_expires_time = null  
+            WHERE lower(user_login) = '" . common::check_input(strtolower($login)) . "';";
+            $rls = common::excuteUpdateSql($sql);
+            if (!$rls) {
+                $str = "Database Error, Try Later.";
+            } else {
+                $sql = "INSERT INTO public.ra_online_user_password_history (user_login, password, create_user, create_date) VALUES ('" . $login . "', " . common::check_input($new_password) . ", '" . $login . "', now());";
+                common::excuteUpdateSql($sql);
+                $str = "success";
+            }
+        }
+
+        return $str;
+    }
+
+    //密码规则验证
+    public function checkPasswordRule($login, $new_password){
+        $sql="select item_value from config where item='passwordCheckRules'";
+        $rs = common::excuteObjectSql($sql);
+
+        $str =  "";
+        if (!empty($rs)) {
+            $passwordCheckRules = json_decode($rs["item_value"],true);
+            //校验使用次数
+            if (!empty($passwordCheckRules["pastPasswordCheckNum"])) {
+                $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"];
+                $passwords = common::excuteListSql($sql);
+                foreach ($passwords as $pwd) {
+                    if ($pwd['password'] == $new_password) {
+                        $str = "This password has been recently used";
+                    }
+                }
+            }
+            if(empty($str)){
+                $str = utils::checkPassword($new_password,$passwordCheckRules,$login);
+            }
+        }else{
+            $str = utils::checkPassword($new_password);
+        }
+
+        return $str;
+    }
+
+   
+    public function getOriginOrAgent($ocean_station_temp){
+        $session_ocean_station = "";
+        if (strtolower($ocean_station_temp) == 'all'){
+            $session_ocean_station = $ocean_station_temp;
+        }
+        if (!(strtolower($ocean_station_temp) == 'all' || empty($ocean_station_temp))){
+            if (utils::checkExist($ocean_station_temp, ";")) {
+                $ost = str_replace(";","','",strtolower($ocean_station_temp));
+                $sql="select kerry_station_id,contact_id from ocean.contacts where  coalesce(kerry_station_id,'') <>''and lower(contact_id) in ('".$ost."')";
+                $tar = common::excuteListSql($sql);
+                foreach ($tar as $tk => $tv) {
+                    $tar[$tv['contact_id']] = $tv['kerry_station_id'];
+                }
+
+                $_tt = explode(";", $ocean_station_temp);
+                foreach ($_tt as $vv) {
+                    if (!empty($vv)){
+                        $session_ocean_station .= trim($vv).';';
+
+                        if (!empty($tar[$vv])) {
+                            $session_ocean_station .= $tar[trim($vv)].';';
+                        }
+                    }
+               }
+
+            } else {
+                $session_ocean_station .= trim($ocean_station_temp).';';
+                $temp_contacts = common::excuteObjectSql("select kerry_station_id from ocean.contacts where lower(contact_id)='".strtolower(common::check_input($ocean_station_temp))."'");
+                if (!empty($temp_contacts['kerry_station_id'])){
+                    $session_ocean_station .= $temp_contacts['kerry_station_id'].';';
+                }
+            }
+        }
+        return $session_ocean_station;
+    }
+
+
+}
+
+?>

+ 461 - 0
service/ocean_booking.class.php

@@ -0,0 +1,461 @@
+<?php
+
+if (!defined('IN_ONLINE')) {
+    exit('Access Denied');
+}
+
+/**
+ * Description of ocean
+ *
+ * @author Administrator
+ */
+class ocean_booking {
+
+    private static $_ocean;
+
+    function __construct() {  
+       
+    }
+
+    public static function getInstance() {
+        global $memory_limit;
+        $memory_limit = ini_get("memory_limit");
+        ini_set("memory_limit", '2048M');
+        if (!self::$_ocean) {
+            $c = __CLASS__;
+            self::$_ocean = new $c;
+        }
+        return self::$_ocean;
+    }
+
+    public function ocean_booking() {
+        $operate = utils::_get('operate');
+        $operate = strtolower($operate);
+        /*
+         * index page
+         */
+        if (empty($operate)) {
+            $data = array();
+            if (_isCustomerLogin())
+                $data['is_customer'] = "yes";
+            else
+                $data['is_customer'] = "no";
+            //栏位信息
+            $column = column::getInstance()->getDisplayColumn('Booking_Search');
+            $BookingTableColumns = column::getInstance()->tableColumns('Booking_Search',$column);
+            $data['BookingTableColumns'] = $BookingTableColumns;
+            common::echo_json_encode(200,$data);
+            exit();
+        }
+        /*
+         * ocean order search
+         */
+        if ($operate == "search") {
+            $this->_booking_search();
+        }
+        if ($operate == "setting_display") {
+            column::getInstance()->settingDisplay('Booking_Search', 'main_new_version.php?action=ocean_booking');
+        }
+        if ($operate == "detail") {
+            $this->_booking_detail();
+        }
+        if ($operate == "excel") {
+            $this->_booking_excel();
+        }
+        if ($operate == "save_communication") {
+            try {
+                $content = $_POST["content"];
+                $content = common::check_input($content);
+                $text = $_POST["text"];
+                $content = urldecode($content);
+                $web_content = urldecode($text);
+
+                $communication_cc = $_POST["communication_cc"];
+                $serial_no = common::uuid();
+                $email_uuid = $_POST["serial_no"];
+                $add_by = _getLoginName();
+                $refer_id = 0;
+               
+                $email = $this->getEmail($email_uuid);
+                $from_email = "US.KApex.Online@kerryapex.com";
+                $to_email = $email["email"];
+                $cc_email = $_SESSION['ONLINE_USER']['email'] . ";ApexOnlineCommunication@apexshipping.com";
+                $communication_cc = trim($communication_cc);
+                if (!empty($communication_cc)) {
+                    $communication_cc = common::check_input($communication_cc);
+                    $cc_email .= ";" . $communication_cc;
+                }
+
+
+                $user_from = _getLoginName();
+                $user_to = $email["name"];
+                $user_cc = $_SESSION['ONLINE_USER']['first_name'];
+                if (empty($user_cc)) {
+                    $user_cc = _getLoginName();
+                }
+                $user_cc .= ";ApexOnlineCommunication";
+
+                //邮件发送
+                $poKey = "<br><br>Important note: when you reply this email, do not remove ApexOnlineCommunication@apexshipping.com<br>Below is system code, do not delete.<br>@@";
+                $emailSql = "select encode(public.pgp_sym_encrypt('" . $serial_no . "','pom_key'), 'base64')::text;";
+                $key = common::excuteOneSql($emailSql);
+
+                $historyEmails = "";
+
+                $title = "Communication from " . _getLoginName() . ", HBOL: " . $email["h_bol"] . ", Consignee: " . $email["consignee"];
+                $emailContent = $content . $poKey . $key . ";" . "@@<br>For your convenience weblink: https://ra.kerryapex.com/<br><br>" . $historyEmails;
+
+                common::excuteUpdateSql("insert into public.email_record (type,title,from_email,to_email,cc_email,content,insert_date)values('Communication','$title','$from_email','$to_email','$cc_email','$emailContent',now());");
+
+                $rs = common::excuteUpdateSql("INSERT INTO public.online_ocean_communication(serial_no, email_uuid, content,web_content,user_from, user_to, user_cc, refer_id, add_by, add_time, cc_email) 
+                VALUES ('$serial_no', '$email_uuid', '$emailContent','$web_content', '$user_from', '$to_email', '$cc_email', $refer_id, '$add_by', now(), '$communication_cc');");
+
+                $emailRecords = $this->getCommunicationNew($email_uuid);
+                common::echo_json_encode(200,array("msg" => "Sent Successfully", "emailRecords" => $emailRecords));
+                exit();
+            } catch (Exception $e) {
+                common::echo_json_encode(500,array("msg" => "Sent Error."));
+                exit();
+            }
+        }
+    }
+
+    private function _booking_search() {
+        $cp = common::check_input($_POST ['cp']); //current_page
+        $ps = common::check_input($_POST ['ps']); //ps
+        if (empty($ps))
+            $ps = 50;
+
+        $sqlWhere = ' where ' . common::searchExtendHandNew("booking", $_SESSION["ONLINE_USER"]);
+        $sqlWhere .= search::getInstance()->getSearchSQL("Booking_Search");
+
+        //前端提交是数组
+        if (!empty($_POST['filterTag']) && count($_POST['filterTag']) < 4) {
+            if (count($_POST['filterTag']) == 1){
+                $filterTag = $_POST['filterTag'][0];
+            }else{
+                $filterTag = implode(",", $_POST['filterTag']);
+            }
+            $_sqlwhere = "1<>1";
+            if (stripos($filterTag, "Confirmed") !== FALSE) {
+                $_sqlwhere .= " or (bol_type = 'BOOKING' and status!='Cancelled')";
+            }
+            if (stripos($filterTag, "type2") !== FALSE) {
+                $_sqlwhere .= " or (bol_type != 'BOOKING' and booking_no is not null and booking_no <> '')";
+            }
+            if (stripos($filterTag, "Cancelled") !== FALSE) {
+                $_sqlwhere .= " or (status='Cancelled')";
+            }
+            if (stripos($filterTag, "Created") !== FALSE) {
+                $_sqlwhere .= " or (bol_type != 'BOOKING' and (booking_no is null or booking_no = ''))";
+            }
+            if(strtolower($filterTag) <> "all" && !empty($filterTag)){
+                $sqlWhere .= " and ($_sqlwhere)";
+            }
+        }
+        if (!empty($_POST["_textSearch"])) {
+            $sqlWhere .= " and text_search @@ (str_to_tsquery('" . common::check_input($_POST["_textSearch"]) . "'))";
+        }
+
+        $rc = $_POST ['rc'];
+        //这里都要查询,除非多传几个参数回来
+        if ($rc == - 1 || true) {
+            //查询ALL
+            $sql = "SELECT count(1) from public.online_booking" . $sqlWhere;
+            $rc = common::excuteOneSql($sql);
+            error_log($sql);
+            
+            //查询Creatd
+            $Creatd_sqlWhere = " and (1<>1 or (bol_type != 'BOOKING' and (booking_no is null or booking_no = '')))";
+            $Creatd_sql = "SELECT count(1) from public.online_booking" . $sqlWhere.$Creatd_sqlWhere;
+            $Creatd = common::excuteOneSql($Creatd_sql);
+
+            //查询Confirmed
+            $Confirmed_sqlWhere = " and (1<>1 or (bol_type = 'BOOKING' and status!='Cancelled'))";
+            $Confirmed_sql = "SELECT count(1) from public.online_booking" . $sqlWhere.$Confirmed_sqlWhere;
+            $Confirmed = common::excuteOneSql($Confirmed_sql);
+
+            //查询Concelled
+            $Concelled_sqlWhere = " and (1<>1 or (status='Cancelled'))";
+            $Concelled_sql = "SELECT count(1) from public.online_booking" . $sqlWhere.$Concelled_sqlWhere;
+            $Concelled = common::excuteOneSql($Concelled_sql);
+
+            //前端数据返回,不管有无数据
+            if (!empty($_POST["filterTag"])) {
+                $tagsList = array(array("name"=>"All","number"=>$rc,"type"=>"all","checked"=>in_array('All', $_POST["filterTag"])? true : false),
+                array("name"=>"Created","number"=>$Creatd,"type"=>"created","checked"=>in_array('Created', $_POST["filterTag"])? true : false),
+                array("name"=>"Confirmed","number"=>$Confirmed,"type"=>"confirmed","checked"=>in_array('Confirmed', $_POST["filterTag"])? true : false),
+                array("name"=>"Cancelled","number"=>$Concelled,"type"=>"cancelled","checked"=>in_array('Cancelled', $_POST["filterTag"])? true : false));
+            }else{
+                //初始,前端有选择着带入选择
+                $tagsList = array(array("name"=>"All","number"=>$rc,"type"=>"all","checked"=>true),
+                array("name"=>"Created","number"=>$Creatd,"type"=>"created","checked"=>false),
+                array("name"=>"Confirmed","number"=>$Confirmed,"type"=>"confirmed","checked"=>false),
+                array("name"=>"Cancelled","number"=>$Concelled,"type"=>"cancelled","checked"=>false));
+            }
+
+            $TransportList = array(
+                array("name"=>"Ocean Freight","number"=>$rc,"checked"=>false,"icon"=>"#icon-icon_ocean_b"));
+
+            //现在下载交给前端,后台预先只返回全部字段的列,
+            $allColumn = column::getInstance()->getDisplayColumnAllReomveDefault('Booking_Search');
+            $allBookingColumns = column::getInstance()->tableColumns('Booking_Search',$allColumn);
+            
+        }
+        $tp = ceil($rc / $ps);
+        if ($rc > 0 ) {
+            $order_by = " f_etd desc NULLS LAST, id";
+            //TopOcean的不用考虑
+            $ocean_dest_sql = "";
+            //合并显示两个特殊字段 voyage_m_voyage/vessel_m_vessel
+            if (!empty($_POST["_textSearch"])) {
+                $sql = "SELECT order_from as _schemas, serial_no as __serial_no, created_time as __created_time, color,
+                        m_voyage as __m_voyage,m_vessel as __m_vessel," .
+                        column::getInstance()->getSearchSql('Booking_Search') . " from public.online_booking $ocean_dest_sql " . $sqlWhere . " "
+                        . "order by $order_by limit " . $ps . " offset " . ($cp - 1) * $ps;
+            } else {
+                $sql = "SELECT order_from as _schemas, serial_no as __serial_no, created_time as __created_time, color, 
+                        f_voyage as __f_voyage, m_voyage as __m_voyage,f_vessel as __f_vessel, m_vessel as __m_vessel," .
+                        column::getInstance()->getSearchSql('Booking_Search') . " from public.online_booking $ocean_dest_sql " . $sqlWhere . " order by $order_by limit " . $ps . " offset " . ($cp - 1) * $ps;
+            }
+            error_log($sql);
+            $rs = common::excuteListSql($sql);
+
+            //对查询的结果做特殊处理,比如要拼接某个值,合并值等
+            foreach($rs as $index => $val) {
+                //合并显示 vessel
+                if(array_key_exists("f_vessel", $val)){
+                    $rs[$index]["f_vessel"] = utils::outDisplayForMerge($val['f_vessel'],$val['__m_vessel']);
+                }
+                //合并显示 voyage
+                if(array_key_exists("f_voyage", $val)){
+                    $rs[$index]["f_voyage"] = utils::outDisplayForMerge($val['f_voyage'],$val['__m_voyage']);
+                }
+                //返回加密serial_no
+                $rs[$index]["__serial_no"] = common::deCode($val['__serial_no'], 'E');
+
+                //按新逻辑处理status,现在是管理员权限,客户权限少了一种状态,先设置默认值防止出错
+                $status = "Created";
+                if(!($val['color'] == "FFFF0000" || $val['color'] == "FF00FF00" || $val['color'] == "FF0000FF")){
+                    $status = "Created";
+                }
+                if ($val['color'] == "FF00FF00"){
+                    $status = "Confirmed";
+                }
+                if ($val['color'] == "FFFF0000"){
+                    $status = "Cancelled";
+                }
+                $rs[$index]["status"] = $status;
+                $rs[$index]["mode"] = "Ocean Frieght";
+
+            }
+
+            
+            $arrTmp = array('searchData' => $rs, 
+                'tagsList' => $tagsList,
+                'TransportList' => $TransportList,
+                'allColums' => $allBookingColumns,
+                'rc' => $rc,
+                'ps' => $ps,
+                'cp' => $cp,
+                'tp' => $tp,
+                'tmp_search' => common::deCode($sql, 'E'),
+                'type' => common::check_input($_POST ['_ntype']));
+        } else {
+            $arrTmp = array('searchData' => array(), 
+                'tagsList' => $tagsList,
+                'TransportList' => $TransportList,
+                'allColums' => $allBookingColumns,
+                'rc' => $rc,
+                'ps' => $ps,
+                'cp' => $cp,
+                'tp' => $tp,
+                'tmp_search' => "",
+                'type' => common::check_input($_POST ['_ntype']));
+        }
+
+        common::echo_json_encode(200,$arrTmp);
+        exit();
+    }
+
+    private function _booking_detail() {
+        $serial_no = common::deCode($_GET['a'], 'D');
+        $status = common::deCode($_GET['status'], 'D');
+        $sql = "SELECT o.serial_no, o.booking_no as _booking_no, o.* ,sh.*, cn.* ,aa.*,dd.* from ocean o
+            LEFT JOIN LATERAL ( SELECT company as cn_company,
+                address_1 as cn_address_1,
+                address_2 as cn_address_2,
+                address_3 as cn_address_3,
+                address_4 as cn_address_4,
+                city as cn_city, state as cn_state, zipcode as cn_zipcode, country as cn_country,
+                phone_1 as cn_phone
+            FROM contacts c WHERE o.consignee::text = c.contact_id::text) cn ON true
+            LEFT JOIN LATERAL ( SELECT company as sh_company,
+                address_1 as sh_address_1,
+                address_2 as sh_address_2,
+                address_3 as sh_address_3,
+                address_4 as sh_address_4,
+                city as sh_city, state as sh_state, zipcode as sh_zipcode, country as sh_country,
+                phone_1 as sh_phone
+            FROM contacts c WHERE o.shipper::text = c.contact_id::text) sh ON true
+            LEFT JOIN LATERAL ( SELECT company as aa_company,
+                address_1 as aa_address_1,
+                address_2 as aa_address_2,
+                address_3 as aa_address_3,
+                address_4 as aa_address_4,
+                city as aa_city, state as aa_state, zipcode as aa_zipcode, country as aa_country,
+                phone_1 as aa_phone
+            FROM contacts c WHERE o.origin_station::text = c.contact_id::text) aa ON true
+            LEFT JOIN LATERAL ( SELECT company as dd_company,
+                address_1 as dd_address_1,
+                address_2 as dd_address_2,
+                address_3 as dd_address_3,
+                address_4 as dd_address_4,
+                city as dd_city, state as dd_state, zipcode as dd_zipcode, country as dd_country,
+                phone_1 as dd_phone
+            FROM contacts c WHERE o.destination_station::text = c.contact_id::text) dd ON true
+        where lower(serial_no) = '" . strtolower($serial_no) . "'";
+        $ocean = common::excuteObjectSql($sql);
+
+        //处理transportInfo信息数据
+        $transportInfo = array("bookingNo." =>$ocean['booking_no'],"status"=>$status,"mode" => "","origin" =>$ocean['origin_station'],"destination" =>$ocean['destination_station'],
+            "etd" =>$ocean['f_etd'],"atd" =>"","eta" =>$ocean['m_eta'],"ata" =>"");
+
+        //处理basicInfo信息数据
+        $vessel = utils::outDisplayForMerge($ocean['f_vessel'],$ocean['m_vessel']);
+        $voyage = utils::outDisplayForMerge($ocean['f_voyage'],$ocean['m_voyage']);
+        $basicInfo = array("bookingNo." =>$ocean['booking_no'],"HAWB/HBOL" => $ocean['h_bol'],"Carrier_Booking_No" =>$ocean['carrier_booking'],
+            "PO_NO" =>$ocean['po_no'],"Vessel/Airline" =>$vessel,"Voyage/Filght" =>$voyage,
+            "Incoterm" =>$ocean['terms'],"Service_Type" =>$ocean['service']);
+
+        //处理 拼接地址 ocean表单exp 字段无法精准分割电话和地址信息,只能从contacts表里查询
+        $shipper_address = $this->retStationInfo($ocean['sh_address_1'], $ocean['sh_address_2'], $ocean['sh_address_3'], $ocean['sh_address_4'], 
+            $ocean['sh_city'], $ocean['sh_state'], $ocean['sh_zipcode'], $ocean['sh_country']);
+        $consignee_address = $this->retStationInfo($ocean['cn_address_1'], $ocean['cn_address_2'], $ocean['cn_address_3'], $ocean['cn_address_4'], 
+            $ocean['cn_city'], $ocean['cn_state'], $ocean['cn_zipcode'], $ocean['cn_country']);
+        $origin_address = $this->retStationInfo($ocean['aa_address_1'], $ocean['aa_address_2'], $ocean['aa_address_3'], $ocean['aa_address_4'], 
+            $ocean['aa_city'], $ocean['aa_state'], $ocean['aa_zipcode'], $ocean['aa_country']); 
+        $destination_address = $this->retStationInfo($ocean['dd_address_1'], $ocean['dd_address_2'], $ocean['dd_address_3'], $ocean['dd_address_4'], 
+            $ocean['dd_city'], $ocean['dd_state'], $ocean['dd_zipcode'], $ocean['dd_country']);    
+
+        $shipperPartners = array("company" =>$ocean['sh_company'],"address"=>$shipper_address,"phone"=>$ocean['sh_phone']);
+        $consigneePartners = array("company" =>$ocean['cn_company'],"address"=>$consignee_address,"phone"=>$ocean['cn_phone']);
+        $originPartners = array("company" =>$ocean['aa_company'],"address"=>$origin_address,"phone"=>$ocean['aa_phone']);
+        $destinationPartners = array("company" =>$ocean['dd_company'],"address"=>$destination_address,"phone"=>$ocean['dd_phone']);
+        $businessPartners = array("shipper"=>$shipperPartners,"consignee" => $consigneePartners,"origin" => $originPartners,"destination" => $destinationPartners);
+
+        //todo 不确定信息
+        $packing = array("Quantity/Unit"=>"47 CTN","G. Weight" => "480.25 KGS","Ch. Weight" => "689.26 KGS","Volume" => "3.801 CBM");
+
+        //处理ocean_reference
+        $ref_no = array();
+        $ref_arr = common::excuteListSql("select * from ocean_reference where lower(serial_no) = '" . strtolower($serial_no) . "'");
+        if(!empty($ref_arr)){
+            foreach($ref_arr as  $ref) {
+                $ref_no[] = array("label"=>$ref["ref_code"],"value"=>$ref["ref_value"]);
+            }
+        }
+      
+        $marksAndDescription = array("marks"=>$ocean['marks'],"description"=>$ocean['description']);
+
+        //处理返回booking的 Container 信息数据
+        $booking_container_column = array();
+        $container_column = column::getInstance()->getDisplayColumnAll('Booking_Container');
+        foreach($container_column as $cc){
+            $booking_container_column[] =array("field" =>$cc['database_column_name'],"title" =>$cc['name'],"formatter" =>"","type" =>"normal");
+        }
+        if (!empty($ocean['_booking_no'])) {
+            $sql = "SELECT " . column::getInstance()->getSearchSql('Booking_Container') . " from ocean_booking_container where lower(serial_no) = '" . strtolower($serial_no) . "'";
+            $rss = common::excuteListSql($sql);
+        } else {
+            $sql = "SELECT " . column::getInstance()->getSearchSql('Booking_Container') . " from oc_container_booking_v where lower(serial_no) = '" . strtolower($serial_no) . "'";
+            $rss = common::excuteListSql($sql);
+        }
+        $containers = array("container_column"=>$booking_container_column,"container_data" =>$rss);
+        
+        //处理邮件信息返回
+        $emailRecords = $this->getCommunicationNew($ocean["serial_no"]);
+        $cc_email = common::excuteOneSql("select cc_email from public.online_ocean_communication where email_uuid='" . $ocean["serial_no"] . "' order by id desc limit 1");
+        $email = $this->getEmail($ocean["serial_no"]);
+        $email['cc_email'] = $cc_email;
+        $email['emailRecords'] = $emailRecords;
+
+
+        global $_COPYRIGHT;
+        $data = array('transportInfo' => $transportInfo, 
+                        'basicInfo' => $basicInfo,
+                        'businessPartners' => $businessPartners,
+                        'ref_no' => $ref_no,
+                        'packing' => $packing,
+                        'marksAndDescription' => $marksAndDescription,
+                        'containers' => $containers,
+                        'email' => $email,
+                        'serial_no' => $serial_no,
+                        '_schemas' => $_GET['_schemas'],
+                        '__serial_no' => common::deCode($ocean['serial_no'], 'E'),
+                        'copyright' =>$_COPYRIGHT);
+        common::echo_json_encode(200,$data);                
+        exit(); 
+    }
+
+    private function _booking_excel() {
+        //现在下载交给前端,后台最后只返回全部字段的列,
+        $allColumn = column::getInstance()->getDisplayColumnAll('Booking_Search');
+        $allBookingColumns = column::getInstance()->tableColumns('Booking_Search',$allColumn);
+        common::echo_json_encode(200,array("msg"=>"success","allColums" => $allBookingColumns));
+        exit;
+    }
+
+    private function getEmail($serial_no) {
+        return utils::getEmail($serial_no);
+    }
+
+    private function getCommunicationNew($serial_no) {
+        $list = common::excuteListSql("select to_char(add_time, 'MM/dd/yyyy hh24:MI:ss') as add_times, * from public.online_ocean_communication where email_uuid='$serial_no' and refer_id = 0  order by id");
+        $emialRecords =array();
+        foreach ($list as $k => $v) {
+            $msg =array();
+            $msg["name"] = $v["add_by"];
+            $msg["creatTime"] = $v["add_times"];
+            $msg["content"] =  urldecode($v["web_content"]);
+            $emialRecords[] = $msg;
+        }
+        return $emialRecords;
+    }
+
+
+    private function retStationInfo($address_1,$address_2,$address_3,$address_4,$city,$state,$country,$zipcode){
+        $stationInfo = "";
+        if(!empty($address_1)){
+            $stationInfo .= $address_1;
+        }
+        if(!empty($address_2)){
+            $stationInfo .= " ".$address_2;
+        }
+        if(!empty($address_3)){
+            $stationInfo .= " ".$address_3;
+        }
+        if(!empty($address_4)){
+            $stationInfo .= " ".$address_4;
+        }
+        $temp_str  = "";
+        if(!empty($city)){
+            $temp_str .= $city." ";
+        }
+        if(!empty($state)){
+            $temp_str .= $state." ";
+        }
+        if(!empty($zipcode)){
+            $temp_str .= $zipcode." ";
+        }
+        if(!empty($country)){
+            $temp_str .= $country." ";
+        }
+        if(!empty($temp_str)){
+            return $stationInfo." ".trim($temp_str);
+        }
+        return $stationInfo;
+    }
+}
+
+?>

+ 787 - 0
service/ocean_order.class.php

@@ -0,0 +1,787 @@
+<?php
+
+if (!defined('IN_ONLINE')) {
+    exit('Access Denied');
+}
+
+/**
+ * Description of ocean
+ *
+ * @author Administrator
+ */
+class ocean_order {
+
+    private static $_ocean;
+
+    function __construct() {  
+       
+    }
+
+    public static function getInstance() {
+        global $memory_limit;
+        $memory_limit = ini_get("memory_limit");
+        ini_set("memory_limit", '2048M');
+        if (!self::$_ocean) {
+            $c = __CLASS__;
+            self::$_ocean = new $c;
+        }
+        return self::$_ocean;
+    }
+    public function ocean_order() {
+        $operate = utils::_get('operate');
+        $operate = strtolower($operate);
+
+        /*
+         * index page
+         */
+        if (empty($operate)) {
+            //search
+            //$search = search::getInstance()->getDisplaySearch("Ocean_Search
+            //栏位信息
+            $column = column::getInstance()->getDisplayColumn('Ocean_Search');
+            $BookingTableColumns = column::getInstance()->tableColumns('Ocean_Search',$column);
+            $data['TrackingTableColumns'] = $BookingTableColumns;
+            common::echo_json_encode(200,$data);
+            exit();
+
+        }
+        /*
+         * ocean order search
+         */
+        if ($operate == "search") {
+            $this->_ocean_search();
+        }
+
+        /*
+         * ocean order detail
+         */
+        if ($operate == "detail") {
+            $this->_ocean_detail();
+        }
+
+        if ($operate == "ams_isf_log"){
+            $this->_ams_isf_log();
+        }
+
+        /*
+         * export ocean order to excel
+         */
+        if ($operate == "excel") {
+            $this->_ocean_excel();
+        }
+       
+        if ($operate == 'setting_ocean_order_display') {
+            column::getInstance()->settingDisplay('Ocean_Search', 'main_new_version.php?action=ocean_order');
+        }
+
+        /*
+         * download document
+         */
+        if ($operate == "download") {
+            $this->_download();
+        }
+
+        if ($operate == "save_communication") {
+            try {
+                $content = $_POST["content"];
+                $content = common::check_input($content);
+                $text = $_POST["text"];
+                $content = urldecode($content);
+                $web_content = urldecode($text);
+
+                $communication_cc = $_POST["communication_cc"];
+                $serial_no = common::uuid();
+                $email_uuid = $_POST["serial_no"];
+                $add_by = _getLoginName();
+                $refer_id = 0;
+               
+                $email = $this->getEmail($email_uuid);
+                $from_email = "US.KApex.Online@kerryapex.com";
+                $to_email = $email["email"];
+                $cc_email = $_SESSION['ONLINE_USER']['email'] . ";ApexOnlineCommunication@apexshipping.com";
+                $communication_cc = trim($communication_cc);
+                if (!empty($communication_cc)) {
+                    $communication_cc = common::check_input($communication_cc);
+                    $cc_email .= ";" . $communication_cc;
+                }
+
+
+                $user_from = _getLoginName();
+                $user_to = $email["name"];
+                $user_cc = $_SESSION['ONLINE_USER']['first_name'];
+                if (empty($user_cc)) {
+                    $user_cc = _getLoginName();
+                }
+                $user_cc .= ";ApexOnlineCommunication";
+
+                //邮件发送
+                $poKey = "<br><br>Important note: when you reply this email, do not remove ApexOnlineCommunication@apexshipping.com<br>Below is system code, do not delete.<br>@@";
+                $emailSql = "select encode(public.pgp_sym_encrypt('" . $serial_no . "','pom_key'), 'base64')::text;";
+                $key = common::excuteOneSql($emailSql);
+
+                $historyEmails = "";
+
+                $title = "Communication from " . _getLoginName() . ", HBOL: " . $email["h_bol"] . ", Consignee: " . $email["consignee"];
+                $emailContent = $content . $poKey . $key . ";" . "@@<br>For your convenience weblink: https://ra.kerryapex.com/<br><br>" . $historyEmails;
+
+                common::excuteUpdateSql("insert into public.email_record (type,title,from_email,to_email,cc_email,content,insert_date)values('Communication','$title','$from_email','$to_email','$cc_email','$emailContent',now());");
+
+                $rs = common::excuteUpdateSql("INSERT INTO public.online_ocean_communication(serial_no, email_uuid, content,web_content,user_from, user_to, user_cc, refer_id, add_by, add_time, cc_email) 
+                VALUES ('$serial_no', '$email_uuid', '$emailContent','$web_content', '$user_from', '$to_email', '$cc_email', $refer_id, '$add_by', now(), '$communication_cc');");
+
+                $emailRecords = $this->getCommunicationNew($email_uuid);
+                common::echo_json_encode(200,array("msg" => "Sent Successfully", "emailRecords" => $emailRecords));
+                exit();
+            } catch (Exception $e) {
+                common::echo_json_encode(500,array("msg" => "Sent Error."));
+                exit();
+            }
+        }
+    }
+
+    /*
+    * ocean order search
+    */
+    private function _ocean_search() {
+        $cp = common::check_input($_POST ['cp']); //current_page
+        $ps = common::check_input($_POST ['ps']); //ps
+        if (empty($ps))
+            $ps = 50;
+
+        $sqlWhere = ' where ' . common::searchExtendHandNew("ocean", $_SESSION["ONLINE_USER"]);
+        $sqlWhere .= search::getInstance()->getSearchSQL("Ocean_Search");
+
+        //查询tag
+        // IFFBCF;Booking Confirmation
+        // IFFREC;Cargo Arrived at Origin
+        // IFFDEP;Departure
+        // IFFARR;Arrived at Final Destination Port
+        // IFFAFD;Arrived at Final Destination
+        if (!empty($_POST["filterTag"])) {
+            $tempsql = "1<>1";
+            foreach($_POST["filterTag"] as $tag){
+                if ($tag == "All"){
+                    continue;
+                } elseif ($tag == "Booked"){
+                    //$tempsql .=" or code ";
+                } elseif ($tag == "Cargo Received"){
+                   
+                } elseif ($tag == "Departure"){
+                   
+                }elseif ($tag == "Arrived"){
+                  
+                }elseif ($tag == "Completed"){
+                   
+                }
+            }
+            if ($tempsql <> "1<>1"){
+                $sqlWhere .= " and (exists(select 1 from public.ocean_milestone where $tempsql))";
+            }
+        }
+        if (!empty($_POST["_textSearch"])) {
+            $sqlWhere .= " and text_search @@ (str_to_tsquery('" . common::check_input($_POST["_textSearch"]) . "'))";
+        }
+
+        $rc = $_POST ['rc'];
+        if ($rc == - 1) {
+            $sql = "SELECT count(1) from public.online_ocean" . $sqlWhere;
+            $rc = common::excuteOneSql($sql);
+
+            if (!empty($_POST["filterTag"])) {
+                $tagsList = array(array("name"=>"All","number"=>$rc,"type"=>"all","checked"=>in_array('All', $_POST["filterTag"])? true : false),
+                array("name"=>"Booked","number"=>0,"type"=>"booked","checked"=>in_array('Booked', $_POST["filterTag"])? true : false),
+                array("name"=>"Cargo Received","number"=>0,"type"=>"cargo_received","checked"=>in_array('Cargo Received', $_POST["filterTag"])? true : false),
+                array("name"=>"Departure","number"=>0,"type"=>"departure","checked"=>in_array('Departure', $_POST["filterTag"])? true : false),
+                array("name"=>"Arrived","number"=>0,"type"=>"arrived","checked"=>in_array('Arrived', $_POST["filterTag"])? true : false),
+                array("name"=>"Completed","number"=>0,"type"=>"completed","checked"=>in_array('Completed', $_POST["filterTag"])? true : false));
+            }else{
+                //初始,前端有选择着带入选择
+                $tagsList = array(array("name"=>"All","number"=>$rc,"type"=>"all","checked"=> true ),
+                array("name"=>"Booked","number"=>0,"type"=>"booked","checked"=> false),
+                array("name"=>"Cargo Received","number"=>0,"type"=>"cargo_received","checked"=> false),
+                array("name"=>"Departure","number"=>0,"type"=>"departure","checked"=> false),
+                array("name"=>"Arrived","number"=>0,"type"=>"arrived","checked"=> false),
+                array("name"=>"Completed","number"=>0,"type"=>"completed","checked"=>false));
+            }
+
+            $TransportList = array(
+                array("name"=>"Ocean Freight","number"=>$rc,"checked"=>false,"icon"=>"#icon-icon_ocean_b"));
+
+            //现在下载交给前端,后台预先只返回全部字段的列,
+            $allColumn = column::getInstance()->getDisplayColumnAllReomveDefault('Ocean_Search');
+            $allBookingColumns = column::getInstance()->tableColumns('Ocean_Search',$allColumn);
+        }
+        $tp = ceil($rc / $ps);
+        $order_by = " etd desc NULLS LAST, id";
+        if (_isCustomerLogin()) {
+            $order_by = " eta desc NULLS LAST, id";
+        }
+        if ($rc > 0) {
+            $ocean_ref_sql = "LEFT JOIN LATERAL ( SELECT string_agg(ref_code ||ref_value, ', ') AS other_refenrence_no
+                            FROM public.ocean_reference temp WHERE temp.serial_no = online_ocean.serial_no) aa ON true ";
+            if (!empty($_POST["_textSearch"])) {
+                $sql = "SELECT order_from as _schemas, serial_no as __serial_no,serial_no,  h_bol as _hbol, isf_bol as _isfbol, " .
+                        column::getInstance()->getSearchSql('Ocean_Search') . " from public.online_ocean  $ocean_ref_sql " . $sqlWhere . " "
+                        . "order by $order_by limit " . $ps . " offset " . ($cp - 1) * $ps;
+            } else {
+                $sql = "SELECT order_from as _schemas,serial_no as __serial_no, serial_no, h_bol as _hbol, isf_bol as _isfbol, " .
+                        column::getInstance()->getSearchSql('Ocean_Search') . " from public.online_ocean $ocean_ref_sql " . $sqlWhere . 
+                        " order by $order_by limit " . $ps . " offset " . ($cp - 1) * $ps;
+            }
+            $rs = common::excuteListSql($sql);
+            //对查询的结果做特殊处理,比如要拼接某个值,合并值等
+            foreach($rs as $index => $val) {
+                //返回加密serial_no
+                $rs[$index]["__serial_no"] = common::deCode($val['__serial_no'], 'E');
+                $rs[$index]["mode"] = "Ocean Frieght";
+            }
+        
+            $arrTmp = array('searchData' => $rs, 
+               'tagsList' => array(),
+               'TransportList' => $TransportList,
+               'allColums' => $allBookingColumns,
+               'rc' => $rc,
+               'ps' => $ps,
+               'cp' => $cp,
+               'tp' => $tp,
+               'tmp_search' => common::deCode($sql, 'E'),
+               'type' => common::check_input($_POST ['_ntype']));
+        } else {
+            $arrTmp = array('searchData' => array(), 
+                'tagsList' => array(),
+                'TransportList' => $TransportList,
+                'allColums' => $allBookingColumns,
+                'rc' => $rc,
+                'ps' => $ps,
+                'cp' => $cp,
+                'tp' => $tp,
+                'tmp_search' => common::deCode($sql, 'E'),
+                'type' => common::check_input($_POST ['_ntype']));
+        }
+        common::echo_json_encode(200,$arrTmp);
+        exit();
+    }
+
+    private function _ocean_detail() {
+        $serial_no = common::deCode($_GET['a'], 'D');
+        $status = $_GET['status'];
+        $sql = "SELECT m_eta as _m_eta,  h_bol as _h_bol, m_bol as _m_bol,job_no as _job_bol,
+                public.z_get_eta_dest(o.final_eta::date, o.eta_dest::text, o.service::text, o.m_eta::date, o.place_of_delivery::text, o.mport_of_discharge::text) as _eta_dest, 
+                to_char(final_eta, 'MM/DD/YYYY') as _final_eta,o.* ,sh.*, cn.* ,aa.*,dd.* 
+                from ocean o 
+                LEFT JOIN LATERAL ( SELECT company as cn_company,
+                    address_1 as cn_address_1,
+                    address_2 as cn_address_2,
+                    address_3 as cn_address_3,
+                    address_4 as cn_address_4,
+                    city as cn_city, state as cn_state, zipcode as cn_zipcode, country as cn_country,
+                    phone_1 as cn_phone
+                FROM contacts c WHERE o.consignee::text = c.contact_id::text) cn ON true
+                LEFT JOIN LATERAL ( SELECT company as sh_company,
+                    address_1 as sh_address_1,
+                    address_2 as sh_address_2,
+                    address_3 as sh_address_3,
+                    address_4 as sh_address_4,
+                    city as sh_city, state as sh_state, zipcode as sh_zipcode, country as sh_country,
+                    phone_1 as sh_phone
+                FROM contacts c WHERE o.shipper::text = c.contact_id::text) sh ON true
+                LEFT JOIN LATERAL ( SELECT company as aa_company,
+                    address_1 as aa_address_1,
+                    address_2 as aa_address_2,
+                    address_3 as aa_address_3,
+                    address_4 as aa_address_4,
+                    city as aa_city, state as aa_state, zipcode as aa_zipcode, country as aa_country,
+                    phone_1 as aa_phone
+                FROM contacts c WHERE o.origin_station::text = c.contact_id::text) aa ON true
+                LEFT JOIN LATERAL ( SELECT company as dd_company,
+                    address_1 as dd_address_1,
+                    address_2 as dd_address_2,
+                    address_3 as dd_address_3,
+                    address_4 as dd_address_4,
+                    city as dd_city, state as dd_state, zipcode as dd_zipcode, country as dd_country,
+                    phone_1 as dd_phone
+                FROM contacts c WHERE o.destination_station::text = c.contact_id::text) dd ON true
+            where lower(serial_no) = '" . strtolower($serial_no) . "'";
+        $ocean = common::excuteObjectSql($sql);
+        if (!empty($ocean)) {
+         
+            $ocean['_isf_bol'] = $ocean['isf_bol'];
+            if (empty($ocean['_isf_bol'])) {
+                $ocean['_isf_bol'] = "AMAW" . $ocean['_h_bol'];
+            }
+            $isf_ss = md5(md5($ocean['_isf_bol']));
+            $isf_ss = substr($isf_ss, 7) . substr($isf_ss, 0, 7);
+
+            if (!empty($ocean['_final_eta'])) {
+                $ocean['ETA Dest'] = $ocean['_final_eta'];
+            } else if (!empty($ocean['_eta_dest'])) {
+                if (strpos($ocean['_eta_dest'], "-") > 0) {
+                    $ocean['ETA Dest'] = substr($ocean['_eta_dest'], 5, 2) . "/" . substr($ocean['_eta_dest'], 8, 2) . "/" . substr($ocean['_eta_dest'], 0, 4);
+                } elseif (strpos($ocean['_eta_dest'], "/") > 0) {
+                    $ocean['ETA Dest'] = $ocean['_eta_dest'];
+                } else {
+                    $ocean['ETA Dest'] = substr($ocean['_eta_dest'], 4, 2) . "/" . substr($ocean['_eta_dest'], 6, 2) . "/" . substr($ocean['_eta_dest'], 0, 4);
+                }
+            } else {
+                if (!empty($ocean['_m_eta']))
+                    $ocean['ETA Dest'] = utils::calculate_ETA_Des($serial_no);
+            }
+
+            // most update status
+            $_schemas = $_REQUEST["_schemas"];
+            $mostStatusSql = "select last_status_loc, last_status_city, to_char(last_status_315_date, 'MM/DD/YYYY') as last_status_315_date,last_status_315_code "
+                    . ", fport_of_loading_un, mport_of_discharge_un, place_of_receipt_un, place_of_delivery_un FROM public.online_ocean "
+                    . "where serial_no= '" . $ocean["serial_no"] . "'";
+            if (!empty($_schemas)) {
+                $mostStatusSql .= " and order_from='" . $_schemas . "'";
+            }
+            $mostStatus = common::excuteObjectSql($mostStatusSql);
+            $state = -1;
+            if (!empty($mostStatus["last_status_315_code"])) {
+                $desc = $mostStatus["last_status_315_code"] . "(" . common::getStatusDesc($mostStatus["last_status_315_code"]) . "): " . $mostStatus["last_status_315_date"];
+                $mostStatus = $desc;
+                $state = common::getStatusStage($mostStatus["last_status_315_code"]);
+            }
+
+            //请求地图是需要的参数
+            $uncode = "'";
+            if ($mostStatus["place_of_receipt_un"] != $mostStatus["fport_of_loading_un"]) {
+                $uncode .= $mostStatus["place_of_receipt_un"];
+            }
+            $uncode .= "'|'" . $mostStatus["fport_of_loading_un"] . "'|'" . $mostStatus["mport_of_discharge_un"] . "'|'";
+            if ($mostStatus["mport_of_discharge_un"] != $mostStatus["place_of_delivery_un"]) {
+                $uncode .= $mostStatus["place_of_delivery_un"];
+            }
+            $uncode .= "'";
+        }
+        //处理shipment data 暂时写死
+        $simplexData = array();
+        $simplexData[] = array("index" =>1,"label" =>"Place of Receipt",
+            "path" =>$ocean['place_of_receipt_exp']."/".$ocean['place_of_receipt'],"isArrival" =>$state == 1 ? true : false);
+
+        $simplexData[] = array("index" =>2,"label" =>"Port of Loading",
+            "path" =>$ocean['fport_of_loading_exp_exp']."/".$ocean['fport_of_loading_exp'],"isArrival" =>$state == 2 ? true : false,
+            "children" =>array(array("label" =>"Cargo arrival at Origin","date" =>"2024-02-01"),array("label" =>"'Departure","date" =>"2024-02-01")));
+
+        $simplexData[] = array("index" =>3,"label" =>"Port of Discharge",
+            "path" =>$ocean['mport_of_discharge_exp']."/".$ocean['mport_of_discharge'],"isArrival" =>$state == 3 ? true : false,
+            "children" =>array(array("label" =>"ETA","date" =>"2024-02-01")));
+
+        $simplexData[] = array("index" =>4,"label" =>"Place of Delivery",
+            "path" =>$ocean['place_of_delivery_exp']."/".$ocean['place_of_delivery'],"isArrival" =>$state == 4 ? true : false);
+
+
+        //处理transportInfo信息数据
+        $transportInfo = array("Tracking No." =>$ocean['tracking_no'],"status"=>$status,"mode" => "","origin" =>$ocean['origin_station'],"destination" =>$ocean['destination_station'],
+            "etd" =>$ocean['f_etd'],"atd" =>"","eta" =>$ocean['m_eta'],"ata" =>"");
+
+        //处理basicInfo信息数据
+        $vessel = utils::outDisplayForMerge($ocean['f_vessel'],$ocean['m_vessel']);
+        $voyage = utils::outDisplayForMerge($ocean['f_voyage'],$ocean['m_voyage']);
+        $basicInfo = array("MAWB/MBL No." =>$ocean['m_bol'],"HAWB/HBOL" => $ocean['h_bol'],"Carrier_Booking_No" =>$ocean['carrier_booking'],
+            "PO_NO" =>$ocean['po_no'],"Vessel/Airline" =>$vessel,"Voyage/Filght" =>$voyage,
+            "Incoterm" =>$ocean['terms'],"Service_Type" =>$ocean['service']);
+
+        //处理 拼接地址 ocean表单exp 字段无法精准分割电话和地址信息,只能从contacts表里查询
+        $shipper_address = $this->retStationInfo($ocean['sh_address_1'], $ocean['sh_address_2'], $ocean['sh_address_3'], $ocean['sh_address_4'], 
+            $ocean['sh_city'], $ocean['sh_state'], $ocean['sh_zipcode'], $ocean['sh_country']);
+        $consignee_address = $this->retStationInfo($ocean['cn_address_1'], $ocean['cn_address_2'], $ocean['cn_address_3'], $ocean['cn_address_4'], 
+            $ocean['cn_city'], $ocean['cn_state'], $ocean['cn_zipcode'], $ocean['cn_country']);
+        $origin_address = $this->retStationInfo($ocean['aa_address_1'], $ocean['aa_address_2'], $ocean['aa_address_3'], $ocean['aa_address_4'], 
+            $ocean['aa_city'], $ocean['aa_state'], $ocean['aa_zipcode'], $ocean['aa_country']); 
+        $destination_address = $this->retStationInfo($ocean['dd_address_1'], $ocean['dd_address_2'], $ocean['dd_address_3'], $ocean['dd_address_4'], 
+            $ocean['dd_city'], $ocean['dd_state'], $ocean['dd_zipcode'], $ocean['dd_country']);    
+
+        $shipperPartners = array("company" =>$ocean['sh_company'],"address"=>$shipper_address,"phone"=>$ocean['sh_phone']);
+        $consigneePartners = array("company" =>$ocean['cn_company'],"address"=>$consignee_address,"phone"=>$ocean['cn_phone']);
+        $originPartners = array("company" =>$ocean['aa_company'],"address"=>$origin_address,"phone"=>$ocean['aa_phone']);
+        $destinationPartners = array("company" =>$ocean['dd_company'],"address"=>$destination_address,"phone"=>$ocean['dd_phone']);
+        $businessPartners = array("shipper"=>$shipperPartners,"consignee" => $consigneePartners,"origin" => $originPartners,"destination" => $destinationPartners);
+        
+         //todo 不确定信息
+         $packing = array("Quantity/Unit"=>"47 CTN","G. Weight" => "480.25 KGS","Ch. Weight" => "689.26 KGS","Volume" => "3.801 CBM");
+
+         //处理routes 
+        $routes = array(array("mode" =>"Sea", "origin" =>$ocean['origin_station'],
+        "destination" => $ocean['destination_station'], "etd" => $ocean['f_etd'],"atd" => "",
+        "eta" =>$ocean['m_eta'],"ata" =>"","vessel" =>$vessel,"voyageNo" =>$voyage));    
+
+         //处理ocean_reference
+         $ref_no = array();
+         $ref_arr = common::excuteListSql("select * from ocean_reference where lower(serial_no) = '" . strtolower($serial_no) . "'");
+         if(!empty($ref_arr)){
+             foreach($ref_arr as  $ref) {
+                 $ref_no[] = array("label"=>$ref["ref_code"],"value"=>$ref["ref_value"]);
+             }
+         }
+
+         //处理marksAndDescription
+         $marksAndDescription = array("marks"=>$ocean['marks'],"description"=>$ocean['description']);
+        
+        //配置Ocean_Container字段 UI 需要的字段有:Container.no Packing,quantity,Gross weight(kg),Gross weight(LB),CBM,seal#,size.service
+        //处理Container
+        $ocean_container_column = array();
+        $container_column = column::getInstance()->getDisplayColumnAll('Ocean_Container');
+        foreach($container_column as $cc){
+            $ocean_container_column[] =array("field" =>$cc['database_column_name'],"title" =>$cc['name'],"formatter" =>"","type" =>"normal");
+        }
+        $sql = "SELECT " . column::getInstance()->getSearchSql('Ocean_Container') . " from oc_container where lower(serial_no) = '" . strtolower($serial_no) . "'";
+        $rss = common::excuteListSql($sql);
+        foreach ($rss as $key => $rs) {
+            //特殊处理weight
+            if(!empty($rss[$key]['grs_kgs'])){
+                $rss[$key]['grs_kgs'] = $rs['grs_kgs']."KG";
+            }
+            if(!empty($rss[$key]['grs_lbs'])){
+                $rss[$key]['grs_lbs'] = $rs['grs_lbs']."LB";
+            }
+        }
+        $containers = array("container_column"=>$ocean_container_column,"container_data" =>$rss);
+       
+        /* Container Status */
+        //数据库里配置好
+        $sql = "SELECT " . column::getInstance()->getSearchSql('Ocean_Container_Status') . " from oc_container_v where lower(serial_no) = '" . strtolower($serial_no) . "'";
+        $rss = common::excuteListSql($sql);
+        $containerStatusData = array();
+        if (!empty($rss)) {
+            //Container_Status 新版只显示几个状态, CTNR# EE I AE VD VA
+            $container_status_column = array("EE","I","AE","VD","VA");
+            foreach ($rss as $rsk => $rs) {
+                $containerStatusDataTemp = array();
+                $content = array();
+                //新UI 还有站点取值,但不清楚取的什么值,CN,SHK 暂时写死
+                foreach($container_status_column as $status){
+                    $dec = common::excuteOneSql("select description from ra_online_edi_event where ra_name = '" . $status . "'");
+                    $status = strtolower($status);
+                    $content[] = array("title" =>$dec,"date"=>common::date2usdate($rs[$status]),"country"=>"CN,SHK");
+                }
+
+                $containerStatusDataTemp['label'] = $rs['ctnr']." / ".$rs['size'];
+                $containerStatusDataTemp['content'] = $content;
+                $containerStatusData[] = $containerStatusDataTemp;
+            }
+        }
+
+        //Milestones info  列名固定
+        $Milestones_column = array();
+        $Milestones_column[] = array("title" =>"Milestones","field" =>"milestones","formatter" =>"","type" =>"normal");
+        $Milestones_column[] = array("title" =>"Date Time","field" =>"date_time","formatter" =>"","type" =>"normal");
+        $Milestones_column[] = array("title" =>"Locations","field" =>"locations","formatter" =>"","type" =>"normal");
+        $Milestones_column[] = array("title" =>"Remarks","field" =>"remarks","formatter" =>"","type" =>"normal");
+        //假数据
+        $Milestones_data = array(array("milestones"=>"booking submit","date_time"=>"2024-02-21","locations" => "china", "remarks" =>""));
+        $Milestones = array("Milestones_column"=>$Milestones_column,"Milestones_data" =>$Milestones_data);
+
+        //页面固定写死的信息
+        $document_column = array();
+        $document_column[] = array("title" =>"File Type","field" =>"file_type","formatter" =>"","type" =>"normal");
+        $document_column[] = array("title" =>"File","field" =>"file","formatter" =>"","type" =>"normal");
+
+        $document_data = array();
+        $document = _getViewDocType($_REQUEST["_schemas"]);
+        $OutFileURL = common::excuteOneSql("select item_value from config where item='OutFileURL'");
+
+        $ocean_can_view_file = common::excuteOneSql("select ocean_can_view_file from ra_online_user where lower(user_login)='".strtolower($_SESSION['ONLINE_USER']['user_login'])."'");
+        if (!empty($document)) {
+            foreach ($document as $v) {
+                $file_type = $v['display_name'];
+                $file_arr =  $this->getFileByHbol($ocean['_m_bol'], $ocean['_h_bol'], $v['serial_no'], $v['m_h'], $v['display_name'], TRUE,$ocean['_job_bol']) ;
+
+                $tar = json_decode($ocean_can_view_file,true);
+
+                if(!empty($tar[$v['display_name']])){
+                    foreach ($tar[$v['display_name']] as $dkey => $dvalue) {
+                        switch ($v['display_name']) {
+                            case 'HBL':
+                                $sql = "SELECT from_system,serial_no,file_path, file_name, upload_by, to_char(upload_date, 'MM/DD/YYYY') as upload_date
+                                        from ra_online_doc_upload
+                                        where lower(bol) = lower('".$ocean['_h_bol']."') and lower(format_serailno) in ('".strtolower(str_replace(";","','",$dvalue['value']))."')  and upper((string_to_array((string_to_array(file_name,'.'))[1], '_'))[2]) = '".$dvalue['type']."'
+                                        order by id desc";
+                                break;
+                            case 'MBL':
+                                $sql = "SELECT from_system,serial_no,file_path, file_name, upload_by, to_char(upload_date, 'MM/DD/YYYY') as upload_date
+                                        from ra_online_doc_upload
+                                        where ( lower(bol) = lower('".strtolower($ocean['_m_bol'])."') or lower(bol) = lower('".strtolower($ocean['_job_bol'])."')) and lower(format_serailno) in ('".strtolower(str_replace(";","','",$dvalue['value']))."')  and upper((string_to_array((string_to_array(file_name,'.'))[1], '_'))[2]) = '".$dvalue['type']."'
+                                        order by id desc";
+                                break;
+                            case 'Others':
+                                $sql = "SELECT from_system,serial_no,file_path, file_name, upload_by, to_char(upload_date, 'MM/DD/YYYY') as upload_date
+                                        from ra_online_doc_upload
+                                        where (lower(bol) = lower('".strtolower($ocean['_h_bol'])."') or lower(bol) = lower('".strtolower($ocean['_m_bol'])."') or lower(bol) = lower('".strtolower($ocean['_job_bol'])."')) and lower(format_serailno) in ('".strtolower(str_replace(";","','",$dvalue['value']))."')  and upper((string_to_array((string_to_array(file_name,'.'))[1], '_'))[2]) = '".$dvalue['type']."'
+                                        order by id desc";
+                                break;
+                            default:
+                                $sql = "";
+                                break;
+                        }
+
+                        if (!empty($sql)) {
+                            $rss = common::excuteListSql($sql);
+                            foreach ($rss as $rs) {
+                                if ($rs['from_system']=="TOPOCEAN"||$rs['from_system']=="KSMART") {
+                                    $file_arr[] = array("url"=>$OutFileURL."/download.php?_schemas=&a=".base64_encode(base64_encode($rs['serial_no'])),
+                                        "file_name" => $rs['file_name'],
+                                        "detail"=>$rs['upload_date'],
+                                        "can_delete"=>_getLoginName() == $rs['upload_by']);
+                                }else{
+                                    $file[] = array("url"=>"main_new_version?action=ocean_order&operate=download&url=". (common::deCode($rs['file_path'] . DS . $rs['file_name'], 'E')),
+                                        "file_name" => $rs['file_name'],
+                                        "detail"=>$rs['upload_date'],
+                                        "can_delete"=>_getLoginName() == $rs['upload_by']);
+                                }
+                            }
+                        }
+                    }
+
+                }
+                //$document_data[] = array("file_type"=>$file_type,"file"=>$file_arr);
+                //按现在的逻辑,有值才会显示
+                foreach($file_arr as $f){
+                    $document_data[] = array("file_type"=>$file_type,"file"=>$f);
+                }
+            }
+        }
+        $document_info = array("document_column"=>$document_column,"document_data" =>$document_data);
+
+
+        $emailRecords = $this->getCommunicationNew($ocean["serial_no"]);
+        $cc_email = common::excuteOneSql("select cc_email from public.online_ocean_communication where email_uuid='" . $ocean["serial_no"] . "' order by id desc limit 1");
+        $email = $this->getEmail($ocean["serial_no"]);
+        $email['cc_email'] = $cc_email;
+        $email['emailRecords'] = $emailRecords;
+
+        global $_COPYRIGHT;
+        $data = array('transportInfo' => $transportInfo, 
+                        'basicInfo' => $basicInfo,
+                        'businessPartners' => $businessPartners,
+                        'ref_no' => $ref_no,
+                        'packing' => $packing,
+                        'marksAndDescription' => $marksAndDescription,
+                        'containers' => $containers,
+                        'simplexData' =>$simplexData,
+                        'containerStatusData' => $containerStatusData,
+                        'document_info' => $document_info,
+                        'containers' => $containers,
+                        'Milestones' => $Milestones,
+                        'routes' => $routes,
+                        'email' => $email,
+                        'ams_ss' =>  md5(md5($ocean['serial_no'])),
+                        'isf_ss' => $isf_ss,
+                        '_schemas' =>$_schemas,
+                        'can_upload_doc' => strtolower($_SESSION['ONLINE_USER']['can_upload_doc']) == 't' || strtolower($_SESSION['ONLINE_USER']['can_view_doc']) == 't',
+                        'canEdiVgm' => _canEdiVgm(),
+                        'copyright' =>$_COPYRIGHT);
+        common::echo_json_encode(200,$data);                
+        exit(); 
+    }
+
+    private function _ocean_excel() {
+        //现在下载交给前端,后台最后只返回全部字段的列,
+        $allColumn = column::getInstance()->getDisplayColumnAll('Ocean_Search');
+        $allBookingColumns = column::getInstance()->tableColumns('Ocean_Search',$allColumn);
+        common::echo_json_encode(200,array("msg"=>"success","allColums" => $allBookingColumns));
+        exit;
+    }
+    
+    private function _ams_isf_log(){
+        global $cbpdb;
+        $ams_ss = $_POST['ams_ss'];
+        $isf_ss = $_POST['isf_ss'];
+
+        $amsLog = array();
+        //页面固定写死的信息
+        $amsLog_column = array();
+        $amsLog_column[] = array("title" =>"Date Time","field" =>"atime","formatter" =>"","type" =>"normal");
+        $amsLog_column[] = array("title" =>"Code","field" =>"cbperrorcode","formatter" =>"","type" =>"normal");
+        $amsLog_column[] = array("title" =>"Name","field" =>"isams_submit","formatter" =>"","type" =>"normal");
+        $amsLog_column[] = array("title" =>"Description","field" =>"amslog","formatter" =>"","type" =>"normal");
+        $amsLog["amsLog_column"] = $amsLog_column;
+        $amsLog["msg"] = "Origin have not filed ACE-M1, no data found";
+        $amsLog["data"] = array();
+        if (_canViewAMSLog()) {
+            $s = $ams_ss;
+            $s = "PDLA200127H";
+            if (!empty($s)) {
+                //$cc = $cbpdb->GetAll("select distinct h_bol from ams_information where md5(md5(from_serial_no)) = '" . pg_escape_string($s) . "'");
+                $cc = $cbpdb->GetAll("select distinct h_bol from ams_information where h_bol = '" . pg_escape_string($s) . "'");
+                foreach ($cc as $v){
+                    $amses[] = $cbpdb->GetAll("select * from ams_info where h_bol = '" . pg_escape_string($v['h_bol']) . "'");
+                }
+                //考虑一个情况
+                if (count($amses) > 0) {
+                    $ams = $amses[0];
+                    $carrier_hbol = substr($ams[0]['m_bol'], 4);
+                    $carrier_scac = substr($ams[0]['m_bol'], 0, 4);
+                    if (empty($ams[0]['h_bol'])){
+                        $amsLog["msg"] = "Origin have not filed ACE-M1, no data found";
+                        $amsLog["data"] = array();
+                    }else{
+                        $log = $cbpdb->GetAll("select cbpreplytime as atime, amslog, cbperrorcode, isams_submit 
+                            from v_e_amslog where hbol = '" . pg_escape_string($ams[0]['h_bol']) . "' 
+                            and split_part(stationname, ',', 1) = split_part('" . pg_escape_string($ams[0]['station_name']) . "', ',', 1) 
+                            order by cbpreplytime desc, substr(cbperrorcode, 2, 1) desc");
+
+                        $amsLog["msg"] = "";
+                        $amsLog["data"] = $log;
+                    }
+                }
+            }
+        }
+
+        $isfLog = array();
+        //页面固定写死的信息
+        $isfLog_column = array();
+        $isfLog_column[] = array("title" =>"Date Time","field" =>"atime","formatter" =>"","type" =>"normal");
+        $isfLog_column[] = array("title" =>"Code","field" =>"cbperrorcode","formatter" =>"","type" =>"normal");
+        $isfLog_column[] = array("title" =>"Name","field" =>"isfsubmit","formatter" =>"","type" =>"normal");
+        $isfLog_column[] = array("title" =>"Description","field" =>"isflog","formatter" =>"","type" =>"normal");
+        $isfLog["isfLog_column"] = $isfLog_column;
+        $isfLog["msg"] = "Origin have not filed ISF, no data found";
+        $isfLog["data"] = array();
+        if (_canViewISFLog()) {
+            if (!empty($isf_ss)) {
+                $ss = $isf_ss;
+                $len = strlen($ss);
+                $b = substr($ss, $len - 7) . substr($ss, 0, $len - 7);
+
+                if (empty($b)){
+				    $isfLog["msg"] = "Origin have not filed ISF, no data found";
+                    $isfLog["data"] = array();
+                }else{
+			        $isf = $cbpdb->GetRow("select * from ocean_isf where md5(md5(bol)) = '" . pg_escape_string($b) . "' or md5(md5(substr(bol, 5))) = '" . pg_escape_string($b) . "' order by id desc limit 1");
+                }
+
+                if (!empty($isf)) {
+                    if (!empty($isf['dob'])){
+                        $isf['dob'] = date("m/d/Y", strtotime($isf['dob']));
+                    }       
+                    $msg = $cbpdb->GetAll("select cbpreplytime as atime, isflog, cbperrorcode, isfsubmit, hbol 
+                            from v_e_isflog where (case when coalesce(isf_no, '')<>'' 
+                            then isf_no = '" . pg_escape_string($isf["isf_no"]) . "' else hbol = '" . pg_escape_string($isf["bol"]) . "'  
+                            and stationname = '" . pg_escape_string($isf["station_name"]) . "' end) 
+                            order by cbpreplytime desc, rowid desc");
+                    $isfLog["msg"] = "";
+                    $isfLog["data"] = $msg;
+                }else{
+                    $isfLog["msg"] = "Origin have not filed ISF, no data found";
+                    $isfLog["data"] = array();
+                }
+                    
+            }
+        }
+
+        $data =array("msg"=>"success",
+            "canViewAMSLog" => _canViewAMSLog(),
+            "canViewISFLog" => _canViewISFLog(),
+            "amsLog" =>$amsLog, 
+            "isfLog" =>$isfLog);
+        common::echo_json_encode(200,$data);
+        exit;
+    }
+    
+
+    private function getEmail($serial_no) {
+        return utils::getEmail($serial_no);
+    }
+
+    private function getCommunicationNew($serial_no) {
+        $list = common::excuteListSql("select to_char(add_time, 'MM/dd/yyyy hh24:MI:ss') as add_times, * from public.online_ocean_communication where email_uuid='$serial_no' and refer_id = 0  order by id");
+        $emialRecords =array();
+        foreach ($list as $k => $v) {
+            $msg =array();
+            $msg["name"] = $v["add_by"];
+            $msg["creatTime"] = $v["add_times"];
+            $msg["content"] =  urldecode($v["web_content"]);
+            $emialRecords[] = $msg;
+        }
+        return $emialRecords;
+    }
+
+    private function retStationInfo($address_1,$address_2,$address_3,$address_4,$city,$state,$country,$zipcode){
+        $stationInfo = "";
+        if(!empty($address_1)){
+            $stationInfo .= $address_1;
+        }
+        if(!empty($address_2)){
+            $stationInfo .= " ".$address_2;
+        }
+        if(!empty($address_3)){
+            $stationInfo .= " ".$address_3;
+        }
+        if(!empty($address_4)){
+            $stationInfo .= " ".$address_4;
+        }
+        $temp_str  = "";
+        if(!empty($city)){
+            $temp_str .= $city." ";
+        }
+        if(!empty($state)){
+            $temp_str .= $state." ";
+        }
+        if(!empty($zipcode)){
+            $temp_str .= $zipcode." ";
+        }
+        if(!empty($country)){
+            $temp_str .= $country." ";
+        }
+        if(!empty($temp_str)){
+            return $stationInfo." ".trim($temp_str);
+        }
+        return $stationInfo;
+    }
+
+    /*
+     * get file by hbol/destination
+     * H:HBL
+     * M: MBL
+     * F: FL
+     * I: C/I & Packing list
+     */
+    private function getFileByHbol($m_bol, $h_bol, $types, $m_bs, $display, $detail = FALSE,$job_no="") {
+        $types = strtolower($types);
+        $types = explode(";", $types);
+        $m_bs = explode(";", $m_bs);
+        $otheres = NULL;
+
+        $filefilter = " ('TELEX') ";//过滤掉类型,单独配置 3537
+        $OutFileURL = common::excuteOneSql("select item_value from config where item='OutFileURL'");
+        $file = array();
+        foreach ($types as $k => $type) {
+            $m_b = $m_bs[$k];
+            if (strtolower($m_b) == 'm')
+                $sql = "SELECT from_system,serial_no,file_path, file_name, upload_by, to_char(upload_date, 'MM/DD/YYYY') as upload_date from ra_online_doc_upload where (lower(bol) = '" . strtolower($m_bol) . "' or lower(bol) ='".strtolower($job_no)."' ) and lower(format_serailno) = '$type' and upper(coalesce((string_to_array((string_to_array(file_name,'.'))[1], '_'))[2],'')) not in ".$filefilter." order by id desc";
+            if (strtolower($m_b) == 'h')
+                $sql = "SELECT from_system,serial_no,file_path, file_name, upload_by, to_char(upload_date, 'MM/DD/YYYY') as upload_date from ra_online_doc_upload where lower(bol) =  '" . strtolower($h_bol) . "' and lower(format_serailno) = '$type' and upper(coalesce((string_to_array((string_to_array(file_name,'.'))[1], '_'))[2],'')) not in ".$filefilter." order by id desc";
+            if (strtolower($m_b) == 'a')
+                $sql = "SELECT from_system,serial_no,file_path, file_name, upload_by, to_char(upload_date, 'MM/DD/YYYY') as upload_date from ra_online_doc_upload where (lower(bol) = '" . strtolower($m_bol) . "' or lower(bol) = '" . strtolower($h_bol) . "' or lower(bol) ='".strtolower($job_no)."') and lower(format_serailno) = '$type' and upper(coalesce((string_to_array((string_to_array(file_name,'.'))[1], '_'))[2],'')) not in ".$filefilter." order by id desc";
+            if (!empty($sql)) {
+                $rss = common::excuteListSql($sql);
+                foreach ($rss as $rs) {
+                    if ($rs['from_system']=="TOPOCEAN"||$rs['from_system']=="KSMART") {
+                        $file[] = array("url"=>$OutFileURL.'/download.php?_schemas=&a='.base64_encode(base64_encode($rs['serial_no'])),
+                            "file_name" => $rs['file_name'],
+                            "detail"=>$rs['upload_date'],
+                            "can_delete"=>_getLoginName() == $rs['upload_by']);
+                    }else {
+                        $file[] = array("url"=>"main_new_version?action=ocean_order&operate=download&url=". (common::deCode($rs['file_path'] . DS . $rs['file_name'], 'E')),
+                        "file_name" => $rs['file_name'],
+                        "detail"=>$rs['upload_date'],
+                        "can_delete"=>_getLoginName() == $rs['upload_by']);
+                    }
+                }
+            }
+        }
+        return $file;
+    }
+
+    /*
+     * download file
+    */
+    private function _download() {
+        $url = common::deCode($_GET['url'], 'D');
+        common::download_file($url);
+    }
+    
+}
+
+?>

+ 122 - 0
service/operation_log.class.php

@@ -0,0 +1,122 @@
+<?php
+
+if (!defined('IN_ONLINE')) {
+    exit('Access Denied');
+}
+
+/**
+ * Description of operation_log
+ *
+ * @author Administrator
+ */
+class operation_log{
+
+    private static $_operation_log;
+
+    function __construct() {  
+       
+    }
+
+    public static function getInstance() {
+        global $memory_limit;
+        $memory_limit = ini_get("memory_limit");
+        ini_set("memory_limit", '2048M');
+        if (!self::$_operation_log) {
+            $c = __CLASS__;
+            self::$_operation_log = new $c;
+        }
+        return self::$_operation_log;
+    }
+    public function operation_log() {
+        $operate = utils::_get('operate');
+        $operate = strtolower($operate);
+
+        /*
+         * index page
+         */
+        if (empty($operate)) {
+            $column = column::getInstance()->getDisplayColumn('Operation_Search');
+            $OperationTableColumns = column::getInstance()->tableColumns('Operation_Search',$column);
+            $data['OperationTableColumns'] = $OperationTableColumns;
+            common::echo_json_encode(200,$data);
+            exit();
+        }
+        /*
+         * operation_search search
+         */
+        if ($operate == "search") {
+            $this->_operation_search();
+        }
+    }
+
+    /*
+    * operation_search search
+    */
+    private function _operation_search() {
+        $cp = common::check_input($_POST ['cp']); //current_page
+        $ps = common::check_input($_POST ['ps']); //ps
+        if (empty($ps))
+            $ps = 10;
+
+        $sqlWhere = ' where 1=1';
+        $user_name = common::check_input($_POST ['user_name']); 
+        $user_type = common::check_input($_POST ['user_type']); 
+        $page = common::check_input($_POST ['page']);
+        $operation = common::check_input($_POST ['operation']); 
+        if (!empty($user_name)){
+            $sqlWhere .= " and user_name ilike '%" . $user_name . "%'";
+        }
+        if (!empty($user_type)){
+            $sqlWhere .= " and lower(user_type) = '".strtolower($user_type)."'";
+        }
+        if (!empty($page)){
+            $sqlWhere .= " and lower(page) = '".strtolower($page)."'";
+        }
+        if (!empty($operation)){
+            $sqlWhere .= " and lower(operation) = '".strtolower($operation)."'";
+        }
+
+        if (isset($_POST['operation_date_start']) && !empty($_POST['operation_date_start']))
+            $sqlWhere .= " and operation_time >= '" . common::usDate2sqlDate($_POST['operation_date_start']) . " 00:00:00'";
+        if (isset($_POST['operation_date_end']) && !empty($_POST['operation_date_end']))
+            $sqlWhere .= " and operation_time <= '" . common::usDate2sqlDate($_POST['operation_date_end']) . " 23:59:59'";
+
+        $rc = $_POST ['rc'];
+        if ($rc == - 1) {
+            $sql = "SELECT count(1) from public.customer_service_operation_log" . $sqlWhere;
+            $rc = common::excuteOneSql($sql);
+        }
+        $tp = ceil($rc / $ps);
+        $order_by = " id";
+        if ($rc > 0) {
+            $sql = "SELECT * from public.customer_service_operation_log " . $sqlWhere . 
+                        " order by $order_by limit " . $ps . " offset " . ($cp - 1) * $ps;
+            $rs = common::excuteListSql($sql);
+
+            //处理operation_detail 可以放在保存的时候做(待定)
+            foreach($rs as $key => $val){
+                $json = $val['operation_detail'];
+                if(!empty($json)){
+                    $_text = '';
+                    $data = json_decode($json,true);
+                    foreach ($data as $jk => $jv) {
+                        $_text .= $jk.":".$jv."; ";
+                    }
+                    $rs[$key]["operation_detail"] = $_text;
+                }
+            }
+
+            $arrTmp = array('searchData' => $rs, 
+               'rc' => $rc,
+               'ps' => $ps,
+               'cp' => $cp,
+               'tp' => $tp);
+        } else {
+           $arrTmp = array('searchData' => array());
+        }
+        common::echo_json_encode(200,$arrTmp);
+        exit();
+    }  
+}
+
+?>

+ 191 - 0
service/search.class.php

@@ -0,0 +1,191 @@
+<?php
+
+if (!defined('IN_ONLINE')) {
+    exit('Access Denied');
+}
+
+class search {
+
+    private static $_search;
+
+    public static function getInstance() {
+        if (!self::$_search) {
+            $c = __CLASS__;
+            self::$_search = new $c;
+        }
+        return self::$_search;
+    }
+    
+     public function getDisplaySearch($model_name, $ids = "") {
+        $rs = null;
+        if (!empty($ids)) {
+            $rs = $ids;
+        } else {
+            $sql = "select ids from public.ra_online_search_config where lower(login_name)='" . strtolower(_getLoginName()) . "' and lower(model_name) = '" . strtolower($model_name) . "'";
+            $rs = common::excuteOneSql($sql);
+            if (empty($rs)) {
+                $sql = "select array_to_string(array(select id from public.ra_online_search where active = true and default_display = true and lower(model_name) = '" . strtolower($model_name) . "'";
+                if (_isCustomerLogin())
+                    $sql .= " and customer_display = true";
+                $sql .= " order by order_by asc, search_name asc), ',')";
+                $rs = common::excuteOneSql($sql);
+            }
+        }
+        $result = "";
+        $sql = $this->_getSql($rs, "html_value, value_name, search_condition, value_name");
+        $rss = common::excuteListSql($sql);
+        foreach ($rss as $key => $value) {
+            if ($value['search_condition'] == "year") {
+                $result .= '<div class="modules3">Year : <input  name="' . $value['value_name'] . '_start" id="' . $value['value_name'] . '_start" type="text" oninput = "value=value.replace(/[^\d]/g,\'\')" value=""><div class="line"> - </div>
+                    <input name="' . $value['value_name'] . '_end" id="' . $value['value_name'] . '_end" type="text" oninput = "value=value.replace(/[^\d]/g,\'\')" value=""></div>';
+            } else {
+                $result .= $value['html_value'];
+            }
+        }
+        return $result;
+    }
+
+
+    public function _getSql($ids, $str) {
+        $ids_arr = explode(',', $ids);
+        $sql = "";
+        foreach ($ids_arr as $value) {
+            if (!empty($value)) {
+                if (empty($sql)) {
+                    $sql .= "SELECT $str FROM public.ra_online_search_cso where id = " . $value;
+                    if (_isCustomerLogin())
+                        $sql .= ' and customer_display = true';
+                } else {
+                    $sql .= " union all SELECT $str FROM public.ra_online_search_cso where id = " . $value;
+                    if (_isCustomerLogin())
+                        $sql .= ' and customer_display = true';
+                }
+            }
+        }
+        return $sql;
+    }
+
+    public function saveSettingDisplay($newid, $model_name) {
+        $login_name = _getLoginName();
+        if ($this->checkUserDisplaySetting($model_name) === TRUE) {
+            $sql = "UPDATE public.ra_online_search_config SET ids = '" . common::check_input($newid) . "' WHERE lower(model_name) = '" . common::check_input(strtolower($model_name)) . "' AND lower(login_name) = '" . common::check_input(strtolower($login_name)) . "'";
+        } else {
+            $sql = "INSERT INTO public.ra_online_search_config (login_name, model_name, ids) VALUES ('" . common::check_input($login_name) . "', '" . common::check_input($model_name) . "', '" . common::check_input($newid) . "')";
+        }
+        common::excuteUpdateSql($sql);
+    }
+
+    /*
+     * check user had setting display
+     */
+
+    public function checkUserDisplaySetting($model_name) {
+        $login_name = _getLoginName();
+        $sql = "select ids from public.ra_online_search_config where lower(login_name)='" . strtolower($login_name) . "' and lower(model_name) = '" . strtolower($model_name) . "'"; //check login_name is setting
+        $rs = common::excuteObjectSql($sql);
+        if (!empty($rs)) {
+            return TRUE;
+        }
+        return FALSE;
+    }
+
+    public function getSearchSQL($model_name) {
+        $sql = "select ids from public.ra_online_search_config_cso where lower(login_name)='" . strtolower(_getLoginName()) . "' and lower(model_name) = '" . strtolower($model_name) . "'";
+        $rs = common::excuteOneSql($sql);
+        if (empty($rs)) {
+            $sql = "select array_to_string(array(select id from public.ra_online_search_cso where active = true and lower(model_name) = '" . strtolower($model_name) . "'";
+            if (_isCustomerLogin())
+                $sql .= " and customer_display = true";
+            $sql .= " order by order_by), ',')";
+            $rs = common::excuteOneSql($sql);
+        }
+        $result = " and 1=1";
+        $sql = $this->_getSql($rs, "value_name, search_condition, is_int");
+        $rss = common::excuteListSql($sql);
+        foreach ($rss as $v) {
+            if ((isset($_POST[$v['value_name']]) && !empty($_POST[$v['value_name']])) || (isset($_POST[$v['value_name'] . '_start']) && !empty($_POST[$v['value_name'] . '_start'])) || (isset($_POST[$v['value_name'] . '_end']) && !empty($_POST[$v['value_name'] . '_end']))) {
+                if (strtolower($model_name) == "booking_search" && (strtolower($v['value_name']) == "transport_mode")) {
+                    //transport_mode todo
+                    
+                } elseif (strtolower($model_name) == "ocean_search" && (strtolower($v['value_name']) == "origin" 
+                    || strtolower($v['value_name']) == "incoterms")){
+                    //这两块特殊处理,可能以后会移除   
+ 
+                } else {
+                    if ($v['search_condition'] == '>=,<=') {
+                        $s = $v['value_name'] . '_start';
+                        $e = $v['value_name'] . '_end';
+                        if (isset($_POST[$s]) && !empty($_POST[$s])) {
+                            $result .= " and " . $v['value_name'] . " >= '" . common::check_input(common::usDate2sqlDate($_POST[$s]) . ' 00:00:00') . "'";
+                        }
+                        if (isset($_POST[$e]) && !empty($_POST[$e])) {
+                            $result .= " and " . $v['value_name'] . " <= '" . common::check_input(common::usDate2sqlDate($_POST[$e]) . ' 23:59:59') . "'";
+                        }
+                    } elseif ($v['search_condition'] == 'year') {
+                        $s = $v['value_name'] . '_start';
+                        $e = $v['value_name'] . '_end';
+                        if (isset($_POST[$s]) && !empty($_POST[$s])) {
+                            $result .= " and " . $v['value_name'] . " >= " . common::check_input($_POST[$s]);
+                        }
+                        if (isset($_POST[$e]) && !empty($_POST[$e])) {
+                            $result .= " and " . $v['value_name'] . " <= " . common::check_input($_POST[$e]);
+                        }
+                    } elseif ($v['search_condition'] == "in") {
+                        $result .= " and lower(" . $v['value_name'] . ") " . common::getInNotInSql($_POST[$v['value_name']]);
+                    } else {
+                        //处理多个输入查询情况包含一个 数组类型,也有可能单个字符串
+                        $value_arr = $_POST[$v['value_name']];
+                        if(!is_array($value_arr)){
+                            $value_arr = array($value_arr);
+                        }
+                        $more_sql = "1<>1";
+                        foreach($value_arr as $value){
+                            //处理合并查询 包含一个
+                            $value_name_arr = explode("/", $v['value_name']);
+                            foreach($value_name_arr as $value_name){
+                                if ($v['is_int'] == 't') {
+                                    $more_sql .= " or " . " " . $value_name . " " . $v['search_condition'] . " " . trim($value);
+                                } elseif ($v['search_condition'] == 'ilike') {
+                                      $more_sql .= " or " . $value_name . " " . $v['search_condition'] . " '" . common::check_input(trim($value)) . "%'";
+                                } elseif ($v['search_condition'] == 'like') {
+                                    $more_sql .= " or " . $value_name . " " . $v['search_condition'] . " '%" . common::check_input(trim($value)) . "%'";
+                                } else {
+                                    $more_sql .= " or " . $value_name . " " . $v['search_condition'] . " '" . common::check_input(trim($value)) . "'";
+                                }
+                            }
+                        }
+                        if ($more_sql <> "1<>1"){
+                            $result .= " and ($more_sql)";
+                        }           
+                    }  
+                }
+            }
+        }
+        return $result;
+    }
+
+    public function getDisplayColumn($model_name, $isin = true) {
+        $rs = null;
+        $sql = "select ids from public.ra_online_search_config where lower(login_name)='" . strtolower(_getLoginName()) . "' and lower(model_name) = '" . strtolower($model_name) . "'";
+        $rs = common::excuteOneSql($sql);
+        if (empty($rs)) {
+            $sql = "select array_to_string(array(select id from public.ra_online_search where active = true and default_display = true and lower(model_name) = '" . strtolower($model_name) . "'";
+            if (_isCustomerLogin())
+                $sql .= " and customer_display = true";
+            $sql .= " order by order_by asc, search_name asc), ',')";
+            $rs = common::excuteOneSql($sql);
+        }
+        if ($isin) {
+            $sql = $this->_getSql($rs, "id, search_name as name");
+            $rss = common::excuteListSql($sql);
+        } else {
+            $sql = "SELECT id, search_name as name FROM public.ra_online_search WHERE active = true and lower(model_name) = '" . strtolower($model_name) . "' and id not in ($rs)";
+            if (_isCustomerLogin())
+                $sql .= ' and customer_display=true';
+            $rss = common::excuteListSql($sql);
+        }
+        return $rss;
+    }
+}
+
+?>