ShuanghongS 1 month ago
parent
commit
7d4b512ef3
2 changed files with 343 additions and 22 deletions
  1. 109 14
      service/report.class.php
  2. 234 8
      utils/common.class.php

+ 109 - 14
service/report.class.php

@@ -335,7 +335,7 @@ class report {
                 $_value_type =  $_field_type == "System" ? "" : (empty($_tempFieldsList['value']) ? "Blank" :"Fixed Value");
                 $_fixed_value = common::check_input($_tempFieldsList['value']);
                 //这两个不能配置查询和过滤
-                if($_field_group_name == 'Container info' || $_field_group_name == 'Milestone'
+                if($_field_group_name == 'Container Status' || $_field_group_name == 'Milestone'
                         ||$_field_code == 'Other reference No.'  || $_field_code == 'Shipper Zip Code' || $_field_code == 'Consignee Zip Code' ){
                     $_is_filter_enabled = "false";
                 } else {
@@ -464,21 +464,26 @@ class report {
                 $dataReturn['sortBy'] =  array("field"=>"","options"=>[],"order"=>"asc");
             }
             
-            $reportFiled = common::excuteObjectSql("select report_sql,count_sql,level from public.kln_report_template where serial_no = '".$serial_no."'");
+            $reportFiled = common::excuteObjectSql("select name,report_sql,count_sql,level from public.kln_report_template where serial_no = '".$serial_no."'");
             $sqlManage = common::excuteObjectSql("select sql,count_sql,level from public.kln_report_sql_manage where level = '".$reportFiled['level']."'");
             $report_sql = $sqlManage["sql"];
-            $count_sql = $sqlManage["count_sql"];
+            //$count_sql = $sqlManage["count_sql"];
 
-            $filterSQLArr = $this->returnFilterSql($filtersList);
+            $filterSQLArr = $this->returnFilterSql_v1($filtersList);
+            $count_sql = common::buildCountSql($filterSQLArr['filterFields'],$reportFiled['level']);
             //return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN);
             $count_sql = str_replace('<{klnOceanSearchKLN}>', $filterSQLArr['klnOceanSearchKLN'], $count_sql);
             $count_sql = str_replace('<{ocItemSearchKLN}>', $filterSQLArr['ocItemSearchKLN'], $count_sql);
             $count_sql = str_replace('<{vvSearchKLN}>', $filterSQLArr['vvSearchKLN'], $count_sql);
+            $count_sql = str_replace('<{orderby}>', "", $count_sql);
+            error_log($reportFiled['name'].": report_detail_count, ".$count_sql);
 
             $report_sql = str_replace('<{klnOceanSearchKLN}>', $filterSQLArr['klnOceanSearchKLN'], $report_sql);
             $report_sql = str_replace('<{ocItemSearchKLN}>', $filterSQLArr['ocItemSearchKLN'], $report_sql);
             $report_sql = str_replace('<{CustomFiled}>', $CustomFiled, $report_sql);
             $report_sql = str_replace('<{vvSearchKLN}>', $filterSQLArr['vvSearchKLN'], $report_sql);
+            $report_sql = str_replace('<{orderby}>', $this->returnSortBySql(), $report_sql);
+            error_log($reportFiled['name'].": report_detail_search, ".$report_sql);
 
             //查询data
             $cp = common::check_input($_POST ['cp']); //current_page
@@ -490,16 +495,12 @@ class report {
             
             $rc = $_POST ['rc'];
             if ($rc == -1) {
-                $count_sql = str_replace('<{orderby}>', "", $count_sql);
-                error_log($count_sql);
                 $rc = common::excuteOneSql($count_sql);
             }
             $tp = ceil($rc / $ps);
             if ($rc > 0) {
-                $report_sql = str_replace('<{orderby}>', $this->returnSortBySql(), $report_sql);
                 $tmp_search_without_limit = $report_sql;
                 $report_sql .= " limit " . $ps . " offset " . ($cp - 1) * $ps;
-                error_log($report_sql);
 
                 $rs = common::excuteListSql($report_sql);
                 $arrTmp = array('searchData' => $rs, 
@@ -682,14 +683,17 @@ class report {
             
             
             //形成sql
-            $schedule_search = common::excuteObjectSql("select schedule_order_field,data_reference_field,data_range_type,
+            $schedule_search = common::excuteObjectSql("select name,level,schedule_order_field,data_reference_field,data_range_type,
                     dynamic_start_offset,dynamic_end_offset,
                     fixed_start_date,fixed_end_date,
                     report_sql,count_sql
                 from public.kln_report_template where  serial_no = '$serial_no'");
 
             $report_sql = $schedule_search["report_sql"];
-            $count_sql = $schedule_search["count_sql"];
+            //$count_sql = $schedule_search["count_sql"];
+
+            $filterFields = [];
+            $count_sql = common::buildCountSql($filterFields,$schedule_search['level']);
 
             //$klnOceanSearchKLN = " where " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
             $klnOceanSearchKLN = " where  created_time > CURRENT_DATE - INTERVAL '1 years' and  " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
@@ -736,11 +740,15 @@ class report {
             $count_sql = str_replace('<{klnOceanSearchKLN}>', $klnOceanSearchKLN, $count_sql);
             $count_sql = str_replace('<{ocItemSearchKLN}>', " ", $count_sql);
             $count_sql = str_replace('<{vvSearchKLN}>', " ", $count_sql);
+            $count_sql = str_replace('<{orderby}>', "", $count_sql);
+            error_log($schedule_search['name'].": report_schedule_count, ".$count_sql);
 
             $report_sql = str_replace('<{klnOceanSearchKLN}>', $klnOceanSearchKLN, $report_sql);
             $report_sql = str_replace('<{ocItemSearchKLN}>', " ", $report_sql);
             $report_sql = str_replace('<{CustomFiled}>', $CustomFiled, $report_sql);
             $report_sql = str_replace('<{vvSearchKLN}>', " ", $report_sql);
+            $report_sql = str_replace('<{orderby}>', $orderby, $report_sql);
+            error_log($schedule_search['name'].": report_schedule_search, ".$report_sql);
 
             //查询sql
             $cp = common::check_input($_POST ['cp']); //current_page
@@ -752,16 +760,12 @@ class report {
            
             $rc = $_POST ['rc'];
             if ($rc == -1) {
-                $count_sql = str_replace('<{orderby}>', "", $count_sql);
-                error_log($count_sql);
                 $rc = common::excuteOneSql($count_sql);
             }
             $tp = ceil($rc / $ps);
             if ($rc > 0) {
-                $report_sql = str_replace('<{orderby}>', $orderby, $report_sql);
                 $tmp_search_without_limit = $report_sql;
                 $report_sql .= " limit " . $ps . " offset " . ($cp - 1) * $ps;
-                error_log($report_sql);
 
                 $rs = common::excuteListSql($report_sql);
                 $arrTmp = array('searchData' => $rs, 
@@ -987,6 +991,97 @@ class report {
         return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN);
     }
 
+    /**
+     * 根据提交的参数动态的拼接Count sql
+     */
+    public function returnFilterSql_v1($filtersList){
+        $klnVipDb = common::getReportRealDBFiled();
+
+        $vvSearchKLN = " where 1=1 ";
+        $klnOceanSearchKLN = " where  created_time > CURRENT_DATE - INTERVAL '1 years' and  " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
+        //$klnOceanSearchKLN = " where   " . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
+        $ocItemSearchKLN = " where 1=1 ";
+
+        $filterFields = array();
+        foreach($filtersList as $fiter){
+            if(!empty($_POST[$fiter['field']])){
+                //这里其实可以改成field_real
+                $key = array_search($fiter['field'], $klnVipDb);
+                $filterFields[] = $fiter['field_real'];
+                if($key !== false){
+                    //找到给key
+                    $temp_sql_where = "";
+                    if ($fiter['data_type'] == "string"){
+                        $temp_sql_where .= " and ".$key." ilike '%". common::check_input($_POST[$fiter['field']])."%'"; 
+                    } elseif ($fiter['data_type'] == "number"){
+                        $temp_arr = $_POST [$fiter['field']];
+                        if(!empty($temp_arr[0])){
+                            $temp_sql_where .= " and ".$key."::numeric >= '". common::check_input($temp_arr[0])."'"; 
+                        }
+                        if(!empty($temp_arr[1])){
+                            $temp_sql_where .= " and ".$key."::numeric <= '". common::check_input($temp_arr[1])."'"; 
+                        } 
+                    } elseif ($fiter['data_type'] == "date"){
+                        $temp_arr = $_POST [$fiter['field']];
+                        if(!empty($temp_arr[0])){
+                            $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
+                            $temp_sql_where .= " and ".$key." >= '". $date_from."'"; 
+                        }
+                        if(!empty($temp_arr[1])){
+                            $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
+                            $temp_sql_where .= " and ".$key." <= '". $date_to."'"; 
+                        }
+                    }
+
+                    if (utils::startWith($key,"oc") || utils::startWith($key,"oi") || utils::startWith($key,"oe") || utils::startWith($key,"co2_r")
+                        || $fiter['field'] == "total_distance"
+                        || $fiter['field'] == "last_mile_delivery"
+                        || $key == "COALESCE(oe.import_po_no,oo.po_no)" 
+                        || $key == "oo._voyage" 
+                        || $key == "oo._vessel"
+                        || $key == "oo.new_status"){
+                        $ocItemSearchKLN .= $temp_sql_where;
+                    } else {
+                        $klnOceanSearchKLN .= $temp_sql_where;
+                    }
+                } else {
+                    //获取POST name  用户去别名得字段,放在vvSearchKLN上
+                    $_post_field = $fiter['field'];
+                    $_post_field = strtolower($_post_field);
+                    $_post_field = preg_replace('/[^a-z0-9]+/', '_', $_post_field); // 非字母数字 → _
+                    $_post_field = trim($_post_field, '_');
+
+                    if ($fiter['data_type'] == "string"){
+                        $vvSearchKLN .= " and \"".$fiter['field_real']."\" ilike '%". common::check_input($_POST [$_post_field])."%'"; 
+                    } elseif ($fiter['data_type'] == "number"){
+                        $temp_arr = $_POST [$_post_field];
+                        if(!empty($temp_arr[0])){
+                            $vvSearchKLN .= " and \"".$fiter['field_real']."\"::numeric >= '". common::check_input($temp_arr[0])."'"; 
+                        }
+                        if(!empty($temp_arr[1])){
+                            $vvSearchKLN .= " and \"".$fiter['field_real']."\"::numeric <= '". common::check_input($temp_arr[1])."'"; 
+                        }  
+                    } elseif ($fiter['data_type'] == "date"){
+                        $temp_arr = $_POST [$_post_field];
+                        //先判断日期字符串是否为空,这里则有做 是因为sql 整合了柜子315时间,和 milestone的时间, 只能text转date
+                        if(!empty($temp_arr[0])){
+                            $date_from = common::check_input(common::usDate2sqlDate($temp_arr[0]) . ' 00:00:00');
+                            $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";  
+                            $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') >= '". $date_from."'"; 
+                        }
+                        if(!empty($temp_arr[1])){
+                            $date_to = common::check_input(common::usDate2sqlDate($temp_arr[1]) . ' 23:59:59');
+                            $vvSearchKLN .= " and COALESCE(\"".$fiter['field_real']."\",''::text)<> ''::text ";  
+                            $vvSearchKLN .= " and to_timestamp(\"".$fiter['field_real']."\", 'MM/DD/YYYY HH24:MI:SS') <= '". $date_to."'"; 
+                        }
+                    }
+                }
+            }
+        }
+        
+        return array("vvSearchKLN"=>$vvSearchKLN,"klnOceanSearchKLN"=>$klnOceanSearchKLN,"ocItemSearchKLN"=>$ocItemSearchKLN,"filterFields"=>$filterFields);
+    }
+
     /**
      * 根据提交的参数动态的拼接sort by sql
      */

+ 234 - 8
utils/common.class.php

@@ -4421,23 +4421,23 @@ class common {
             "oo.h_bol" => "hbol_hawb_no",
             "oo.invoice_no" => "invoice_no",
             "oo.booking_no" => "booking_no",
-            //"oo.po_no"=>"shipment_po_no",
+            "COALESCE(oe.import_po_no,oo.po_no)"=>"shipment_po_no",    //代表oo里的组合字段,需要特殊处理
             "oo.quote_no" => "quote_no",
             "oo.carrier_booking" => "carrier_booking_no",
             "oo.contract" => "contract_no",
             "oo.manifest_hbol" => "manifest_hbol",
             "oo.transport_mode" => "transportation_mode",
             "oo.service" => "service_type",
-            //"oe.manifest_type"=>"shipment_type",
+            "oe.manifest_type"=>"shipment_type",
             "oo.ex_im" => "ex_im",
             "oo.incoterms" => "incoterms",
-            //"oe.loadterm"=>"load_terms",
-            //"oo.status" => "status",
+            "oe.loadterm"=>"load_terms",
+            "oo.new_status" => "status",
             "oo.carbon_emission" => "total_co2_emission",
             "oo.qty" => "shipment_qty",
             "oo.piece_count" => "shipment_gross_weight",
             "oo.weight" => "chargeable_weight",
-            //"oe.volume"=>"shipment_volume",
+            "oe.volume"=>"shipment_volume",
             "oo.shipper" => "shipper",
             "oo.shipper_id" => "shipper_id",
             "oo.consignee" => "consignee",
@@ -4463,8 +4463,8 @@ class common {
             "oo.place_of_delivery_exp" => "place_of_delivery",
             "oo.port_of_transshipment_name" => "port_of_transhipment",
             "oo.carrier" => "carrier",
-            //"oo.voyage"=>"voyage_flight",
-            //"oo.vessel"=>"vessel_airline",
+            "oo._voyage"=>"voyage_flight",    
+            "oo._vessel"=>"vessel_airline",
             "oo.ams_status" => "ace_m1_status",
             "oo.isisf" => "is_isf",
             "oo.obl_set" => "obl_set",
@@ -4484,7 +4484,19 @@ class common {
             "oi.grs_kgs" => "item_weight",
             "oi.vol_cbm" => "item_volume",
             "oi.description" => "description",
-            "oi.inner_pcs" => "inner_pcs"
+            "oi.inner_pcs" => "inner_pcs",
+            "(COALESCE(co2_r.pickup_distances, 0) +COALESCE(co2_r.routes_distances, 0) +COALESCE(co2_r.delivery_distances, 0))" => "total_distance",
+		    "co2_r.pickup_carbon_emission" => "pickup_co2_emission",
+		    "co2_r.pickup_distances" => "pickup_distance",
+		    "co2_r.routes_carbon_emission" => "main_route_co2_emission",
+		    "co2_r.routes_distances" => "main_route_distance",
+		    "co2_r.delivery_carbon_emission" => "delivery_co2_emission",
+		    "co2_r.delivery_distances" => "delivery_distance",
+            "(SELECT  case when coalesce(trim((item.value ->> 'delivery_datetime')),'') <>'' 
+                            then to_timestamp(trim((item.value ->> 'delivery_datetime')), 'YYYY-MM-DD')
+				    else '1997-01-01'::timestamp end 
+			FROM jsonb_array_elements(oe.lmdds) item(value)
+			  WHERE (item.value ->> 'ctnr'::text) = oc.ctnr limit 1) " => "last_mile_delivery"
         ];
         return  $kln_ocean; 
     }
@@ -4736,5 +4748,219 @@ class common {
         // 3. 默认
         return new \DateTimeZone('UTC');
     }
+
+    // 判断某个字段是否属于特定逻辑表
+    // $filterFields = [
+    //     'Description',     // 来自 oi
+    //     'Status',          // 来自 oo
+    //     'Load Terms'       // 来自 oe
+    // ];
+    public static function getRequiredTables(array $filterFields)
+    {
+        $FIELD_TABLE_MAP = [
+        // 主表 oo (kln_ocean)
+        'Status'                     => ['oo'],
+        'Transportation Mode'        => ['oo'],
+        'Voyage/Flight'              => ['oo'],
+        'Vessel/Airline'             => ['oo'],
+        'Container No. (House)'      => ['oo'],
+        'Shipment PO No.'            => ['oo', 'oe'], // 可能来自 oe.import_po_no
+
+        // oc_container
+        'Container No.'              => ['oc'],
+        'Container Size'             => ['oc'],
+        'Container Qty'              => ['oc'],
+        'Container Unit'             => ['oc'],
+        'Container Weight'           => ['oc'],
+        'Container Volume'           => ['oc'],
+        'Container PO No.'           => ['oc'],
+        'Item No.'                   => ['oc'],
+        'Invoice No.'                => ['oc'],
+
+        // oc_container_item (oi)
+        'Item PO No.'                => ['oi'],
+        'SKU NO.'                    => ['oi'],
+        'Item Qty'                   => ['oi'],
+        'Item Unit'                  => ['oi'],
+        'Item Weight'                => ['oi'],
+        'Item Volume'                => ['oi'],
+        'Description'                => ['oi'],
+        'Inner PCS'                  => ['oi'],
+
+        // kln_ocean_extend (oe)
+        'Shipment Type'              => ['oe'],
+        'Container Size (House)'     => ['oe'],
+        'Load Terms'                 => ['oe'],
+
+        // calculate_co2_result (co2_r)
+        'Total Distance'             => ['co2_r'],
+        'Pickup CO2 Emission'        => ['co2_r'],
+        'Pickup Distance'            => ['co2_r'],
+        'Main Route CO2 Emission'    => ['co2_r'],
+        'Main Route Distance'        => ['co2_r'],
+        'Delivery CO2 Emission'      => ['co2_r'],
+        'Delivery Distance'          => ['co2_r'],
+
+        // 特殊字段:依赖 oc + oe
+        'Last Mile Delivery'         => ['oc', 'oe'],
+        ];
+
+        $tables = [];
+
+        foreach ($filterFields as $fieldAlias) {
+            if (isset($FIELD_TABLE_MAP[$fieldAlias])) {
+                foreach ($FIELD_TABLE_MAP[$fieldAlias] as $table) {
+                    $tables[$table] = true;
+                }
+            }
+        }
+
+        return array_keys($tables); // e.g., ['oo', 'oi']
+    }
+
+    public static function buildCountSql(array $filterFieldAliases,$level)
+    {
+        $requiredTables = common::getRequiredTables($filterFieldAliases);
+
+        // 是否需要容器/项数据(即区分 public / sfs)
+        $needContainerData = in_array('oc', $requiredTables);
+        $needItemData = in_array('oi', $requiredTables);
+        $needOceanExtend   = in_array('oe', $requiredTables) || in_array('Last Mile Delivery', $filterFieldAliases);
+        $needCO2           = in_array('co2_r', $requiredTables);
+
+        //在根据层级分配是否需要字段
+        if($level == 'Container Level'){
+            $needContainerData = true;
+        }elseif($level == 'Item Level'){
+            $needItemData = true;
+            $needContainerData = true;
+        }
+
+        // --- CTE: oo (主表) ---
+        $sql = "
+        with oo as (
+            SELECT CASE
+                        WHEN (m_iffcpu is null and m_iffrec is null and m_iffdep is null and m_iffarr is null and m_iffdel is null) THEN 'Created'::text
+                        WHEN ((m_iffcpu is not null or m_iffrec is not null) and m_iffdep is null and m_iffarr is null and m_iffdel is null) THEN 'Cargo Received'::text
+                        WHEN (m_iffdep is not null and m_iffarr is null and m_iffdel is null) THEN 'Departed'::text
+                        WHEN (m_iffarr is not null and m_iffdel is null) THEN 'Arrived'::text
+                        WHEN (m_iffdel is not null) THEN 'Completed'::text
+                        ELSE 'Created'
+                    END AS new_status,
+                    CASE
+                        WHEN transport_mode_extend = 'sea' THEN 'Ocean Freight'::text
+                        WHEN transport_mode_extend = 'air' THEN 'Air Freight'::text
+                        WHEN transport_mode_extend = 'rail' THEN 'Rail Freight'::text
+                        WHEN transport_mode_extend = 'road' THEN 'Road Freight'::text
+                        ELSE ''
+                    END AS new_transport_mode_extend,
+                    CASE
+                        WHEN oo.voyage IS NOT DISTINCT FROM oo.f_voyage THEN oo.voyage
+                        WHEN NULLIF(TRIM(oo.voyage), '') IS NOT NULL AND NULLIF(TRIM(oo.f_voyage), '') IS NOT NULL
+                            THEN oo.f_voyage || '/' || oo.voyage
+                        WHEN NULLIF(TRIM(oo.voyage), '') IS NOT NULL
+                            THEN oo.voyage
+                        ELSE oo.f_voyage
+                    END AS _voyage,
+                    CASE
+                        WHEN oo.vessel IS NOT DISTINCT FROM oo.f_vessel THEN oo.vessel
+                        WHEN NULLIF(TRIM(oo.vessel), '') IS NOT NULL AND NULLIF(TRIM(oo.f_vessel), '') IS NOT NULL
+                            THEN oo.f_vessel || '/' || oo.vessel
+                        WHEN NULLIF(TRIM(oo.vessel), '') IS NOT NULL
+                            THEN oo.vessel
+                        ELSE oo.f_vessel
+                    END AS _vessel, * FROM public.kln_ocean oo  <{klnOceanSearchKLN}>
+        )";
+
+        // 如果不需要容器/项数据,直接 COUNT
+        if (!$needContainerData) {
+            return $sql . "\n select count(*) from oo <{ocItemSearchKLN}> ;";
+        }
+
+        // --- 需要容器数据:构建 vv_public 和 vv_sfs ---
+
+        // 构建 LATERAL 子查询(按需)
+        $oeLateral = '';
+        if ($needOceanExtend) {
+            $oeLateral = "
+                LEFT JOIN LATERAL (
+                    SELECT 
+                        loadterm,
+                        manifest_type,
+                        container_size,
+                        import_po_no,
+                        (SELECT jsonb_agg(to_jsonb(de.*)) FROM (
+                            SELECT 
+                                split_part(lmd, '/', 1) AS ctnr,
+                                split_part(lmd, '/', 2) AS delivery_datetime
+                            FROM regexp_split_to_table(COALESCE(oe.last_mile_delivery_date, ''), ';') AS lmd
+                            WHERE lmd <> ''
+                        ) de) AS lmdds
+                    FROM public.kln_ocean_extend oe 
+                    WHERE oe.serial_no::text = oo.serial_no::text 
+                    AND oe.order_from::text = oo.order_from::text 
+                    LIMIT 1
+                ) oe ON true";
+        }
+
+        $co2Lateral = '';
+        if ($needCO2) {
+            $co2Lateral = "
+                LEFT JOIN LATERAL (
+                    SELECT 
+                        pickup_carbon_emission,
+                        pickup_distances,
+                        routes_carbon_emission,
+                        routes_distances,
+                        delivery_carbon_emission,
+                        delivery_distances
+                    FROM public.calculate_co2_result ccr
+                    WHERE ccr.serial_no::text = oo.serial_no::text
+                    LIMIT 1
+                ) co2_r ON true";
+        }
+
+        $joinPublic = "
+            LEFT JOIN public.oc_container oc ON oo.serial_no::text = oc.serial_no::text AND oo.order_from = 'public'";
+
+        $joinSfs = "
+            LEFT JOIN sfs.oc_container oc ON oo.serial_no::text = oc.serial_no::text AND oo.order_from = 'sfs'";
+
+        // 公共部分:JOIN 容器和 item
+        if ($needContainerData && $needItemData) {
+            $joinPublic = "
+            LEFT JOIN public.oc_container oc ON oo.serial_no::text = oc.serial_no::text AND oo.order_from = 'public'
+            LEFT JOIN public.oc_container_item oi ON oc.id = oi.oc_container_id";
+
+            $joinSfs = "
+                LEFT JOIN sfs.oc_container oc ON oo.serial_no::text = oc.serial_no::text AND oo.order_from = 'sfs'
+                LEFT JOIN sfs.oc_container_item oi ON oc.id = oi.oc_container_id";
+        }
+
+        $sql .= ",
+        vv_public AS (
+            SELECT 1
+            FROM oo 
+            {$joinPublic}
+            {$oeLateral}
+            {$co2Lateral}
+            <{ocItemSearchKLN}>
+        ),
+        vv_sfs AS (
+            SELECT 1
+            FROM oo 
+            {$joinSfs}
+            {$oeLateral}
+            {$co2Lateral}
+            <{ocItemSearchKLN}>
+        )
+        SELECT COUNT(*) FROM (
+            SELECT * FROM vv_public
+            UNION ALL
+            SELECT * FROM vv_sfs
+        ) vv  <{vvSearchKLN}>;";
+
+    return $sql;
+    }
 }
 ?>