印度仓的时效日报表

/*
 * Linux 自动任务
 * 印度仓的时效日报表
 *
 * 印度时间 2017-11-13 00:00:00 ~ 2017-11-13 23:59:59  对应北京时间 2017-11-13 02:30:00 ~ 2017-11-14 02:29:59
 * 印度时间 每天 08:00 统计数据,9:00 发邮件   对应北京时间 每天 10:30 统计数据,11:30 点发邮件
 */

require_once ('config.php');
$flagFile = dirname(__FILE__) . '/order-send-report';
if (@file_exists($flagFile)) {
    Common_Service_Common::autoRunFlag($flagFile, __FILE__, 0.5); //
    die("程序正在运行!");
}
$link = fopen($flagFile, 'wb');
fclose($link);
define('RUNTIME', '[' . date('Y-m-d H:i:s') . '] ');
echo RUNTIME . "Starting!\n";
set_time_limit(0);
ini_set('memory_limit', '-1');

try {
    $cooperaWarehouseId = Common_Service_CooperationAuthenticate::getCooperaTionWarehouseEx();
    if (empty($cooperaWarehouseId)) {
        throw new Exception('请先配置仓储认证.DownOrders');
    }
    if (count($cooperaWarehouseId) > 1) {
        throw new Exception('该系统存在多条仓库验证信息.请确认.DownOrders');
    }

    $stringtmp = '';
    if ($cooperaWarehouseId[0]['warehouse_id'] == 9) {
        $stringtmp = 'Delhi';
        $stringtmp2 = '德里';
        $mail_title = 'CFF India (Delhi) warehousing center daily order delivery report';
    } else if ($cooperaWarehouseId[0]['warehouse_id'] == 13) {
        $stringtmp = 'MEMBAI';
        $stringtmp2 = '孟买';
        $mail_title = 'CFF India(Mumbai) warehousing center daily order delivery report';
    } else {
        throw new Exception('该系统仓库验证信息有误.请确认.');
    }

    $warehouseLocal = array(0 => $cooperaWarehouseId[0]['warehouse_id']);
    $config = Common_Service_Config::getByAttribute('ORDER_SEND_MAIL_USER_' . $stringtmp, $warehouseLocal[0]);
    if (!$config || $config['config_value'] == '')
        throw new Exception('请配置ORDER_SEND_REPORT_MAIL_USER_' . $stringtmp . '项');
    $mailUser = explode(';', $config['config_value']);

    $config = Common_Service_Config::getByAttribute('ORDER_To_' . $stringtmp . '_From_CN', $warehouseLocal[0]);
    if (!$config || $config['config_value'] == '')
        throw new Exception('请配置ORDER_To_' . $stringtmp . '_From_CN项');
    $warehouseNotLocal = explode(',', $config['config_value']);

    $config = Common_Service_Config::getByAttribute('Shipmethod_To_' . $stringtmp . '_From_CN', $warehouseLocal[0]);
    if (!$config || $config['config_value'] == '')
        throw new Exception('请配置Shipmethod_To_' . $stringtmp . '_From_CN项');
    $shipping_method_array = explode(',', $config['config_value']);

    $warehouse = array_merge($warehouseLocal, $warehouseNotLocal);

    $unsendlist = Order_Service_OrderSendReport::countAndInsertData($warehouseLocal, $warehouseNotLocal, $shipping_method_array, date('Y-m-d', strtotime("-2 day")) . ' 18:30:00', date('Y-m-d', strtotime("-1 day")) . ' 18:30:00', date('Y-m-d', strtotime("-1 day")) . ' 11:30:00');

    //延迟 3 秒
    sleep(3);
    $date = date('Y-m-d', strtotime("-1 day"));
    $ym = date('Ym', strtotime("-1 day"));
    $combination = array(
        'start_date' => substr($date, 0, -2) . '01',
        'end_date' => $date,
        'warehouse_id' => $warehouse
    );
    $total = Order_Service_OrderSendReport::getByCondition($combination, 'count(*)');
    if ($total == 0)
        throw new Exception('没有数据');

    $rows = Order_Service_OrderSendReport::getByCondition($combination, '*');

    list($lists, $totals) = Order_Service_OrderSendReport::countData($rows, $warehouseLocal, $warehouseNotLocal);
    $list = $lists[$ym];
    $total = $totals[$ym];

    //下面中文表头
    $content = iconv("UTF-8", "GB2312", "日期,时间段,,STK订单(" . $stringtmp2 . "仓本地订单)除FBA订单以外,,,FBA订单(" . $stringtmp2 . "仓本地订单),,,已下架待打包(CNTOIN)以PDA收货时间为起始点 中国仓下架" . $stringtmp2 . "仓打包发货,,,当天交寄的本地订单和当天PDA收货的CNTOIN  的订单总和,,,交寄到CFF系统总订单,,16点前的订单已创建问题件的数量,16点前的订单待截单数量,16点前的订单发货数量,16点前的订单未发货数量,截单数量,及时发货率") . "\n";
    $content .= iconv("UTF-8", "GB2312", "日期,星期,前天16~昨天9(不含0、9点),昨天9~昨天16(含9、16点),前天16~昨天16,前天16~昨天9(不含0、9点),昨天9~昨天16(含9、16点),前天16~昨天16,前天16~昨天9(不含0、9点),昨天9~昨天16(含9、16点),前天16~昨天16,前天16~昨天9(不含0、9点),昨天9~昨天16(含9、16点),前天16~昨天16,前天16~昨天9(不含0、9点),昨天9~昨天16(含9、16点),前天16~昨天16,每天早上8点统计,每天早上8点统计,每天早上8点统计,每天早上8点统计,每天早上8点统计,16点前订单发货量/(总订单数-问题件数-待截单数)") . "\n";

    $data = "日期</td><td>星期</td><td>前天16~昨天9<br>不含16、<br>9点</td><td>昨天9~昨天16<br>含9<br>、16点</td><td>前天16~昨天16</td><td>前天16~昨天9<br>不含16、<br>9点</td><td>昨天9~昨天16<br>含9<br>、16点</td><td>前天16~昨天16</td><td>前天16~昨天9<br>不含16、<br>9点</td><td>昨天9~昨天16<br>含9<br>、16点</td><td>前天16~昨天16</td><td>前天16~昨天9<br>不含16、<br>9点</td><td>昨天9~昨天16<br>含9<br>、16点</td><td>前天16~昨天16</td><td>前天16~昨天9<br>不含16、<br>9点</td><td>昨天9~昨天16<br>含9<br>、16点</td><td>前天16~昨天16</td><td>每天早上<br>8点统计</td><td>每天早上<br>8点统计</td><td>每天早上<br>8点统计</td><td>每天早上<br>8点统计</td><td>每天早上<br>8点统计<br>(当天)</td><td width='105'>16点前订单发货量/<br>(总订单数-问题<br>件数-待截单数)";
    $content1 = '<style>.tab-report{width:1300px;border-top:1px solid #cccccc;border-left:1px solid #cccccc;font-size:12px} .tab-report td, .tab-report th{border-bottom:1px solid #cccccc;border-right:1px solid #cccccc; text-align:center;} .tab-report .yellow{background-color:yellow} .tab-report .blue{background-color:#82A3F8} .tab-report .orange{background-color:#E6F3F9} .tab-report .event-tr{background-color:#E6F3F9}</style>';
    $content1 .= '<table border="0" cellspacing="0" cellpadding="0" class="tab-report">';
    $content1 .= '<tr class="orange"><th>日期</th><th width="60">时间段</th><th colspan="3">STK订单(' . $stringtmp2 . '仓本地订单)<br>除FBA订单以外</th><th colspan="3">FBA订单(' . $stringtmp2 . '仓本地订单)</th><th colspan="3">已下架待打包(CNTOIN)<br>以PDA收货时间为起始点<br>中国仓下架' . $stringtmp2 . '仓打包发货</th><th colspan="3">当天交寄的本地订单和当天PDA收货的CNTOIN<br>的订单总和</th><th colspan="3">交寄到CFF系统总订单</th><th>16点前的订单已创建问题件数量<br>(当天)</th><th>16点前的订单待截单数量<br>(当天)</th><th>16点前的订单已发货数量<br>(当天)</th><th>16点前的订单未发货数量<br>(多天)</th><th>截单数量</th><th width="105">及时发货率<br>(当天)</th></tr>';
    $content1 .= '<tr><td>' . $data . '</td></tr>';

    //下面英文表头
    $content .= "DATE,Time period,,STK order (local order in " . $stringtmp . ") Except for the FBA order,,,FBA order (local order in " . $stringtmp . "),,,Package (CNTOIN) has been removed.The receiving time of PDA is the starting point,,,The order of the local order submitted on the current day and the CNTOIN order received on the same day PDA,,,Delivery to CFF system total order,,Error orders have been created before 16:00,Intercept order have been created before 16:00,Shipments Order have been created before 16:00,Not shipments Order have been created before 16:00 ,Prompt delivery rate\n";
    $content .= "DATE,week,the day before yesterday 16~yesterday 9(not contains 16、9 TIME),yesterday 9~yesterday 16(contains 9、16 TIME),the day before yesterday 16~yesterday 16,the day before yesterday 16~yesterday 9(not contains 16、9 TIME),yesterday 9~yesterday 16(contains 9、16 TIME),the day before yesterday 16~yesterday 16,the day before yesterday 16~yesterday 9(not contains 16、9 TIME),yesterday 9~yesterday 16(contains 9、16 TIME),the day before yesterday 16~yesterday 16,the day before yesterday 16~yesterday 9(not contains 16、9 TIME),yesterday 9~yesterday 16(contains 9、16 TIME),the day before yesterday 16~yesterday 16,the day before yesterday 16~yesterday 9(not contains 16、9 TIME),yesterday 9~yesterday 16(contains 9、16 TIME),the day before yesterday 16~yesterday 16,Statistics are at 8 o 'clock every morning,Statistics are at 8 o 'clock every morning,Statistics are at 8 o 'clock every morning,Statistics are at 8 o 'clock every morning,Statistics are at 8 o 'clock every morning,Local order before 16 o'clock and CNTOIN type order that PDA has received\n";

    $content1 .= '<tr class="orange"><th>DATE</th><th width="60">Time period</th><th colspan="3">STK order (local order in ' . $stringtmp . ')<br>Except for the FBA order</th><th colspan="3">FBA order (local order in ' . $stringtmp . ')</th><th colspan="3">Package (CNTOIN) has been removed.<br>The receiving time of PDA is the starting point</th><th colspan="3">The order of the local order <br>submitted on the current day and the<br> CNTOIN order received on the <br>same day PDA</th><th colspan="3">Delivery to CFF system total order</th><th>Error orders have been created before 16:00<br>(TODAY)</th><th>Intercept order have been created before 16:00<br>(TODAY)</th><th>Shipments Order have been created before 16:00<br>(TODAY)</th><th>Not shipments Order have been created before 16:00<br>(Many days)</th><th>intercept order QTY<br>(TODAY)</th><th width="105">Prompt delivery rate<br>(TODAY)</th></tr>';

    $content1 .= '<tr><td>' . "DATE</td><td>week</td><td>the day before yesterday 16~yesterday 9<br>(not contains 16、<br>9 TIME)</td><td>yesterday 9~yesterday 16<br>(contains 9、<br>16 TIME)</td><td>the day before yesterday 16~yesterday 16</td><td>the day before yesterday 16~yesterday9<br>(not contains 16、<br>9 TIME)</td><td>yesterday 9~yesterday 16<br>(contains 9、<br>16 TIME)</td><td>the day before yesterday 16~yesterday 16</td><td>the day before yesterday 16~yesterday 9<br>(not contains 16、<br>9 TIME)</td><td>yesterday 9~yesterday 16<br>(contains 9、<br>16 TIME)</td><td>the day before yesterday 16~yesterday 16</td><td>the day before yesterday 16~yesterday 9<br>(not contains 16、<br>9 TIME)</td><td>yesterday 9~yesterday 16<br>(contains 9、<br>16 TIME)</td><td>the day before yesterday 16~yesterday 16</td><td>the day before yesterday 16~yesterday 9<br>(not contains 16、<br>9 TIME)</td><td>yesterday 9~yesterday 16<br>(contains 9、<br>16 TIME)</td><td>the day before yesterday 16~yesterday 16</td><td>Statistics are at<br>8 o 'clock every morning</td><td>Statistics are at<br>8 o 'clock every morning</td><td>Statistics are at<br>8 o 'clock every morning</td><td>Statistics are at<br> 8 o 'clock every morning</td><td>Statistics are at<br> 8 o 'clock every morning</td><td width='105'>Local order before 16 o'clock and<br>CNTOIN type order that PDA has received" . '</td></tr>';
    $i = 0;
    foreach ($list as $date1 => $value) {
        $data = $date1 . '</td><td>' . $value['week_name'] . '</td><td>' . $value['STK01'][0] . '</td><td>' . $value['STK01'][1] . '</td><td>' . $value['STK01'][2] . '</td><td>' . $value['FBA'][0] . '</td><td>' . $value['FBA'][1] . '</td><td>' . $value['FBA'][2] . '</td><td>' . $value['CNTOIN'][0] . '</td><td>' . $value['CNTOIN'][1] . '</td><td>' . $value['CNTOIN'][2] . '</td><td>' . $value['total_cff1'][0] . '</td><td>' . $value['total_cff1'][1] . '</td><td>' . $value['total_cff1'][2] . '</td><td>' . $value['total_cff'][0] . '</td><td>' . $value['total_cff'][1] . '</td><td>' . $value['total_cff'][2] . '</td><td>' . $value['problem'] . '</td><td>' . $value['under'] . '</td><td>' . $value['sended'] . '</td><td>' . $value['unsend'] . '</td><td>' . $value['system_cutoff'] . '</td><td class="yellow">' . $value['rate'] . "%";
        $content .= iconv("UTF-8", "GB2312", str_replace('</td><td>', ',', str_replace(' class="yellow"', '', $data))) . "\n";
        $content1 .= '<tr class="' . ($i % 2 == 0 ? '' : 'event-tr') . '"><td>' . $data . '</td></tr>';
        $i++;
    }

    $data = '</td><td>合计</td><td>' . $total['STK01'][0] . '</td><td>' . $total['STK01'][1] . '</td><td>' . $total['STK01'][2] . '</td><td>' . $total['FBA'][0] . '</td><td>' . $total['FBA'][1] . '</td><td>' . $total['FBA'][2] . '</td><td>' . $total['CNTOIN'][0] . '</td><td>' . $total['CNTOIN'][1] . '</td><td>' . $total['CNTOIN'][2] . '</td><td>' . $total['total_cff1'][0] . '</td><td>' . $total['total_cff1'][1] . '</td><td>' . $total['total_cff1'][2] . '</td><td>' . $total['total_cff'][0] . '</td><td>' . $total['total_cff'][1] . '</td><td>' . $total['total_cff'][2] . '</td><td>' . $total['problem'] . '</td><td>' . $total['under'] . '</td><td>' . $total['sended'] . '</td><td>' . $total['unsend'] . '</td><td>' . $total['system_cutoff'] . '</td><td>';
    $content .= iconv("UTF-8", "GB2312", str_replace('</td><td>', ',', $data)) . "\n";
    $content1 .= '<tr height="26"><td>' . $data . '</td></tr>';

    $data = '</td><td>平均</td><td>' . $total['avg_STK01'][0] . '</td><td>' . $total['avg_STK01'][1] . '</td><td>' . $total['avg_STK01'][2] . '</td><td>' . $total['avg_FBA'][0] . '</td><td>' . $total['avg_FBA'][1] . '</td><td>' . $total['avg_FBA'][2] . '</td><td>' . $total['avg_CNTOIN'][0] . '</td><td>' . $total['avg_CNTOIN'][1] . '</td><td>' . $total['avg_CNTOIN'][2] . '</td><td>' . $total['avg_total_cff1'][0] . '</td><td>' . $total['avg_total_cff1'][1] . '</td><td>' . $total['avg_total_cff1'][2] . '</td><td>' . $total['avg_total_cff'][0] . '</td><td>' . $total['avg_total_cff'][1] . '</td><td>' . $total['avg_total_cff'][2] . '</td><td>' . $total['avg_problem'] . '</td><td>' . $total['avg_under'] . '</td><td>' . $total['avg_sended'] . '</td><td>' . $total['avg_unsend'] . '</td><td>' . $total['avg_system_cutoff'] . "</td><td class='yellow'>" . $total['avg'] . '%';
    $content .= iconv("UTF-8", "GB2312", str_replace('</td><td>', ',', str_replace(" class='yellow'", '', $data))) . "\n";
    $content1 .= '<tr height="26"><td>' . $data . '</td></tr></table>';

    //未发货订单报表
    if (!empty($unsendlist)) {
        $unsendContent = "Client ID,Order Number,Created Time,Submitted Time,Status, Shipped Warehouse, Shipping Method, System Forecast Weight, Status, Package Time, Packing Staff, Shipped Time, Shipping Staff, Whether Bag, Start Bagging Time, Confirm Bagging Time, Bagging Staff,\n";
        $status = array(0 => 'Unprocessed', 1 => 'Pending Off-Shelf', 2 => 'Off-Shelf in Progress', 3 => 'Off-Shelf', 4 => 'Pending Shipment', 5 => 'Shipped');
        $systemNewestStatus = array(
            0 => 'deleted',
            1 => 'draft',
            2 => 'confirmed',
            3 => 'submitted',
            4 => 'On Hold',
            5 => 'CFF-shipped',
            6 => 'SFC-shipped',
            7 => 'signed',
        );
        foreach ($unsendlist as $order) {
            $unsendContent .= $order['customer_id'] . ',' . $order['orders_code'] . ',' . $order['add_time'];
            $unsendContent .= ',' . $order['submit_time'];
            $unsendContent .= ',' . $status[$order['process_status']] . ($order['problem_status'] == 1 ? '-问题件' : '');
            $packageTime = $order['package_time'] == '0000-00-00 00:00:00' ? '' : $order['package_time'];
            $shipmentsTime = $order['ship_date'] == '0000-00-00 00:00:00' ? '' : $order['ship_date'];
            $unsendContent .= ',' . $order['warehouse_name']
                    . ',' . $order['shipping_method']
                    . ',' . $order['system_estimate_weight']
                    . ',' . $systemNewestStatus[$order['orders_status']]
                    . ',' . $packageTime
                    . ',' . $order['package_people_name']
                    . ',' . $shipmentsTime
                    . ',' . $order['shipments_member_name']
                    . ',' . $order['whether_bagging']
                    . ',' . $order['start_bagging_time']
                    . ',' . $order['notarize_bagging_time']
                    . ',' . $order['bagging_people_name']
                    . "\n";
        }
        $unsendContent = iconv("UTF-8", "GB2312", $unsendContent);
        $unsend_mail_subject = "CFF印度仓储中心未发货订单明细" . $date;
    }

    $mail_subject = $mail_title . "-" . $date;
    $mail = Cff::setupMail();
    $mail->setBodyHtml($content1);
    $mail->addTo($mailUser, $mail_subject);
    $mail->setSubject($mail_subject);
    $at = $mail->createAttachment($content);
    $at->type = 'application/vnd.ms-excel';
    $at->disposition = Zend_Mime::DISPOSITION_INLINE;
    $at->encoding = Zend_Mime::ENCODING_8BIT;
    $at->filename = iconv("UTF-8", "GB2312", 'Delivery schedule.csv');
    //未发货订单附件
    if (!empty($unsendlist)) {
        $at = $mail->createAttachment($unsendContent);
        $at->type = 'application/vnd.ms-excel';
        $at->disposition = Zend_Mime::DISPOSITION_INLINE;
        $at->encoding = Zend_Mime::ENCODING_8BIT;
        $at->filename = iconv("UTF-8", "GB2312", 'Not shipments Order (' . $date . ' before 16 o\'clock).csv');
    }
    $path = APPLICATION_PATH . "/../public/file/attachment/" . strtotime("now") . 'Not shipments Order (' . $date . ' before 16 o\'clock).csv';
    if ($path) {
        $handle = fopen($path, 'a');
        if ($handle) {
            fwrite($handle, $content);
            fclose($handle);
        }
    }
    if ($mail->send()) {
        if (is_array($mailUser)) {
            $mailUser = implode(';', $mailUser);
        }
        $combinat = array(
            'eq_to' => $mailUser,
            'eq_subject' => $mail_subject,
            'eq_body' => $content1,
            'eq_attachment' => $path,
            'eq_add_time' => date('Y-m-d H:i:s'),
            'eq_send_time' => date('Y-m-d H:i:s'),
            'eq_status' => 1
        );
        Common_Service_MailRecord::addMailRecord($combinat);
    }
} catch (Exception $e) {
    @unlink($flagFile);
    echo '[' . date('Y-m-d H:is') . ']出现异常,异常信息为:' . $e->getMessage() . '\r\n';
}
echo "[" . date('Y-m-d H:is') . "]结束运行\r\n";
@unlink($flagFile);



//Service
class Order_Service_OrderSendReport {
    /*
     * 统计订单数据并写入数据库
     * 
     * $start_time             0000-00-00 00:00:00        开始时间
     * $end_time               0000-00-00 00:00:00        结束时间
     */

    public static function countAndInsertData($warehouseLocal = array('9'), $warehouseNotLocal = array('11'), $shipping_method_array, $start_time, $end_time, $St_time) {
        $date = date('Y-m-d', strtotime($end_time));
        $warehouse = array_merge($warehouseLocal, $warehouseNotLocal);
        $count = Order_Service_OrderSendReport::getByCondition(array('osr_date' => $date, 'warehouse_id' => $warehouse), 'count(*)');

        if ($count > 0)
            return;

        //不统计FBA
        $combination = array(
            'dateType' => 'submit_time',
            'dateFrom' => $start_time,
            'dateTo' => $end_time,
            'orders_status' => array(0, 3, 5, 6, 7),
            'warehouse_id' => $warehouseLocal,
            'customer_id' => 'STK01',
            'shipping_method_not' => 'Self-Pickup'
        );
        $list = Order_Service_Order::getByConditionStatistic($combination, array('orders_code', 'customer_id', 'problem_status', 'underreview_status', 'process_status', 'submit_time', 'warehouse_id', 'orders_status', 'add_time', 'order_stop_date', 'ship_date', 'shipping_method', 'package_time', 'package_user_id', 'outbound_user_id'));
        if (!$list) {
            $list = array();
        }

        //只统计FBA
        $combinat = array(
            'dateType' => 'ship_time',
            'dateFrom' => $start_time,
            'dateTo' => $end_time,
            'orders_status' => array(0, 3, 5, 6, 7),
            'warehouse_id' => $warehouseLocal,
            'customer_id' => 'STK01',
            'shipping_method' => 'Self-Pickup'
        );
        $list2 = Order_Service_Order::getByConditionStatistic($combinat, array('orders_code', 'customer_id', 'problem_status', 'underreview_status', 'process_status', 'submit_time', 'warehouse_id', 'orders_status', 'add_time', 'order_stop_date', 'ship_date', 'shipping_method', 'package_time', 'package_user_id', 'outbound_user_id'));
        if ($list2) {
            foreach ($list2 as $key => $value) {
                $list2[$key]['submit_time'] = $value['ship_date'];
            }
        }

        $list = array_merge($list, $list2);
        foreach ($list as $key => $value) {
            //pickup 获取 FBA 订单数量 op_order_qty
            if ($value['shipping_method'] == 'Self-Pickup') {
                $condition_tmp = array('orders_code' => $value['orders_code']);
                $PickUpMap = Order_Service_OrderPickupMap::getByCondition($condition_tmp);
                if (!$PickUpMap) {
                    return;
                }
                $condition_tmp = array('op_code' => $PickUpMap[0]['op_code']);
                $PickUp = Order_Service_OrderPickup::getByCond($condition_tmp);
                if (!$PickUp) {
                    return;
                }
                $list[$key]['qty'] = $PickUp[0]['op_order_qty'];
            }
            $warehouseId = Warehouse_Service_Warehouse::getById($value['warehouse_id']);
            $list[$key]['warehouse_name'] = $warehouseId['warehouse_name'];
            $osIds = Order_Service_OrderShip::getByfield('orders_code', $value['orders_code']);
            $list[$key]['system_estimate_weight'] = $osIds['os_estimate_weight'] ? $osIds['os_estimate_weight'] : 0;
            if ($value['package_user_id']) {
                $userId = User_Service_User::getByUserId($value['package_user_id']);
                $list[$key]['package_people_name'] = $userId['name'];
            } else {
                $list[$key]['package_people_name'] = '';
            }
            if ($value['outbound_user_id']) {
                $userId = User_Service_User::getByUserId($value['outbound_user_id']);
                $list[$key]['shipments_member_name'] = $userId['name'];
            } else {
                $list[$key]['shipments_member_name'] = '';
            }
            $Object = new Order_Model_OrderPackage();
            $opIds = $Object->getByCondition(array('orders_code' => $value['orders_code']), '*');
            if ($opIds) {
                foreach ($opIds as $valu) {
                    $list[$key]['whether_bagging'] = 'Yes';
                    $list[$key]['start_bagging_time'] = $valu['opi_add_time'];
                    $list[$key]['notarize_bagging_time'] = $valu['opackage_update_time'];
                    $userId = User_Service_User::getByUserId($valu['user_id']);
                    $list[$key]['bagging_people_name'] = $userId['name'];
                }
            } else {
                $list[$key]['whether_bagging'] = 'NO';
                $list[$key]['start_bagging_time'] = '';
                $list[$key]['notarize_bagging_time'] = '';
                $list[$key]['bagging_people_name'] = '';
            }
        }

        $insertData = $submitArr = array();
        $sended = $total = $under = $undered = $problem = $unsend_orders = array();
        foreach ($list as $value) {
            //过滤不是已截单
            if ($value['orders_status'] == 0) {
                if ($value['process_status'] != 0 || $value['underreview_status'] != 3)
                    continue;
            }
            if ($value['shipping_method'] != 'Self-Pickup') {
                $value['shipping_method'] = 'other';
            } else {
                $value['shipping_method'] = 'FBA';
            }
            if (!isset($insertData[$value['customer_id']]) || !isset($insertData[$value['customer_id']][$value['warehouse_id']]) || !isset($insertData[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']])) {
                $insertData[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']] = array('osr_submit_count' => '', 'osr_sended_count' => '', 'osr_unsend_count' => 0, 'osr_under_count' => 0, 'osr_problem_count' => 0, 'osr_guest_cutoff_qty' => 0, 'osr_system_cutoff_qty' => 0);
                $submitArr[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']] = array();
            }

            $submitArr[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']] = self::getSubmitCount($value, $submitArr[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']]);

            //交寄的订单
            $insertData[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']]['osr_submit_count'] = serialize($submitArr[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']]);

            if (!isset($undered[$value['warehouse_id']]))
                $undered[$value['warehouse_id']] = 0;

            if (!isset($sended[$value['warehouse_id']]))
                $sended[$value['warehouse_id']] = 0;

            if (!isset($under[$value['warehouse_id']]))
                $under[$value['warehouse_id']] = 0;

            if (!isset($problem[$value['warehouse_id']]))
                $problem[$value['warehouse_id']] = 0;

            //截单订单
            if ($value['orders_status'] == 0) {
                if ($value['shipping_method'] != 'FBA') {
                    $insertData[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']]['osr_undered_count'] ++;
                    $undered[$value['warehouse_id']] ++;
                }
            //已发货订单
            } elseif ($value['orders_status'] == 6 || $value['orders_status'] == 7) {
                $insertData[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']]['osr_sended_count'] = self::getSubmitCount($value, $insertData[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']]['osr_sended_count']);
                if ($value['shipping_method'] == 'FBA') {
                    $sended[$value['warehouse_id']] = $sended[$value['warehouse_id']] + $value['qty'];
                } else {
                    $sended[$value['warehouse_id']] ++;
                }
            //待截单订单
            } elseif ($value['underreview_status'] == 3) {
                if ($value['shipping_method'] != 'FBA') {
                    $insertData[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']]['osr_under_count'] ++;
                    $under[$value['warehouse_id']] ++;
                }
            //问题件订单
            } elseif ($value['problem_status'] == 1) {
                if ($value['shipping_method'] != 'FBA') {
                    $insertData[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']]['osr_problem_count'] ++;
                    $problem[$value['warehouse_id']] ++;
                }
            //未发货
            } else {
                $insertData[$value['customer_id']][$value['warehouse_id']][$value['shipping_method']]['osr_unsend_count'] ++;
                $unsend_orders[] = $value;
            }

            if (!isset($total[$value['warehouse_id']]))
                $total[$value['warehouse_id']] = 0;
            if ($value['shipping_method'] == 'FBA') {
                $total[$value['warehouse_id']] = $total[$value['warehouse_id']] + $value['qty'];
            } else {
                $total[$value['warehouse_id']] ++;
            }
        }
        $is_native = 0;
        if ($insertData) {
            $is_native = 1;
        }

        //当天印度时间 16 点之前 PDA 收货的 CNTOIN 订单 list
        $objPbcode = new Order_Model_TransportDetail();
        //前天 18:30 ~ 昨天 11:30
        $Pbcode1 = $objPbcode->getByConditionbyAddtime($start_time, $St_time);
        //昨天 11:30 ~ 昨天 18:30
        $Pbcode2 = $objPbcode->getByConditionbyAddtime($St_time, $end_time);

        $objOrderShip = new Order_Model_OrderShip();
        $combineCode1 = $combineCode2 = array();
        $submitCount1 = $submitCount2 = $sendedCount = $unsendCount = $underCount = $problemCount = $underedCount = 0;

        //返回结果集的 tracking_number 作为 combineCode
        if ($Pbcode1) {
            $combineCode1 = $objOrderShip->getByOrderInfoNew($Pbcode1);
        }
        if ($Pbcode2) {
            $combineCode2 = $objOrderShip->getByOrderInfoNew($Pbcode2);
        }

        $combin = array(
            'orders_status' => array(0, 3, 5, 6, 7),
            'warehouse_id' => $warehouseNotLocal,
            'customer_id' => array('STK01')
        );
        if ($combineCode1) {
            $combineCodeTmp = array();
            foreach ($combineCode1 as $key => $value) {
                $combineCodeTmp[] = $value['tracking_number'];
            }
            $submitCount1 = $objOrderShip->CountByOsAndOrders($combineCodeTmp, $combin);
        }
        if ($combineCode2) {
            $combineCodeTmp = array();
            foreach ($combineCode2 as $key => $value) {
                $combineCodeTmp[] = $value['tracking_number'];
            }
            $submitCount2 = $objOrderShip->CountByOsAndOrders($combineCodeTmp, $combin);
        }
        $combineCode = array_merge($combineCode1, $combineCode2);
        if (count($combineCode) > 0) {
            $combineCodeTmp = array();
            foreach ($combineCode as $key => $value) {
                $combineCodeTmp[] = $value['tracking_number'];
            }
            $comb = array(
                'orders_status' => array(6, 7),
                'warehouse_id' => $warehouseNotLocal,
                'customer_id' => array('STK01'),
                'problem_status' => 0
            );
            $sendedCount = $objOrderShip->CountByOsAndOrders($combineCodeTmp, $comb);
            //CNTOIN 没有待截单
            $underCount = 0;

            $com = array(
                'orders_status' => array(3, 5, 6, 7),
                'warehouse_id' => $warehouseNotLocal,
                'customer_id' => array('STK01'),
                'problem_status' => 1
            );
            $problemCount = $objOrderShip->CountByOsAndOrders($combineCodeTmp, $com);

            $combination = array(
                'orders_status' => array(0),
                'warehouse_id' => $warehouseNotLocal,
                'customer_id' => array('STK01'),
                'underreview_status' => 3
            );
            $underedCount = $objOrderShip->CountByOsAndOrders($combineCodeTmp, $combination);

            if ($is_native == 1) {
                $undered[11] = $underedCount + $undered[$warehouseLocal[0]];
                $undered[$warehouseLocal[0]] = $undered[11];
            } else {
                $undered[11] = $underedCount;
            }
            if ($is_native == 1) {
                $under[11] = $under[$warehouseLocal[0]];
            } else {
                $under[11] = 0;
            }
            if ($is_native == 1) {
                $problem[11] = $problemCount + $problem[$warehouseLocal[0]];
                $problem[$warehouseLocal[0]] = $problem[11];
            } else {
                $problem[11] = $problemCount;
            }
            if ($is_native == 1) {
                $sended[11] = $sendedCount + $sended[$warehouseLocal[0]];
                $sended[$warehouseLocal[0]] = $sended[11];
            } else {
                $sended[11] = $sendedCount;
            }
            if ($is_native == 1) {
                $total[11] = $submitCount1 + $submitCount2 + $total[$warehouseLocal[0]];
                $total[$warehouseLocal[0]] = $total[11];
            } else {
                $total[11] = $submitCount1 + $submitCount2;
            }

            $insertData['STK01'][11]['CNTOIN'] = array('osr_submit_count' => '', 'osr_sended_count' => '', 'osr_unsend_count' => 0, 'osr_under_count' => 0, 'osr_problem_count' => 0, 'osr_guest_cutoff_qty' => 0, 'osr_system_cutoff_qty' => 0);

            $timetmp1 = "1" . date('His', strtotime("-1 hour", strtotime($St_time)));
            $timetmp2 = "1" . date('His', strtotime("+1 hour", strtotime($St_time)));

            $insertData['STK01'][11]['CNTOIN']['osr_submit_count'] = serialize(array($timetmp1 => $submitCount1, $timetmp2 => $submitCount2));
            $insertData['STK01'][11]['CNTOIN']['osr_sended_count'] = array($timetmp1 => $sendedCount);
            $insertData['STK01'][11]['CNTOIN']['osr_unsend_count'] = 0;
            $insertData['STK01'][11]['CNTOIN']['osr_under_count'] = $underCount;
            $insertData['STK01'][11]['CNTOIN']['osr_problem_count'] = $problemCount;
        }

        $is_CNTOIN = 0;
        if ($insertData['STK01'][11]['CNTOIN']) {
            $is_CNTOIN = 1;
        }
        if (count($insertData) == 0) {
            return;
        }

        //CNTOIN 多日未发货
        $CNTOIN_unsend = array();
        $combinat = array(
            'orders_status' => array(3, 5),
            'warehouse_id' => $warehouseNotLocal,
            'customer_id' => array('STK01'),
            'shipping_method' => $shipping_method_array,
            'problem_status' => 0,
            'underreview_status' => 0,
            'is_AOG_not' => 1,
            'dateType' => 'submit_time',
            'dateFrom' => '2018-01-01 00:00:00'
        );
        $CNTOIN_unsend = Order_Service_Order::getByConditionStatistic($combinat, array('orders_code', 'customer_id', 'problem_status', 'underreview_status', 'process_status', 'submit_time', 'warehouse_id', 'orders_status', 'add_time', 'order_stop_date', 'ship_date', 'shipping_method'));

        if ($CNTOIN_unsend && $is_CNTOIN == 0) {
            $insertData['STK01'][11]['CNTOIN'] = array('osr_submit_count' => '', 'osr_sended_count' => '', 'osr_unsend_count' => 0, 'osr_under_count' => 0, 'osr_problem_count' => 0, 'osr_guest_cutoff_qty' => 0, 'osr_system_cutoff_qty' => 0);
            $insertData['STK01'][11]['CNTOIN']['osr_unsend_count'] = count($CNTOIN_unsend);
            $undered[11] = $undered[$warehouseLocal[0]];
            $under[11] = $under[$warehouseLocal[0]];
            $problem[11] = $problem[$warehouseLocal[0]];
            $sended[11] = $sended[$warehouseLocal[0]];
            $total[11] = $total[$warehouseLocal[0]];
        }

        //查询本地是否有未发订单
        $combin = array(
            'submitTimeLt' => $start_time,
            'submit_time_gt' => '2018-01-01 00:00:00',
            'orders_status' => array(3, 5),
            'problem_status' => 0,
            'underreview_status' => 0,
            'warehouse_id' => $warehouseLocal,
            'customer_id' => 'STK01'
        );
        $native_unsend = self::countUnsendOrders($combin);
        if ($is_native == 0 && $native_unsend) {
            $insertData['STK01'][$warehouseLocal[0]]['other'] = array('osr_submit_count' => '', 'osr_sended_count' => '', 'osr_unsend_count' => 0, 'osr_under_count' => 0, 'osr_problem_count' => 0, 'osr_guest_cutoff_qty' => 0, 'osr_system_cutoff_qty' => 0);
            $insertData['STK01'][$warehouseLocal[0]]['FBA'] = array('osr_submit_count' => '', 'osr_sended_count' => '', 'osr_unsend_count' => 0, 'osr_under_count' => 0, 'osr_problem_count' => 0, 'osr_guest_cutoff_qty' => 0, 'osr_system_cutoff_qty' => 0);
            $undered[$warehouseLocal[0]] = $undered[11];
            $under[$warehouseLocal[0]] = $under[11];
            $problem[$warehouseLocal[0]] = $problem[11];
            $sended[$warehouseLocal[0]] = $sended[11];
            $total[$warehouseLocal[0]] = $total[11];
        }

        //api 连接深圳主系统,获取客户当天交寄到 CFF 的订单
        $cobj = new Common_Service_CooperationAuthenticateProccess($warehouseLocal[0]);
        $comb = array(
            'dateFrom' => $start_time,
            'dateTo' => $end_time,
            'Sttime' => $St_time,
            'warehouseid' => $warehouseLocal[0],
            'warehouseNotLocal' => $warehouseNotLocal,
            'shippingmethodarray' => $shipping_method_array
        );
        $result = $cobj->GetCntoinOrdersNum($comb);

        $timetmp1 = "1" . date('His', strtotime("-1 hour", strtotime($St_time)));
        $timetmp2 = "1" . date('His', strtotime("+1 hour", strtotime($St_time)));

        if ($result['status'] == 1) {
            //num1:前 16 ~ 昨 9 点交寄数量
            //num2:昨 9 ~ 昨 16 点后交寄数量
            $insertData['STK01'][11]['GoingToSendIndia'] = array('osr_submit_count' => '', 'osr_sended_count' => '', 'osr_unsend_count' => 0, 'osr_under_count' => 0, 'osr_problem_count' => 0, 'osr_guest_cutoff_qty' => 0, 'osr_system_cutoff_qty' => 0);

            $insertData['STK01'][11]['GoingToSendIndia']['osr_submit_count'] = serialize(array($timetmp1 => $result['data']['cntoin_submit_sz']['num1'], $timetmp2 => $result['data']['cntoin_submit_sz']['num2']));

            if (!isset($undered[11])) {
                $undered[11] = $undered[$warehouseLocal[0]];
            }
            if (!isset($under[11])) {
                $under[11] = $under[$warehouseLocal[0]];
            }
            if (!isset($problem[11])) {
                $problem[11] = $problem[$warehouseLocal[0]];
            }
            if (!isset($sended[11])) {
                $sended[11] = $sended[$warehouseLocal[0]];
            }
            if (!isset($total[11])) {
                $total[11] = $total[$warehouseLocal[0]];
            }
        }

        //统计截单数量
        $com = array(
            'dateType' => 'order_stop_date',
            'dateFrom' => $start_time,
            'dateTo' => $end_time,
            'warehouse_id' => $warehouse,
            'customer_id' => 'STK01',
            'shipping_method_not' => 'Self-Pickup',
            'underreview_status' => 3
        );
        $list1 = Order_Service_Order::getByConditionStatistic($com, array('customer_id', 'problem_status', 'underreview_status', 'process_status', 'submit_time', 'warehouse_id', 'orders_status', 'orders_code', 'add_time', 'shipping_method'));
        if ($list1) {
            $osr_system_cutoff_qty = 0;
            $osr_guest_cutoff_qty = 0;
            foreach ($list1 as $lv) {
                $osr_system_cutoff_qty++;
            }
            foreach ($insertData as $customer => $value) {
                foreach ($value as $wh => $cvalue) {
                    foreach ($cvalue as $sh => $v) {
                        $insertData[$customer][$wh][$sh]['osr_system_cutoff_qty'] = $osr_system_cutoff_qty;
                        $insertData[$customer][$wh][$sh]['osr_guest_cutoff_qty'] = $osr_guest_cutoff_qty;
                    }
                }
            }
        }

        //昨天之前未发货的订单 印度本地
        $combination = array(
            'submitTimeLt' => $start_time,
            'submit_time_gt' => '2018-01-01 00:00:00',
            'orders_status' => array(3, 5),
            'problem_status' => 0,
            'underreview_status' => 0,
            'warehouse_id' => $warehouseLocal
        );
        $unsendOrders = !empty($unsend_orders) ? $unsend_orders : array();
        foreach ($insertData as $customer => $value) {
            foreach ($value as $wh => $cvalue) {
                foreach ($cvalue as $sh => $v) {
                    $combination['customer_id'] = $customer;
                    $combination['warehouse_id'] = $wh;
                    $combination['shipping_method'] = $sh;
                    if ($combination['shipping_method'] == 'CNTOIN') {
                        $v['osr_unsend_count'] = count($CNTOIN_unsend);
                    } elseif ($combination['shipping_method'] == 'GoingToSendIndia') {
                        $v['osr_unsend_count'] = 0;
                    } else {
                        $unsendlist = self::countUnsendOrders($combination);
                        $v['osr_unsend_count'] += $unsendlist ? count($unsendlist) : 0;
                    }
                    $v['customer_id'] = $customer;
                    $v['warehouse_id'] = $wh;
                    $v['shipping_method'] = $sh;
                    $send_count = serialize($v['osr_sended_count']);
                    $v['osr_sended_count'] = '';
                    $v['osr_sended_count'] = $send_count;
                    $v['osr_date'] = $date;
                    if ($total[$wh] == 0) {
                        $v['osr_send_rate'] = 0;
                    } else {
                        $v['osr_send_rate'] = round($sended[$wh] * 100 / ($total[$wh] - $under[$wh] - $problem[$wh] - $undered[$wh]), 2);
                    }
                    self::add($v);
                    if ($unsendlist) {
                        $unsendOrders = array_merge($unsendOrders, $unsendlist);
                    }
                }
            }
        }
        if (count($CNTOIN_unsend) > 0) {
            $unsendOrders = array_merge($unsendOrders, $CNTOIN_unsend);
        }
        return $unsendOrders;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值